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