src / generator.ts

import { type Chat, type GeneratorController, type InferParsedConfig } from "@lmstudio/sdk";
import OpenAI from "openai";
import {
  type ChatCompletionMessageParam,
  type ChatCompletionMessageToolCall,
  type ChatCompletionTool,
  type ChatCompletionToolMessageParam,
} from "openai/resources/index";
import { CUSTOM_MODEL_VALUE, configSchematics, globalConfigSchematics } from "./config";

/* -------------------------------------------------------------------------- */
/*                                   Types                                    */
/* -------------------------------------------------------------------------- */

type ToolCallState = {
  id: string;
  name: string | null;
  index: number;
  arguments: string;
};

type Route = {
  providerName: string;
  baseURL: string;
  apiKeyField: "openaiApiKey" | "anthropicApiKey" | "deepseekApiKey" | "glmApiKey" | "customApiKey";
};

/* -------------------------------------------------------------------------- */
/*                               Build helpers                                */
/* -------------------------------------------------------------------------- */

/** Build a pre-configured OpenAI client. */
function createOpenAI(
  globalConfig: InferParsedConfig<typeof globalConfigSchematics>,
  route: Route,
) {
  const overrideBaseUrl = String(globalConfig.get("overrideBaseUrl") || "").trim();
  const baseURL = overrideBaseUrl || route.baseURL;
  if (!baseURL) throw new Error("Missing Base URL. Set Override Base URL for custom models.");

  const apiKey = String(globalConfig.get(route.apiKeyField) || "").trim();
  if (!apiKey) throw new Error(`Missing ${route.providerName} API key.`);

  return new OpenAI({
    apiKey,
    baseURL,
  });
}

function resolveRoute(model: string): Route {
  if (model.startsWith("claude-")) {
    return {
      providerName: "Anthropic",
      baseURL: "https://api.anthropic.com/v1",
      apiKeyField: "anthropicApiKey",
    };
  }

  if (model.startsWith("gpt-")) {
    return {
      providerName: "OpenAI",
      baseURL: "https://api.openai.com/v1",
      apiKeyField: "openaiApiKey",
    };
  }

  if (model.startsWith("deepseek-")) {
    return {
      providerName: "Deepseek",
      baseURL: "https://api.deepseek.com/v1",
      apiKeyField: "deepseekApiKey",
    };
  }

  if (model.startsWith("glm-")) {
    return {
      providerName: "GLM",
      baseURL: "https://api.z.ai/api/paas/v4",
      apiKeyField: "glmApiKey",
    };
  }

  return {
    providerName: "Custom",
    baseURL: "",
    apiKeyField: "customApiKey",
  };
}

function resolveModel(config: InferParsedConfig<typeof configSchematics>) {
  const selectedModel = String(config.get("model") || "").trim();
  if (selectedModel && selectedModel !== CUSTOM_MODEL_VALUE) return selectedModel;

  const customModel = String(config.get("customModel") || "").trim();
  if (customModel) return customModel;

  throw new Error("Missing custom model. Select Use Custom Model and fill Custom Model.");
}

function resolveCustomRoute(
  config: InferParsedConfig<typeof configSchematics>,
  globalConfig: InferParsedConfig<typeof globalConfigSchematics>,
) {
  const selectedModel = String(config.get("model") || "").trim();
  if (selectedModel !== CUSTOM_MODEL_VALUE) return resolveRoute(selectedModel);

  const overrideBaseUrl = String(globalConfig.get("overrideBaseUrl") || "").trim();
  if (!overrideBaseUrl) {
    throw new Error("Missing Base URL. Override Base URL is required when Model is Use Custom Model.");
  }

  return resolveRoute(CUSTOM_MODEL_VALUE);
}

