@agentic-kit/openai 1.0.3 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +120 -2
- package/esm/index.js +625 -82
- package/esm/package.json +1 -0
- package/index.d.ts +205 -25
- package/index.js +627 -87
- package/package.json +10 -5
package/esm/index.js
CHANGED
|
@@ -1,97 +1,640 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
1
|
+
// Use the runtime's native fetch. Node 18.17+ (engine requirement),
|
|
2
|
+
// browsers, Bun, and Deno all provide it with a Web ReadableStream body —
|
|
3
|
+
// which is what SSE parsing here requires.
|
|
4
|
+
const fetch = globalThis.fetch.bind(globalThis);
|
|
5
|
+
class EventStream {
|
|
6
|
+
isTerminal;
|
|
7
|
+
extractResult;
|
|
8
|
+
queue = [];
|
|
9
|
+
waiting = [];
|
|
10
|
+
done = false;
|
|
11
|
+
finalResultPromise;
|
|
12
|
+
resolveFinalResult;
|
|
13
|
+
constructor(isTerminal, extractResult) {
|
|
14
|
+
this.isTerminal = isTerminal;
|
|
15
|
+
this.extractResult = extractResult;
|
|
16
|
+
this.finalResultPromise = new Promise((resolve) => {
|
|
17
|
+
this.resolveFinalResult = resolve;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
push(event) {
|
|
21
|
+
if (this.done) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (this.isTerminal(event)) {
|
|
25
|
+
this.done = true;
|
|
26
|
+
this.resolveFinalResult(this.extractResult(event));
|
|
27
|
+
}
|
|
28
|
+
const waiter = this.waiting.shift();
|
|
29
|
+
if (waiter) {
|
|
30
|
+
waiter({ value: event, done: false });
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
this.queue.push(event);
|
|
34
|
+
}
|
|
35
|
+
end(result) {
|
|
36
|
+
this.done = true;
|
|
37
|
+
if (result !== undefined) {
|
|
38
|
+
this.resolveFinalResult(result);
|
|
39
|
+
}
|
|
40
|
+
while (this.waiting.length > 0) {
|
|
41
|
+
this.waiting.shift()({ value: undefined, done: true });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async *[Symbol.asyncIterator]() {
|
|
45
|
+
while (true) {
|
|
46
|
+
if (this.queue.length > 0) {
|
|
47
|
+
yield this.queue.shift();
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (this.done) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const next = await new Promise((resolve) => {
|
|
54
|
+
this.waiting.push(resolve);
|
|
55
|
+
});
|
|
56
|
+
if (next.done) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
yield next.value;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
result() {
|
|
63
|
+
return this.finalResultPromise;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
class DefaultAssistantMessageEventStream extends EventStream {
|
|
67
|
+
constructor() {
|
|
68
|
+
super((event) => event.type === 'done' || event.type === 'error', (event) => {
|
|
69
|
+
if (event.type === 'done') {
|
|
70
|
+
return event.message;
|
|
71
|
+
}
|
|
72
|
+
if (event.type === 'error') {
|
|
73
|
+
return event.error;
|
|
74
|
+
}
|
|
75
|
+
throw new Error('Unexpected terminal event');
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export const OPENAI_COMPATIBLE_MODELS = [
|
|
80
|
+
{
|
|
81
|
+
id: 'gpt-5.4',
|
|
82
|
+
name: 'GPT-5.4',
|
|
83
|
+
api: 'openai-compatible',
|
|
84
|
+
provider: 'openai',
|
|
85
|
+
baseUrl: 'https://api.openai.com/v1',
|
|
86
|
+
input: ['text', 'image'],
|
|
87
|
+
reasoning: true,
|
|
88
|
+
tools: true,
|
|
89
|
+
contextWindow: 1050000,
|
|
90
|
+
maxOutputTokens: 128000,
|
|
91
|
+
cost: { input: 2.4, output: 19.2, cacheRead: 0, cacheWrite: 0 },
|
|
92
|
+
compat: {
|
|
93
|
+
maxTokensField: 'max_completion_tokens',
|
|
94
|
+
reasoningFormat: 'openai',
|
|
95
|
+
supportsReasoningEffort: true,
|
|
96
|
+
supportsStrictToolSchema: true,
|
|
97
|
+
supportsUsageInStreaming: true,
|
|
98
|
+
toolCallIdFormat: 'passthrough',
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
id: 'gpt-5.4-mini',
|
|
103
|
+
name: 'GPT-5.4 Mini',
|
|
104
|
+
api: 'openai-compatible',
|
|
105
|
+
provider: 'openai',
|
|
106
|
+
baseUrl: 'https://api.openai.com/v1',
|
|
107
|
+
input: ['text', 'image'],
|
|
108
|
+
reasoning: true,
|
|
109
|
+
tools: true,
|
|
110
|
+
contextWindow: 1050000,
|
|
111
|
+
maxOutputTokens: 128000,
|
|
112
|
+
cost: { input: 0.4, output: 1.6, cacheRead: 0, cacheWrite: 0 },
|
|
113
|
+
compat: {
|
|
114
|
+
maxTokensField: 'max_completion_tokens',
|
|
115
|
+
reasoningFormat: 'openai',
|
|
116
|
+
supportsReasoningEffort: true,
|
|
117
|
+
supportsStrictToolSchema: true,
|
|
118
|
+
supportsUsageInStreaming: true,
|
|
119
|
+
toolCallIdFormat: 'passthrough',
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
id: 'gpt-5.4-nano',
|
|
124
|
+
name: 'GPT-5.4 Nano',
|
|
125
|
+
api: 'openai-compatible',
|
|
126
|
+
provider: 'openai',
|
|
127
|
+
baseUrl: 'https://api.openai.com/v1',
|
|
128
|
+
input: ['text', 'image'],
|
|
129
|
+
reasoning: true,
|
|
130
|
+
tools: true,
|
|
131
|
+
contextWindow: 1050000,
|
|
132
|
+
maxOutputTokens: 128000,
|
|
133
|
+
cost: { input: 0.2, output: 1.25, cacheRead: 0, cacheWrite: 0 },
|
|
134
|
+
compat: {
|
|
135
|
+
maxTokensField: 'max_completion_tokens',
|
|
136
|
+
reasoningFormat: 'openai',
|
|
137
|
+
supportsReasoningEffort: true,
|
|
138
|
+
supportsStrictToolSchema: true,
|
|
139
|
+
supportsUsageInStreaming: true,
|
|
140
|
+
toolCallIdFormat: 'passthrough',
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
];
|
|
3
144
|
export class OpenAIAdapter {
|
|
4
|
-
|
|
145
|
+
api = 'openai-compatible';
|
|
146
|
+
provider;
|
|
147
|
+
name;
|
|
5
148
|
apiKey;
|
|
6
149
|
baseUrl;
|
|
7
|
-
|
|
150
|
+
compat;
|
|
151
|
+
defaultHeaders;
|
|
152
|
+
defaultInput;
|
|
8
153
|
defaultMaxTokens;
|
|
154
|
+
defaultModel;
|
|
155
|
+
defaultReasoning;
|
|
156
|
+
defaultTools;
|
|
157
|
+
defaultContextWindow;
|
|
9
158
|
constructor(options) {
|
|
10
|
-
const
|
|
11
|
-
this.apiKey =
|
|
12
|
-
this.baseUrl =
|
|
13
|
-
this.
|
|
14
|
-
this.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
159
|
+
const normalized = typeof options === 'string' ? { apiKey: options } : options ?? {};
|
|
160
|
+
this.apiKey = normalized.apiKey;
|
|
161
|
+
this.baseUrl = normalizeBaseUrl(normalized.baseUrl ?? 'https://api.openai.com/v1');
|
|
162
|
+
this.provider = normalized.provider ?? 'openai';
|
|
163
|
+
this.name = this.provider;
|
|
164
|
+
this.defaultHeaders = normalized.headers;
|
|
165
|
+
this.defaultInput = normalized.defaultInput ?? ['text', 'image'];
|
|
166
|
+
this.defaultMaxTokens = normalized.maxTokens ?? 4096;
|
|
167
|
+
this.defaultModel = normalized.defaultModel ?? 'gpt-5.4-mini';
|
|
168
|
+
this.defaultReasoning = normalized.reasoning ?? false;
|
|
169
|
+
this.defaultTools = normalized.tools ?? true;
|
|
170
|
+
this.defaultContextWindow = normalized.contextWindow;
|
|
171
|
+
this.compat = {
|
|
172
|
+
maxTokensField: 'max_tokens',
|
|
173
|
+
reasoningFormat: 'openai',
|
|
174
|
+
supportsReasoningEffort: true,
|
|
175
|
+
supportsStrictToolSchema: true,
|
|
176
|
+
supportsUsageInStreaming: true,
|
|
177
|
+
toolCallIdFormat: 'passthrough',
|
|
178
|
+
...(normalized.compat ?? {}),
|
|
179
|
+
};
|
|
18
180
|
}
|
|
19
|
-
|
|
20
|
-
|
|
181
|
+
createModel(modelId, overrides) {
|
|
182
|
+
const builtIn = OPENAI_COMPATIBLE_MODELS.find((model) => model.provider === this.provider && model.id === modelId);
|
|
183
|
+
if (builtIn) {
|
|
184
|
+
return {
|
|
185
|
+
...builtIn,
|
|
186
|
+
baseUrl: this.baseUrl,
|
|
187
|
+
headers: { ...(builtIn.headers ?? {}), ...(this.defaultHeaders ?? {}), ...(overrides?.headers ?? {}) },
|
|
188
|
+
compat: { ...(builtIn.compat ?? {}), ...(this.compat ?? {}), ...(overrides?.compat ?? {}) },
|
|
189
|
+
...overrides,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
id: modelId,
|
|
194
|
+
name: modelId,
|
|
195
|
+
api: this.api,
|
|
196
|
+
provider: this.provider,
|
|
197
|
+
baseUrl: this.baseUrl,
|
|
198
|
+
input: this.defaultInput,
|
|
199
|
+
reasoning: this.defaultReasoning,
|
|
200
|
+
tools: this.defaultTools,
|
|
201
|
+
contextWindow: this.defaultContextWindow,
|
|
202
|
+
maxOutputTokens: overrides?.maxOutputTokens ?? this.defaultMaxTokens,
|
|
203
|
+
headers: { ...(this.defaultHeaders ?? {}), ...(overrides?.headers ?? {}) },
|
|
204
|
+
compat: { ...this.compat, ...(overrides?.compat ?? {}) },
|
|
205
|
+
...overrides,
|
|
206
|
+
};
|
|
21
207
|
}
|
|
22
208
|
async listModels() {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
209
|
+
if (!this.apiKey) {
|
|
210
|
+
return OPENAI_COMPATIBLE_MODELS.filter((model) => model.provider === this.provider);
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
214
|
+
headers: this.buildHeaders(),
|
|
215
|
+
});
|
|
216
|
+
if (!response.ok) {
|
|
217
|
+
throw new Error(`OpenAI listModels failed: ${response.status}`);
|
|
218
|
+
}
|
|
219
|
+
const payload = (await response.json());
|
|
220
|
+
return payload.data?.map((model) => model.id) ?? [];
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return OPENAI_COMPATIBLE_MODELS.filter((model) => model.provider === this.provider);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
stream(model, context, options) {
|
|
227
|
+
const stream = new DefaultAssistantMessageEventStream();
|
|
228
|
+
const output = createAssistantMessage(model);
|
|
229
|
+
void (async () => {
|
|
230
|
+
let textIndex;
|
|
231
|
+
let thinkingIndex;
|
|
232
|
+
const toolIndexMap = new Map();
|
|
233
|
+
let doneReason = 'stop';
|
|
234
|
+
try {
|
|
235
|
+
const body = buildRequestBody(model, context, {
|
|
236
|
+
...options,
|
|
237
|
+
maxTokens: options?.maxTokens ?? model.maxOutputTokens ?? this.defaultMaxTokens,
|
|
238
|
+
});
|
|
239
|
+
options?.onPayload?.(body);
|
|
240
|
+
const response = await fetch(`${model.baseUrl}/chat/completions`, {
|
|
241
|
+
method: 'POST',
|
|
242
|
+
headers: this.buildHeaders(model, options),
|
|
243
|
+
body: JSON.stringify(body),
|
|
244
|
+
signal: options?.signal,
|
|
245
|
+
});
|
|
246
|
+
if (!response.ok) {
|
|
247
|
+
const text = await response.text().catch(() => '');
|
|
248
|
+
throw new Error(`OpenAI error ${response.status}: ${text}`);
|
|
249
|
+
}
|
|
250
|
+
stream.push({ type: 'start', partial: clone(output) });
|
|
251
|
+
const reader = response.body?.getReader();
|
|
252
|
+
if (!reader) {
|
|
253
|
+
throw new Error('No response body');
|
|
254
|
+
}
|
|
255
|
+
const decoder = new TextDecoder();
|
|
256
|
+
let buffer = '';
|
|
257
|
+
while (true) {
|
|
258
|
+
const { done, value } = await reader.read();
|
|
259
|
+
if (done) {
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
buffer += decoder.decode(value, { stream: true });
|
|
263
|
+
const lines = buffer.split('\n');
|
|
264
|
+
buffer = lines.pop() ?? '';
|
|
265
|
+
for (const line of lines) {
|
|
266
|
+
const trimmed = line.trim();
|
|
267
|
+
if (!trimmed.startsWith('data:')) {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const payload = trimmed.slice(5).trim();
|
|
271
|
+
if (!payload) {
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (payload === '[DONE]') {
|
|
275
|
+
emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
|
|
276
|
+
calculateUsageCost(model, output.usage);
|
|
277
|
+
stream.push({ type: 'done', reason: doneReason, message: clone(output) });
|
|
278
|
+
stream.end(output);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const chunk = JSON.parse(payload);
|
|
282
|
+
if (chunk.usage) {
|
|
283
|
+
applyUsage(output.usage, model, chunk.usage);
|
|
284
|
+
}
|
|
285
|
+
const choice = chunk.choices?.[0];
|
|
286
|
+
if (!choice) {
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (choice.finish_reason === 'length') {
|
|
290
|
+
doneReason = 'length';
|
|
291
|
+
output.stopReason = 'length';
|
|
292
|
+
}
|
|
293
|
+
else if (choice.finish_reason === 'tool_calls' || choice.finish_reason === 'function_call') {
|
|
294
|
+
doneReason = 'toolUse';
|
|
295
|
+
output.stopReason = 'toolUse';
|
|
296
|
+
}
|
|
297
|
+
const delta = choice.delta ?? {};
|
|
298
|
+
const reasoningDelta = firstNonEmpty(delta.reasoning_content, delta.reasoning, delta.reasoning_text) ?? '';
|
|
299
|
+
if (reasoningDelta) {
|
|
300
|
+
if (thinkingIndex === undefined) {
|
|
301
|
+
thinkingIndex = output.content.push({ type: 'thinking', thinking: '' }) - 1;
|
|
302
|
+
stream.push({
|
|
303
|
+
type: 'thinking_start',
|
|
304
|
+
contentIndex: thinkingIndex,
|
|
305
|
+
partial: clone(output),
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
const block = output.content[thinkingIndex];
|
|
309
|
+
block.thinking += reasoningDelta;
|
|
310
|
+
stream.push({
|
|
311
|
+
type: 'thinking_delta',
|
|
312
|
+
contentIndex: thinkingIndex,
|
|
313
|
+
delta: reasoningDelta,
|
|
314
|
+
partial: clone(output),
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
if (typeof delta.content === 'string' && delta.content.length > 0) {
|
|
318
|
+
if (textIndex === undefined) {
|
|
319
|
+
textIndex = output.content.push({ type: 'text', text: '' }) - 1;
|
|
320
|
+
stream.push({
|
|
321
|
+
type: 'text_start',
|
|
322
|
+
contentIndex: textIndex,
|
|
323
|
+
partial: clone(output),
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
const block = output.content[textIndex];
|
|
327
|
+
block.text += delta.content;
|
|
328
|
+
stream.push({
|
|
329
|
+
type: 'text_delta',
|
|
330
|
+
contentIndex: textIndex,
|
|
331
|
+
delta: delta.content,
|
|
332
|
+
partial: clone(output),
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
for (const toolDelta of delta.tool_calls ?? []) {
|
|
336
|
+
const toolIndex = toolDelta.index ?? 0;
|
|
337
|
+
let contentIndex = toolIndexMap.get(toolIndex);
|
|
338
|
+
if (contentIndex === undefined) {
|
|
339
|
+
contentIndex =
|
|
340
|
+
output.content.push({
|
|
341
|
+
type: 'toolCall',
|
|
342
|
+
id: toolDelta.id ?? `tool_${toolIndex}`,
|
|
343
|
+
name: toolDelta.function?.name ?? '',
|
|
344
|
+
arguments: {},
|
|
345
|
+
rawArguments: '',
|
|
346
|
+
}) - 1;
|
|
347
|
+
toolIndexMap.set(toolIndex, contentIndex);
|
|
348
|
+
stream.push({
|
|
349
|
+
type: 'toolcall_start',
|
|
350
|
+
contentIndex,
|
|
351
|
+
partial: clone(output),
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
const block = output.content[contentIndex];
|
|
355
|
+
if (toolDelta.id) {
|
|
356
|
+
block.id = toolDelta.id;
|
|
357
|
+
}
|
|
358
|
+
if (toolDelta.function?.name) {
|
|
359
|
+
block.name = toolDelta.function.name;
|
|
360
|
+
}
|
|
361
|
+
if (toolDelta.function?.arguments) {
|
|
362
|
+
block.rawArguments = `${block.rawArguments ?? ''}${toolDelta.function.arguments}`;
|
|
363
|
+
block.arguments = parsePartialJson(block.rawArguments);
|
|
364
|
+
stream.push({
|
|
365
|
+
type: 'toolcall_delta',
|
|
366
|
+
contentIndex,
|
|
367
|
+
delta: toolDelta.function.arguments,
|
|
368
|
+
partial: clone(output),
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
|
|
375
|
+
calculateUsageCost(model, output.usage);
|
|
376
|
+
stream.push({ type: 'done', reason: doneReason, message: clone(output) });
|
|
377
|
+
stream.end(output);
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
|
|
381
|
+
output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
|
|
382
|
+
output.errorMessage = error instanceof Error ? error.message : String(error);
|
|
383
|
+
calculateUsageCost(model, output.usage);
|
|
384
|
+
stream.push({
|
|
385
|
+
type: 'error',
|
|
386
|
+
reason: output.stopReason === 'aborted' ? 'aborted' : 'error',
|
|
387
|
+
error: clone(output),
|
|
388
|
+
});
|
|
389
|
+
stream.end(output);
|
|
390
|
+
}
|
|
391
|
+
})();
|
|
392
|
+
return stream;
|
|
393
|
+
}
|
|
394
|
+
buildHeaders(model, options) {
|
|
395
|
+
const apiKey = options?.apiKey ?? this.apiKey;
|
|
396
|
+
return {
|
|
397
|
+
'Content-Type': 'application/json',
|
|
398
|
+
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
|
399
|
+
...(this.defaultHeaders ?? {}),
|
|
400
|
+
...(model?.headers ?? {}),
|
|
401
|
+
...(options?.headers ?? {}),
|
|
33
402
|
};
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
function buildRequestBody(model, context, options) {
|
|
406
|
+
const compat = model.compat ?? {};
|
|
407
|
+
const messages = [
|
|
408
|
+
...(context.systemPrompt
|
|
409
|
+
? [
|
|
410
|
+
{
|
|
411
|
+
role: 'system',
|
|
412
|
+
content: context.systemPrompt,
|
|
413
|
+
},
|
|
414
|
+
]
|
|
415
|
+
: []),
|
|
416
|
+
...context.messages.map((message) => toOpenAIMessage(message, compat)),
|
|
417
|
+
];
|
|
418
|
+
const body = {
|
|
419
|
+
model: model.id,
|
|
420
|
+
messages,
|
|
421
|
+
stream: true,
|
|
422
|
+
};
|
|
423
|
+
const maxTokensField = compat.maxTokensField ?? 'max_tokens';
|
|
424
|
+
if (options?.maxTokens !== undefined) {
|
|
425
|
+
body[maxTokensField] = options.maxTokens;
|
|
426
|
+
}
|
|
427
|
+
if (options?.temperature !== undefined) {
|
|
428
|
+
body.temperature = options.temperature;
|
|
429
|
+
}
|
|
430
|
+
if ((compat.supportsUsageInStreaming ?? true) === true) {
|
|
431
|
+
body.stream_options = { include_usage: true };
|
|
432
|
+
}
|
|
433
|
+
if (model.reasoning && compat.reasoningFormat === 'openai' && compat.supportsReasoningEffort !== false && options?.reasoning) {
|
|
434
|
+
body.reasoning_effort = options.reasoning;
|
|
435
|
+
}
|
|
436
|
+
if (context.tools && context.tools.length > 0) {
|
|
437
|
+
body.tools = context.tools.map((tool) => ({
|
|
438
|
+
type: 'function',
|
|
439
|
+
function: {
|
|
440
|
+
name: tool.name,
|
|
441
|
+
description: tool.description,
|
|
442
|
+
parameters: tool.parameters,
|
|
443
|
+
...(compat.supportsStrictToolSchema ? { strict: true } : {}),
|
|
39
444
|
},
|
|
40
|
-
|
|
445
|
+
}));
|
|
446
|
+
}
|
|
447
|
+
return body;
|
|
448
|
+
}
|
|
449
|
+
function toOpenAIMessage(message, compat) {
|
|
450
|
+
if (message.role === 'user') {
|
|
451
|
+
return {
|
|
452
|
+
role: 'user',
|
|
453
|
+
content: typeof message.content === 'string'
|
|
454
|
+
? message.content
|
|
455
|
+
: message.content.map((block) => block.type === 'text'
|
|
456
|
+
? { type: 'text', text: block.text }
|
|
457
|
+
: {
|
|
458
|
+
type: 'image_url',
|
|
459
|
+
image_url: {
|
|
460
|
+
url: `data:${block.mimeType};base64,${block.data}`,
|
|
461
|
+
},
|
|
462
|
+
}),
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
if (message.role === 'toolResult') {
|
|
466
|
+
const content = message.content
|
|
467
|
+
.map((block) => block.type === 'text' ? block.text : `[image:${block.mimeType};bytes=${block.data.length}]`)
|
|
468
|
+
.join('\n');
|
|
469
|
+
return {
|
|
470
|
+
role: 'tool',
|
|
471
|
+
tool_call_id: message.toolCallId,
|
|
472
|
+
content,
|
|
473
|
+
...(compat.requiresToolResultName ? { name: message.toolName } : {}),
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
const content = message.content
|
|
477
|
+
.filter((block) => block.type === 'text' || block.type === 'thinking')
|
|
478
|
+
.map((block) => (block.type === 'text' ? block.text : `<thinking>${block.thinking}</thinking>`))
|
|
479
|
+
.join('\n');
|
|
480
|
+
const toolCalls = message.content
|
|
481
|
+
.filter((block) => block.type === 'toolCall')
|
|
482
|
+
.map((block) => ({
|
|
483
|
+
id: block.id,
|
|
484
|
+
type: 'function',
|
|
485
|
+
function: {
|
|
486
|
+
name: block.name,
|
|
487
|
+
arguments: block.rawArguments ?? JSON.stringify(block.arguments),
|
|
488
|
+
},
|
|
489
|
+
}));
|
|
490
|
+
return {
|
|
491
|
+
role: 'assistant',
|
|
492
|
+
content: content.length > 0 ? content : null,
|
|
493
|
+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function createAssistantMessage(model) {
|
|
497
|
+
return {
|
|
498
|
+
role: 'assistant',
|
|
499
|
+
api: model.api,
|
|
500
|
+
provider: model.provider,
|
|
501
|
+
model: model.id,
|
|
502
|
+
content: [],
|
|
503
|
+
usage: {
|
|
504
|
+
input: 0,
|
|
505
|
+
output: 0,
|
|
506
|
+
cacheRead: 0,
|
|
507
|
+
cacheWrite: 0,
|
|
508
|
+
totalTokens: 0,
|
|
509
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
510
|
+
},
|
|
511
|
+
stopReason: 'stop',
|
|
512
|
+
timestamp: Date.now(),
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
function calculateUsageCost(model, usage) {
|
|
516
|
+
usage.cost.input = ((model.cost?.input ?? 0) / 1_000_000) * usage.input;
|
|
517
|
+
usage.cost.output = ((model.cost?.output ?? 0) / 1_000_000) * usage.output;
|
|
518
|
+
usage.cost.cacheRead = ((model.cost?.cacheRead ?? 0) / 1_000_000) * usage.cacheRead;
|
|
519
|
+
usage.cost.cacheWrite = ((model.cost?.cacheWrite ?? 0) / 1_000_000) * usage.cacheWrite;
|
|
520
|
+
usage.cost.total =
|
|
521
|
+
usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
522
|
+
}
|
|
523
|
+
function applyUsage(usage, model, payload) {
|
|
524
|
+
const cachedTokens = payload.prompt_tokens_details?.cached_tokens ?? 0;
|
|
525
|
+
const reasoningTokens = payload.completion_tokens_details?.reasoning_tokens ?? 0;
|
|
526
|
+
usage.input = (payload.prompt_tokens ?? 0) - cachedTokens;
|
|
527
|
+
usage.output = (payload.completion_tokens ?? 0) + reasoningTokens;
|
|
528
|
+
usage.cacheRead = cachedTokens;
|
|
529
|
+
usage.cacheWrite = 0;
|
|
530
|
+
usage.totalTokens = payload.total_tokens ?? usage.input + usage.output + usage.cacheRead;
|
|
531
|
+
calculateUsageCost(model, usage);
|
|
532
|
+
}
|
|
533
|
+
function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinkingIndex) {
|
|
534
|
+
const textBlock = textIndex !== undefined ? message.content[textIndex] : undefined;
|
|
535
|
+
if (textIndex !== undefined && textBlock) {
|
|
536
|
+
stream.push({
|
|
537
|
+
type: 'text_end',
|
|
538
|
+
contentIndex: textIndex,
|
|
539
|
+
content: textBlock.text,
|
|
540
|
+
partial: clone(message),
|
|
41
541
|
});
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
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
|
-
|
|
542
|
+
}
|
|
543
|
+
const thinkingBlock = thinkingIndex !== undefined ? message.content[thinkingIndex] : undefined;
|
|
544
|
+
if (thinkingIndex !== undefined && thinkingBlock) {
|
|
545
|
+
stream.push({
|
|
546
|
+
type: 'thinking_end',
|
|
547
|
+
contentIndex: thinkingIndex,
|
|
548
|
+
content: thinkingBlock.thinking,
|
|
549
|
+
partial: clone(message),
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
for (const contentIndex of toolIndexMap.values()) {
|
|
553
|
+
const toolCall = message.content[contentIndex];
|
|
554
|
+
if (!toolCall) {
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
toolCall.arguments = parsePartialJson(toolCall.rawArguments ?? '');
|
|
558
|
+
stream.push({
|
|
559
|
+
type: 'toolcall_end',
|
|
560
|
+
contentIndex,
|
|
561
|
+
toolCall: clone(toolCall),
|
|
562
|
+
partial: clone(message),
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
function normalizeBaseUrl(baseUrl) {
|
|
567
|
+
const trimmed = baseUrl.replace(/\/+$/, '');
|
|
568
|
+
if (/\/v\d+$/.test(trimmed)) {
|
|
569
|
+
return trimmed;
|
|
570
|
+
}
|
|
571
|
+
return `${trimmed}/v1`;
|
|
572
|
+
}
|
|
573
|
+
function parsePartialJson(raw) {
|
|
574
|
+
const trimmed = raw.trim();
|
|
575
|
+
if (!trimmed) {
|
|
576
|
+
return {};
|
|
577
|
+
}
|
|
578
|
+
try {
|
|
579
|
+
return JSON.parse(trimmed);
|
|
580
|
+
}
|
|
581
|
+
catch {
|
|
582
|
+
// continue
|
|
583
|
+
}
|
|
584
|
+
const completed = completePartialJson(trimmed);
|
|
585
|
+
if (!completed) {
|
|
586
|
+
return {};
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
return JSON.parse(completed);
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
return {};
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
function completePartialJson(input) {
|
|
596
|
+
let output = input;
|
|
597
|
+
let inString = false;
|
|
598
|
+
let escaping = false;
|
|
599
|
+
const stack = [];
|
|
600
|
+
for (const char of input) {
|
|
601
|
+
if (escaping) {
|
|
602
|
+
escaping = false;
|
|
603
|
+
continue;
|
|
94
604
|
}
|
|
605
|
+
if (char === '\\') {
|
|
606
|
+
escaping = true;
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
if (char === '"') {
|
|
610
|
+
inString = !inString;
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
if (inString) {
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
if (char === '{') {
|
|
617
|
+
stack.push('}');
|
|
618
|
+
}
|
|
619
|
+
else if (char === '[') {
|
|
620
|
+
stack.push(']');
|
|
621
|
+
}
|
|
622
|
+
else if (char === '}' || char === ']') {
|
|
623
|
+
stack.pop();
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (inString) {
|
|
627
|
+
output += '"';
|
|
628
|
+
}
|
|
629
|
+
while (stack.length > 0) {
|
|
630
|
+
output += stack.pop();
|
|
95
631
|
}
|
|
632
|
+
return output;
|
|
633
|
+
}
|
|
634
|
+
function clone(value) {
|
|
635
|
+
return JSON.parse(JSON.stringify(value));
|
|
636
|
+
}
|
|
637
|
+
function firstNonEmpty(...values) {
|
|
638
|
+
return values.find((value) => typeof value === 'string' && value.length > 0);
|
|
96
639
|
}
|
|
97
640
|
export default OpenAIAdapter;
|