client.ts
4.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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);
}