openai-compat-endpoint

Public

src / config.ts

import { createConfigSchematics } from "@lmstudio/sdk";
import { readCachedState } from "./modelCache";

// This file contains the definition of configuration schematics for your plugin.

export const placeholderModelValue = "__set_base_url__";
const placeholderOption = {
  value: placeholderModelValue,
  displayName: "Set base URL to load models",
};

function normalizeModelOptions(models: string[]) {
  const seen = new Set<string>();
  const options = [];
  for (const model of models) {
    if (!model || seen.has(model)) continue;
    seen.add(model);
    options.push({ value: model, displayName: model });
  }
  return options;
}

function buildConfigSchematics(models: string[], defaultModel?: string) {
  const options = normalizeModelOptions(models);
  const allOptions = [placeholderOption, ...options];
  const resolvedDefault =
    defaultModel &&
    allOptions.some(option => option.value === defaultModel)
      ? defaultModel
      : options[0]?.value ?? placeholderModelValue;

  return createConfigSchematics()
    .field(
      "model",
      "select",
      {
        displayName: "Model",
        subtitle: "Select the model to use for generation.",
        options: allOptions,
      },
      resolvedDefault,
    )
    .build();
}

export let configSchematics = buildConfigSchematics([], "");

export function updateModelOptions(models: string[], defaultModel?: string) {
  configSchematics = buildConfigSchematics(models, defaultModel);
  return configSchematics;
}

export function loadConfigSchematicsFromCache() {
  const cachedState = readCachedState();
  const cachedLastSelected =
    cachedState.lastSelected && cachedState.lastSelected !== placeholderModelValue
      ? cachedState.lastSelected
      : undefined;
  const initialModels = cachedLastSelected
    ? [cachedLastSelected, ...cachedState.models.filter(id => id !== cachedLastSelected)]
    : cachedState.models;
  return updateModelOptions(initialModels, cachedLastSelected ?? "");
}

export const globalConfigSchematics = createConfigSchematics()
  .field(
    "openaiApiKey",
    "string",
    {
      displayName: "OpenAI API Key",
      isProtected: true,
      placeholder: "sk-...",
    },
    "",
  )
  .field(
    "overrideBaseUrl",
    "string",
    {
      displayName: "(Optional) Override Base URL",
      subtitle: "Override the base URL for API calls. Leave empty to let the plugin guess the base URL.",
      placeholder: "https://api.example.com/v1",
    },
    "",
  )
  .build();