/** Convert internal chat history to the format expected by OpenAI. */
function toOpenAIMessages(history: Chat): ChatCompletionMessageParam[] {
  const messages: ChatCompletionMessageParam[] = [];

  for (const message of history) {
    switch (message.getRole()) {
      case "system":
        messages.push({ role: "system", content: message.getText() });
        break;

      case "user":
        messages.push({ role: "user", content: message.getText() });
        break;

      case "assistant": {
        const toolCalls: ChatCompletionMessageToolCall[] = message
          .getToolCallRequests()
          .map(toolCall => ({
            id: toolCall.id ?? "",
            type: "function",
            function: {
              name: toolCall.name,
              arguments: JSON.stringify(toolCall.arguments ?? {}),
            },
          }));

        messages.push({
          role: "assistant",
          content: message.getText(),
          ...(toolCalls.length ? { tool_calls: toolCalls } : {}),
        });
        break;
      }

      case "tool": {
        message.getToolCallResults().forEach(toolCallResult => {
          messages.push({
            role: "tool",
            tool_call_id: toolCallResult.toolCallId ?? "",
            content: toolCallResult.content,
          } as ChatCompletionToolMessageParam);
        });
        break;
      }
    }
  }

  return messages;
}

/** Convert LM Studio tool definitions to OpenAI function-tool descriptors. */
function toOpenAITools(ctl: GeneratorController): ChatCompletionTool[] | undefined {
  const tools = ctl.getToolDefinitions().map<ChatCompletionTool>(t => ({
    type: "function",
    function: {
      name: t.function.name,
      description: t.function.description,
      parameters: t.function.parameters ?? {},
    },
  }));
  return tools.length ? tools : undefined;
}

/* -------------------------------------------------------------------------- */
/*                            Stream-handling utils                           */
/* -------------------------------------------------------------------------- */

function wireAbort(ctl: GeneratorController, stream: { controller: AbortController }) {
  ctl.onAborted(() => {
    console.info("Generation aborted by user.");
    stream.controller.abort();
  });
}

async function consumeStream(stream: AsyncIterable<any>, ctl: GeneratorController) {
  let current: ToolCallState | null = null;

  function maybeFlushCurrentToolCall() {
    if (current === null || current.name === null) {
      return;
    }
    ctl.toolCallGenerationEnded({
      type: "function",
      name: current.name,
      arguments: JSON.parse(current.arguments),
      id: current.id,
    });
    current = null;
  }

  for await (const chunk of stream) {
    console.info("Received chunk:", JSON.stringify(chunk));
    const delta = chunk.choices?.[0]?.delta as
      | {
          content?: string;
          tool_calls?: Array<{
            index: number;
            id?: string;
            function?: { name?: string; arguments?: string };
          }>;
        }
      | undefined;

    if (!delta) continue;

    /* Text streaming */
    if (delta.content) {
      ctl.fragmentGenerated(delta.content);
    }

    /* Tool-call streaming */
    for (const toolCall of delta.tool_calls ?? []) {
      if (toolCall.id !== undefined) {
        maybeFlushCurrentToolCall();
        current = { id: toolCall.id, name: null, index: toolCall.index, arguments: "" };
        ctl.toolCallGenerationStarted();
      }

      if (toolCall.function?.name && current) {
        current.name = toolCall.function.name;
        ctl.toolCallGenerationNameReceived(toolCall.function.name);
      }

      if (toolCall.function?.arguments && current) {
        current.arguments += toolCall.function.arguments;
        ctl.toolCallGenerationArgumentFragmentGenerated(toolCall.function.arguments);
      }
    }

    /* Finalize tool call */
    if (chunk.choices?.[0]?.finish_reason === "tool_calls" && current?.name) {
      maybeFlushCurrentToolCall();
    }
  }

  console.info("Generation completed.");
}

/* -------------------------------------------------------------------------- */
/*                                     API                                    */
/* -------------------------------------------------------------------------- */

export async function generate(ctl: GeneratorController, history: Chat) {
  const config = ctl.getPluginConfig(configSchematics);
  const globalConfig = ctl.getGlobalPluginConfig(globalConfigSchematics);
  const model = resolveModel(config);
  const route = resolveCustomRoute(config, globalConfig);

  /* 1. Setup client & payload */
  const openai = createOpenAI(globalConfig, route);
  const messages = toOpenAIMessages(history);
  const tools = toOpenAITools(ctl);

  /* 2. Kick off streaming completion */
  const stream = await openai.chat.completions.create({
    model: model,
    messages,
    tools,
    stream: true,
  });

  /* 3. Abort wiring & stream processing */
  wireAbort(ctl, stream as any);
  await consumeStream(stream as any, ctl);
}