client.ts 4.1 KB
import { ChatOpenAI, type ChatOpenAIFields } from '@langchain/openai';
import type { BaseMessage } from '@langchain/core/messages';
import { getBuiltinDefaultConfig, getDefaultModelConfig } from './config.js';
import type { AiModelConfig, CompleteChatOptions } from './types.js';

/**
 * `ChatOpenAIFields` plus the pass-through keys this client forwards verbatim.
 *
 * `maxRetries` is not modelled by `@langchain/openai` v1's field type, but the
 * underlying client still honours it, so it is declared here rather than
 * silently dropped (the engine relies on it for its short-timeout retry).
 */
type ChatRequestConfig = ChatOpenAIFields & { maxRetries?: number };

/**
 * Merge the three config layers (per-call override > caller default > built-in)
 * into one concrete identity, and fail loudly when the result cannot possibly
 * reach an endpoint. Nothing is read from disk or env at this point.
 */
function resolveConfig(opts: CompleteChatOptions): AiModelConfig {
    const userSet = getDefaultModelConfig();
    const base = userSet ?? getBuiltinDefaultConfig();
    const override = opts.config;

    const merged: AiModelConfig = {
        modelName: override?.modelName ?? base.modelName,
        apiKey: override?.apiKey ?? base.apiKey,
        baseUrl: override?.baseUrl ?? base.baseUrl,
        temperature: override?.temperature ?? base.temperature,
        maxTokens: override?.maxTokens ?? base.maxTokens,
    };

    if (!merged.modelName || !merged.apiKey) {
        throw new Error(
            '[ai-client] resolved config is missing modelName or apiKey. Pass opts.config, call setDefaultModelConfig(...), or edit the module default-config.ts.'
        );
    }

    return merged;
}

/**
 * Normalise whatever the transport hands back into a plain string.
 * Kept defensive on purpose: providers differ in whether they return a bare
 * string, an array of text parts, or an array of objects with a `text` field.
 */
function extractText(content: unknown): string {
    if (typeof content === 'string') return content;
    if (Array.isArray(content)) {
        return content
            .map((part: unknown) => {
                if (typeof part === 'string') return part;
                if (part && typeof part === 'object' && 'text' in part) {
                    return String((part as { text: unknown }).text);
                }
                return '';
            })
            .join('');
    }
    return content == null ? '' : String(content);
}

/**
 * Send a list of chat messages to an OpenAI-compatible endpoint and return the
 * model's text reply.
 *
 * This is the only public surface with business-agnostic I/O:
 *   input  = messages (caller builds them) + transport options
 *   output = model text (string)
 *
 * No logging, no file IO, no global config files. Any vendor extension
 * (reasoning toggle, custom sampling, ...) goes through `modelKwargs` and is
 * forwarded verbatim — the client never learns what it means.
 */
export async function completeChat(messages: BaseMessage[], opts: CompleteChatOptions = {}): Promise<string> {
    const cfg = resolveConfig(opts);

    const requestConfig: ChatRequestConfig = {
        modelName: cfg.modelName,
        apiKey: cfg.apiKey,
        temperature: opts.temperature ?? cfg.temperature ?? 0.1,
    };

    if (cfg.baseUrl) {
        requestConfig.configuration = { baseURL: cfg.baseUrl };
    }
    if (opts.maxTokens ?? cfg.maxTokens) {
        requestConfig.maxTokens = opts.maxTokens ?? cfg.maxTokens;
    }
    if (opts.timeout !== undefined) {
        requestConfig.timeout = opts.timeout;
    }
    if (opts.maxRetries !== undefined) {
        requestConfig.maxRetries = opts.maxRetries;
    }
    if (opts.streaming) {
        requestConfig.streaming = true;
    }

    const modelKwargs: Record<string, unknown> = { ...(opts.modelKwargs ?? {}) };
    if (opts.responseFormat) {
        modelKwargs.response_format = opts.responseFormat;
    }
    if (Object.keys(modelKwargs).length > 0) {
        requestConfig.modelKwargs = modelKwargs;
    }

    const model = new ChatOpenAI(requestConfig);
    const message = await model.invoke(messages);
    return extractText(message.content);
}