@lostgradient/operative-openai 0.0.0-stage → 0.1.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/dist/openai.js ADDED
@@ -0,0 +1,440 @@
1
+ import { parseOpenAIToolCalls } from 'armorer';
2
+ import { toOpenAIMessagesGrouped } from 'conversationalist';
3
+ import { concatenateTextParts, isProviderContractError, ProviderError, resolveCommonParameters, ToolCallParseError, withBackendDescriptors, withInputLineage, } from '@lostgradient/operative/provider-kit';
4
+ import { openAIRows, resolveOpenAIEffort, resolveOpenAIModel } from "./openai-catalog.js";
5
+ import { mapOpenAIMessage, mergeAssembledField } from "./openai-parts.js";
6
+ import { toOpenAIResponseFormat } from "./openai-response-format.js";
7
+ import { toOpenAIToolChoice } from "./openai-tool-choice.js";
8
+ /**
9
+ * Narrow a non-streaming response's tool calls to function entries. A
10
+ * `type: 'custom'` entry has no `function`, which armorer's parser cannot
11
+ * read, so it is rejected with a clear message rather than an accidental
12
+ * `TypeError`. Runs inside the caller's `try`, so the `catch` wraps it.
13
+ */
14
+ function requireFunctionToolCalls(toolCalls) {
15
+ if (!toolCalls)
16
+ return undefined;
17
+ const functionCalls = [];
18
+ for (const call of toolCalls) {
19
+ if (call.type !== 'function') {
20
+ throw new Error(`OpenAI returned a custom tool call (id "${call.id}"); only function tool calls are supported`);
21
+ }
22
+ functionCalls.push(call);
23
+ }
24
+ return functionCalls;
25
+ }
26
+ /**
27
+ * Build a provider-neutral {@link TokenUsage} from an OpenAI `usage` payload.
28
+ *
29
+ * OpenAI's `prompt_tokens` INCLUDES cached tokens — `prompt_tokens_details.
30
+ * cached_tokens` is a subset of it, not a disjoint bucket like Anthropic's
31
+ * cache fields. To keep `TokenUsage.prompt` meaning "fresh, non-cached input"
32
+ * across providers, cached tokens are subtracted out of `prompt` here.
33
+ * `cacheReadTokens` is only set when the API actually reported the field —
34
+ * never fabricated as `0`. OpenAI has no cache-write counterpart, so
35
+ * `cacheCreationTokens` is always absent for this provider.
36
+ *
37
+ * `prompt` is clamped at `0`: a malformed or inconsistent response (e.g.
38
+ * `cached_tokens` exceeding `prompt_tokens`, or `prompt_tokens` missing while
39
+ * `cached_tokens` is present) must never surface as a negative prompt count,
40
+ * which would violate `TokenUsage`'s non-negative contract and corrupt any
41
+ * downstream cost estimate.
42
+ */
43
+ function buildOpenAIUsage(usage) {
44
+ const promptTokens = usage.prompt_tokens ?? 0;
45
+ const cachedTokens = usage.prompt_tokens_details?.cached_tokens;
46
+ return {
47
+ prompt: cachedTokens !== undefined ? Math.max(promptTokens - cachedTokens, 0) : promptTokens,
48
+ completion: usage.completion_tokens ?? 0,
49
+ total: usage.total_tokens ?? promptTokens + (usage.completion_tokens ?? 0),
50
+ ...(cachedTokens !== undefined ? { cacheReadTokens: cachedTokens } : {}),
51
+ };
52
+ }
53
+ /**
54
+ * The single `BackendDescriptor` (AB-64 AC2) matching `model` on the
55
+ * `'chat.completions'` endpoint, from the static seed catalog — zero or one
56
+ * entries, never fabricated. `baseURL` is threaded through so a custom
57
+ * endpoint reads as `endpointAmbiguous` and reports no descriptor for a
58
+ * `chat.completions`-shaped model that may not really be OpenAI's own,
59
+ * exactly as `createModelCatalog`'s own `endpointAmbiguous` rule already
60
+ * does for `getProviderCapabilities`.
61
+ */
62
+ function openAIDescriptorsFor(model, baseURL) {
63
+ return openAIRows({ baseURL }).filter((descriptor) => descriptor.provider === 'openai' && descriptor.model === model);
64
+ }
65
+ /**
66
+ * Creates a GenerateFunction backed by the OpenAI Chat Completions API.
67
+ *
68
+ * When no `client` is provided, dynamically imports `openai`
69
+ * and constructs one using `apiKey` or the `OPENAI_API_KEY` env var.
70
+ * The optional `baseURL` enables LM Studio, Ollama, Groq, etc.
71
+ *
72
+ * Note: "Provider" here is distinct from the Vercel AI SDK's concept of
73
+ * "provider". This factory returns a `GenerateFunction` — a plain async
74
+ * function that produces a `GenerateResponse` — not an SDK provider object.
75
+ */
76
+ export function createOpenAIProvider(options) {
77
+ const { baseURL } = options;
78
+ const resolvedModel = resolveOpenAIModel(options.model);
79
+ const resolvedEffort = options.effort
80
+ ? resolveOpenAIEffort(options.effort, resolvedModel)
81
+ : undefined;
82
+ const common = resolveCommonParameters(options);
83
+ let clientPromise;
84
+ function getClient() {
85
+ if (options.client)
86
+ return Promise.resolve(options.client);
87
+ if (!clientPromise) {
88
+ clientPromise = import('openai').then((module) => {
89
+ const OpenAI = module.default ?? module.OpenAI;
90
+ const clientOptions = {};
91
+ if (options.apiKey)
92
+ clientOptions['apiKey'] = options.apiKey;
93
+ if (baseURL)
94
+ clientOptions['baseURL'] = baseURL;
95
+ return new OpenAI(clientOptions);
96
+ });
97
+ }
98
+ return clientPromise;
99
+ }
100
+ const generate = async (context) => {
101
+ // The step's steered effort, read per call (COR-1935), not the construction-time one. A model
102
+ // that takes no `reasoning_effort` resolves it to `undefined`: the parameter is omitted, and
103
+ // the response's `effectiveEffort` says `'none'`.
104
+ const stepEffort = context.steering?.effort === undefined
105
+ ? resolvedEffort
106
+ : resolveOpenAIEffort(context.steering.effort, resolvedModel);
107
+ const client = await getClient();
108
+ const { messages, lineage } = toOpenAIMessagesGrouped(context.conversation.current, {
109
+ sources: context.resolvedSources,
110
+ });
111
+ const tools = await context.toolbox.toOpenAITools();
112
+ const hasTools = tools.length > 0;
113
+ const params = {
114
+ model: resolvedModel,
115
+ messages,
116
+ };
117
+ const effectiveMaxTokens = context.maximumTokens ?? common.maximumTokens;
118
+ if (effectiveMaxTokens !== undefined)
119
+ params['max_tokens'] = effectiveMaxTokens;
120
+ if (stepEffort !== undefined)
121
+ params['reasoning_effort'] = stepEffort;
122
+ if (hasTools && options.toolChoice !== 'none')
123
+ params['tools'] = tools;
124
+ if (hasTools && options.toolChoice && options.toolChoice !== 'none')
125
+ params['tool_choice'] = toOpenAIToolChoice(options.toolChoice);
126
+ // Construction-time `options.responseFormat` (an explicit caller
127
+ // override) wins when set; otherwise fall back to the per-run
128
+ // `context.responseFormat` the loop derives from `RunOptions.output`
129
+ // (AB-18), so a run's `output` schema reaches the wire without every
130
+ // caller having to re-derive and pass it at provider construction.
131
+ const responseFormat = options.responseFormat ?? context.responseFormat;
132
+ if (responseFormat) {
133
+ const adapted = toOpenAIResponseFormat(responseFormat);
134
+ if (adapted !== undefined)
135
+ params['response_format'] = adapted;
136
+ }
137
+ if (options.requestMetadata)
138
+ params['metadata'] = options.requestMetadata;
139
+ if (common.temperature !== undefined)
140
+ params['temperature'] = common.temperature;
141
+ if (common.topP !== undefined)
142
+ params['top_p'] = common.topP;
143
+ if (common.stopSequences)
144
+ params['stop'] = common.stopSequences;
145
+ // The signal goes in the SDK's request options, never the body — a body
146
+ // `signal` is serialized away and the request outlives `run.abort()`.
147
+ const requestOptions = context.signal ? { signal: context.signal } : undefined;
148
+ try {
149
+ const response = await client.chat.completions.create(params, requestOptions);
150
+ const choice = response.choices[0];
151
+ const usage = response.usage ? buildOpenAIUsage(response.usage) : undefined;
152
+ // Every message field is a part, metadata or a typed error: nothing the model returned vanishes.
153
+ const mapped = mapOpenAIMessage(choice?.message ?? {}, usage);
154
+ const content = concatenateTextParts(mapped.parts);
155
+ const toolCalls = parseOpenAIToolCalls(requireFunctionToolCalls(choice?.message.tool_calls));
156
+ return withInputLineage({
157
+ content,
158
+ parts: mapped.parts,
159
+ toolCalls,
160
+ usage,
161
+ metadata: {
162
+ ...mapped.metadata,
163
+ effectiveModel: resolvedModel,
164
+ effectiveEffort: stepEffort ?? 'none',
165
+ },
166
+ }, lineage);
167
+ }
168
+ catch (error) {
169
+ if (isProviderContractError(error))
170
+ throw error;
171
+ throw new ProviderError({ provider: 'openai', cause: error });
172
+ }
173
+ };
174
+ return withBackendDescriptors(generate, openAIDescriptorsFor(resolvedModel, baseURL));
175
+ }
176
+ /**
177
+ * Creates a StreamingGenerateFunction backed by the OpenAI Chat Completions API.
178
+ *
179
+ * Streams chunks from the API, progressively calling `streaming.update`
180
+ * with accumulated text and collecting tool call fragments into complete
181
+ * ToolCallInput objects.
182
+ *
183
+ * When no `client` is provided, dynamically imports `openai`
184
+ * and constructs one using `apiKey` or the `OPENAI_API_KEY` env var.
185
+ * The optional `baseURL` enables LM Studio, Ollama, Groq, etc.
186
+ */
187
+ export function createOpenAIProviderStream(options) {
188
+ const { baseURL } = options;
189
+ const resolvedModel = resolveOpenAIModel(options.model);
190
+ const resolvedEffort = options.effort
191
+ ? resolveOpenAIEffort(options.effort, resolvedModel)
192
+ : undefined;
193
+ const common = resolveCommonParameters(options);
194
+ let clientPromise;
195
+ function getClient() {
196
+ if (options.client)
197
+ return Promise.resolve(options.client);
198
+ if (!clientPromise) {
199
+ clientPromise = import('openai').then((module) => {
200
+ const OpenAI = module.default ?? module.OpenAI;
201
+ const clientOptions = {};
202
+ if (options.apiKey)
203
+ clientOptions['apiKey'] = options.apiKey;
204
+ if (baseURL)
205
+ clientOptions['baseURL'] = baseURL;
206
+ return new OpenAI(clientOptions);
207
+ });
208
+ }
209
+ return clientPromise;
210
+ }
211
+ const generate = async (context) => {
212
+ // The step's steered effort, read per call (COR-1935), not the construction-time one. A model
213
+ // that takes no `reasoning_effort` resolves it to `undefined`: the parameter is omitted, and
214
+ // the response's `effectiveEffort` says `'none'`.
215
+ const stepEffort = context.steering?.effort === undefined
216
+ ? resolvedEffort
217
+ : resolveOpenAIEffort(context.steering.effort, resolvedModel);
218
+ const client = await getClient();
219
+ const { streaming } = context;
220
+ const { messages, lineage } = toOpenAIMessagesGrouped(context.conversation.current, {
221
+ sources: context.resolvedSources,
222
+ });
223
+ const tools = await context.toolbox.toOpenAITools();
224
+ const hasTools = tools.length > 0;
225
+ const params = {
226
+ model: resolvedModel,
227
+ messages,
228
+ stream: true,
229
+ stream_options: { include_usage: true },
230
+ };
231
+ const effectiveMaxTokensStream = context.maximumTokens ?? common.maximumTokens;
232
+ if (effectiveMaxTokensStream !== undefined)
233
+ params['max_tokens'] = effectiveMaxTokensStream;
234
+ if (stepEffort !== undefined)
235
+ params['reasoning_effort'] = stepEffort;
236
+ if (hasTools && options.toolChoice !== 'none')
237
+ params['tools'] = tools;
238
+ if (hasTools && options.toolChoice && options.toolChoice !== 'none')
239
+ params['tool_choice'] = toOpenAIToolChoice(options.toolChoice);
240
+ // Construction-time `options.responseFormat` (an explicit caller
241
+ // override) wins when set; otherwise fall back to the per-run
242
+ // `context.responseFormat` the loop derives from `RunOptions.output`
243
+ // (AB-18), so a run's `output` schema reaches the wire without every
244
+ // caller having to re-derive and pass it at provider construction.
245
+ const responseFormat = options.responseFormat ?? context.responseFormat;
246
+ if (responseFormat) {
247
+ const adapted = toOpenAIResponseFormat(responseFormat);
248
+ if (adapted !== undefined)
249
+ params['response_format'] = adapted;
250
+ }
251
+ if (options.requestMetadata)
252
+ params['metadata'] = options.requestMetadata;
253
+ if (common.temperature !== undefined)
254
+ params['temperature'] = common.temperature;
255
+ if (common.topP !== undefined)
256
+ params['top_p'] = common.topP;
257
+ if (common.stopSequences)
258
+ params['stop'] = common.stopSequences;
259
+ // See createOpenAIProvider: request options, not the body. This is what
260
+ // lets an abort actually close the streaming connection instead of
261
+ // parking the `for await` below until the model finishes on its own.
262
+ const requestOptions = context.signal ? { signal: context.signal } : undefined;
263
+ try {
264
+ // Await handles both sync (mock) and async (real SDK APIPromise) returns
265
+ const stream = await Promise.resolve(client.chat.completions.create(params, requestOptions));
266
+ let accumulatedText = '';
267
+ let usage;
268
+ // The assistant message as the deltas assemble it; mapped by the same table as a whole
269
+ // completion once the stream has drained, so the two modes cannot disagree.
270
+ const assembled = {};
271
+ let textSequence = 0;
272
+ // Track in-progress tool calls by index. `blockId` is the stable identity
273
+ // carried on the live `stream:tool-call-*` events, so a host can
274
+ // correlate a start with its deltas before the response closes.
275
+ const pendingToolCalls = new Map();
276
+ for await (const chunk of stream) {
277
+ if (context.signal?.aborted)
278
+ break;
279
+ const choice = chunk.choices[0];
280
+ if (choice) {
281
+ // Accumulate text content
282
+ if (choice.delta.content != null && choice.delta.content !== '') {
283
+ if (streaming.reportPart !== undefined) {
284
+ if (textSequence === 0) {
285
+ streaming.reportPart({ type: 'start', partIndex: 0, kind: 'text' });
286
+ }
287
+ textSequence += 1;
288
+ streaming.reportPart({
289
+ type: 'delta',
290
+ partIndex: 0,
291
+ sequence: textSequence,
292
+ delta: { kind: 'text', text: choice.delta.content },
293
+ });
294
+ }
295
+ accumulatedText += choice.delta.content;
296
+ if (streaming.reportPart === undefined)
297
+ streaming.update(accumulatedText);
298
+ }
299
+ // Every other delta field except tool calls and `role` joins the assembled message:
300
+ // strings concatenate across deltas, anything else keeps its latest value.
301
+ for (const [field, value] of Object.entries(choice.delta)) {
302
+ if (field === 'content' || field === 'tool_calls' || field === 'role')
303
+ continue;
304
+ if (value === undefined || value === null)
305
+ continue;
306
+ mergeAssembledField(assembled, field, value);
307
+ }
308
+ // Accumulate tool calls
309
+ if (choice.delta.tool_calls) {
310
+ for (const toolCallDelta of choice.delta.tool_calls) {
311
+ let pending = pendingToolCalls.get(toolCallDelta.index);
312
+ if (!pending) {
313
+ // First chunk for this tool call index
314
+ pending = {
315
+ id: toolCallDelta.id,
316
+ name: toolCallDelta.function?.name ?? '',
317
+ arguments: '',
318
+ blockId: undefined,
319
+ };
320
+ pendingToolCalls.set(toolCallDelta.index, pending);
321
+ }
322
+ else {
323
+ // `id` and `function.name` are both optional on every delta, so
324
+ // the chunk that opens an index need not carry them. Take them
325
+ // from whichever later chunk does rather than leaving the call
326
+ // permanently unnamed or id-less.
327
+ if (pending.id === undefined)
328
+ pending.id = toolCallDelta.id;
329
+ if (!pending.name && toolCallDelta.function?.name) {
330
+ pending.name = toolCallDelta.function.name;
331
+ }
332
+ }
333
+ // Append arguments fragment. OpenAI may put the first fragment on
334
+ // the same chunk that opens the call, so this runs for the
335
+ // opening chunk too rather than only for continuations.
336
+ const argumentsFragment = toolCallDelta.function?.arguments;
337
+ if (argumentsFragment)
338
+ pending.arguments += argumentsFragment;
339
+ // Hold the live start until BOTH the name and the provider's id
340
+ // are known, and use that id as the block id.
341
+ //
342
+ // The name, because an event announcing an empty tool is worse
343
+ // than one that arrives a chunk later. The id, because it is the
344
+ // only identity the wrapper can correlate a reported block with:
345
+ // the resolved response carries the provider id (the caller needs
346
+ // it to round-trip tool results), and a block id cannot be
347
+ // re-keyed once consumers have seen it. Publishing a synthesized
348
+ // id here would guarantee those two disagree.
349
+ //
350
+ // Both fields are optional on every delta, so a stream that never
351
+ // supplies an id gets no live events for that call — it is
352
+ // announced by the wrapper's reconstruction once the response
353
+ // resolves, exactly as before this option existed. The real API
354
+ // sends id and name together on a call's first delta, so this
355
+ // costs nothing in practice.
356
+ let justStarted = false;
357
+ if (pending.blockId === undefined && pending.name && pending.id !== undefined) {
358
+ pending.blockId = pending.id;
359
+ justStarted = true;
360
+ streaming.report?.({
361
+ type: 'stream:tool-call-start',
362
+ toolName: pending.name,
363
+ blockId: pending.blockId,
364
+ });
365
+ }
366
+ // Emit whenever this chunk carried arguments, and once more at the
367
+ // moment of a deferred start, to flush fragments that arrived on
368
+ // chunks before the name did.
369
+ if (pending.blockId !== undefined && (argumentsFragment || justStarted)) {
370
+ if (pending.arguments) {
371
+ streaming.report?.({
372
+ type: 'stream:tool-call-delta',
373
+ toolName: pending.name,
374
+ blockId: pending.blockId,
375
+ partialArguments: pending.arguments,
376
+ });
377
+ }
378
+ }
379
+ }
380
+ }
381
+ }
382
+ // Extract usage from the final chunk
383
+ if (chunk.usage) {
384
+ usage = buildOpenAIUsage(chunk.usage);
385
+ }
386
+ }
387
+ // Build completed tool calls. Skipped entirely when the caller aborted mid-stream:
388
+ // any accumulated arguments fragment is caller-truncated, not model-malformed, so it
389
+ // must never be parsed and misreported as a ToolCallParseError.
390
+ const toolCalls = [];
391
+ if (!context.signal?.aborted) {
392
+ for (const pending of pendingToolCalls.values()) {
393
+ let parsedArguments;
394
+ if (pending.arguments) {
395
+ try {
396
+ parsedArguments = JSON.parse(pending.arguments);
397
+ }
398
+ catch (parseError) {
399
+ throw new ToolCallParseError({
400
+ provider: 'openai',
401
+ toolName: pending.name,
402
+ toolCallId: pending.id,
403
+ rawArguments: pending.arguments,
404
+ cause: parseError,
405
+ });
406
+ }
407
+ }
408
+ toolCalls.push({
409
+ id: pending.id,
410
+ name: pending.name,
411
+ arguments: parsedArguments,
412
+ });
413
+ }
414
+ }
415
+ // An aborted stream's text is whatever arrived; it maps like any other.
416
+ const mapped = mapOpenAIMessage({ ...assembled, content: accumulatedText }, usage);
417
+ const [textPart] = mapped.parts;
418
+ if (textPart !== undefined) {
419
+ streaming.reportPart?.({ type: 'complete', partIndex: 0, part: textPart });
420
+ }
421
+ return withInputLineage({
422
+ content: concatenateTextParts(mapped.parts),
423
+ parts: mapped.parts,
424
+ toolCalls,
425
+ usage,
426
+ metadata: {
427
+ ...mapped.metadata,
428
+ effectiveModel: resolvedModel,
429
+ effectiveEffort: stepEffort ?? 'none',
430
+ },
431
+ }, lineage);
432
+ }
433
+ catch (error) {
434
+ if (error instanceof ProviderError)
435
+ throw error;
436
+ throw new ProviderError({ provider: 'openai', cause: error });
437
+ }
438
+ };
439
+ return withBackendDescriptors(generate, openAIDescriptorsFor(resolvedModel, baseURL));
440
+ }
@@ -0,0 +1,18 @@
1
+ import type { StreamEvent } from '@lostgradient/operative/provider-kit';
2
+ import { buildState, findBlock } from '@lostgradient/operative/provider-kit';
3
+ import type { OpenAIChatCompletionChunk } from "../openai-types.js";
4
+ type NormalizeOpenAIStreamDependencies = {
5
+ buildState: typeof buildState;
6
+ findBlock: typeof findBlock;
7
+ };
8
+ /**
9
+ * Normalizes an OpenAI Chat Completions streaming response into a
10
+ * provider-agnostic AsyncIterable of StreamEvents.
11
+ *
12
+ * Handles `delta.content` for text, `delta.tool_calls` for tool calls,
13
+ * `finish_reason` for completion, and `usage` for token tracking.
14
+ */
15
+ export declare function normalizeOpenAIStream(stream: AsyncIterable<OpenAIChatCompletionChunk>, dependencies?: NormalizeOpenAIStreamDependencies, options?: {
16
+ readonly messageId?: string;
17
+ }): AsyncIterable<StreamEvent>;
18
+ export {};
@@ -0,0 +1,213 @@
1
+ import { buildState, findBlock, ProviderContractError } from '@lostgradient/operative/provider-kit';
2
+ /**
3
+ * Normalizes an OpenAI Chat Completions streaming response into a
4
+ * provider-agnostic AsyncIterable of StreamEvents.
5
+ *
6
+ * Handles `delta.content` for text, `delta.tool_calls` for tool calls,
7
+ * `finish_reason` for completion, and `usage` for token tracking.
8
+ */
9
+ export async function* normalizeOpenAIStream(stream, dependencies = {
10
+ buildState,
11
+ findBlock,
12
+ }, options = {}) {
13
+ const messageId = options.messageId ?? 'message';
14
+ let textPartSequence = 0;
15
+ let textPartComplete = false;
16
+ const { buildState: dependencyBuildState, findBlock: dependencyFindBlock } = dependencies;
17
+ const state = {
18
+ blocks: [],
19
+ hasUsageData: false,
20
+ promptTokens: undefined,
21
+ completionTokens: undefined,
22
+ };
23
+ const { blocks } = state;
24
+ /** Map from OpenAI tool call index → our tracker */
25
+ const toolTrackers = new Map();
26
+ let accumulatedText = '';
27
+ let textBlockId;
28
+ for await (const chunk of stream) {
29
+ // Handle usage before checking for choices — OpenAI sends a final
30
+ // usage-only chunk with choices: [] when stream_options.include_usage
31
+ // is enabled.
32
+ if (chunk.usage) {
33
+ state.hasUsageData = true;
34
+ state.promptTokens = chunk.usage.prompt_tokens ?? 0;
35
+ state.completionTokens = chunk.usage.completion_tokens ?? 0;
36
+ yield {
37
+ type: 'stream:usage',
38
+ usage: {
39
+ prompt: state.promptTokens,
40
+ completion: state.completionTokens,
41
+ total: chunk.usage.total_tokens ?? state.promptTokens + state.completionTokens,
42
+ },
43
+ };
44
+ }
45
+ const choice = chunk.choices[0];
46
+ if (!choice)
47
+ continue;
48
+ const { delta, finish_reason } = choice;
49
+ for (const field of ['audio', 'function_call']) {
50
+ if (delta[field] !== undefined && delta[field] !== null) {
51
+ // The stream ends at its error: nothing follows it, not even `stream:complete`.
52
+ yield {
53
+ type: 'stream:error',
54
+ error: new ProviderContractError({
55
+ provider: 'openai',
56
+ reason: 'unlisted-block',
57
+ blockType: field,
58
+ partIndex: 0,
59
+ usage: undefined,
60
+ }),
61
+ };
62
+ return;
63
+ }
64
+ }
65
+ // Handle text content
66
+ if (delta.content !== undefined && delta.content !== null && delta.content !== '') {
67
+ // Lazily create a text block
68
+ if (!textBlockId) {
69
+ textBlockId = `text-${blocks.length}`;
70
+ const block = {
71
+ id: textBlockId,
72
+ type: 'text',
73
+ index: blocks.length,
74
+ content: '',
75
+ complete: false,
76
+ };
77
+ blocks.push(block);
78
+ yield { type: 'stream:block-start', block: { ...block } };
79
+ }
80
+ if (textPartSequence === 0)
81
+ yield { type: 'stream:part-start', messageId, partIndex: 0, kind: 'text' };
82
+ textPartSequence += 1;
83
+ yield {
84
+ type: 'stream:part-delta',
85
+ messageId,
86
+ partIndex: 0,
87
+ sequence: textPartSequence,
88
+ delta: { kind: 'text', text: delta.content },
89
+ };
90
+ const block = dependencyFindBlock(blocks, textBlockId);
91
+ if (block) {
92
+ block.content += delta.content;
93
+ accumulatedText += delta.content;
94
+ yield {
95
+ type: 'stream:block-delta',
96
+ block: { ...block },
97
+ delta: delta.content,
98
+ };
99
+ yield {
100
+ type: 'stream:text-delta',
101
+ content: delta.content,
102
+ accumulated: accumulatedText,
103
+ };
104
+ }
105
+ }
106
+ // Handle tool calls
107
+ if (delta.tool_calls) {
108
+ for (const toolCall of delta.tool_calls) {
109
+ const { index } = toolCall;
110
+ let tracker = toolTrackers.get(index);
111
+ if (!tracker && toolCall.id && toolCall.function?.name) {
112
+ // New tool call
113
+ const blockId = toolCall.id;
114
+ const toolName = toolCall.function.name;
115
+ tracker = { blockId, toolName, arguments: '' };
116
+ toolTrackers.set(index, tracker);
117
+ const block = {
118
+ id: blockId,
119
+ type: 'tool-call',
120
+ index: blocks.length,
121
+ content: '',
122
+ complete: false,
123
+ toolName,
124
+ partialArguments: '',
125
+ };
126
+ blocks.push(block);
127
+ yield { type: 'stream:block-start', block: { ...block } };
128
+ yield { type: 'stream:tool-call-start', toolName, blockId };
129
+ }
130
+ if (tracker && toolCall.function?.arguments) {
131
+ const args = toolCall.function.arguments;
132
+ tracker.arguments += args;
133
+ const block = dependencyFindBlock(blocks, tracker.blockId);
134
+ if (block) {
135
+ block.content += args;
136
+ block.partialArguments = tracker.arguments;
137
+ }
138
+ yield {
139
+ type: 'stream:block-delta',
140
+ block: block
141
+ ? { ...block }
142
+ : {
143
+ id: tracker.blockId,
144
+ type: 'tool-call',
145
+ index: 0,
146
+ content: tracker.arguments,
147
+ complete: false,
148
+ toolName: tracker.toolName,
149
+ partialArguments: tracker.arguments,
150
+ },
151
+ delta: args,
152
+ };
153
+ yield {
154
+ type: 'stream:tool-call-delta',
155
+ toolName: tracker.toolName,
156
+ blockId: tracker.blockId,
157
+ partialArguments: tracker.arguments,
158
+ };
159
+ }
160
+ }
161
+ }
162
+ // Handle finish — complete blocks immediately but defer the
163
+ // stream:complete event until after the loop so that a trailing
164
+ // usage-only chunk (OpenAI's stream_options.include_usage) is captured.
165
+ if (finish_reason) {
166
+ if (textPartSequence > 0 && !textPartComplete) {
167
+ textPartComplete = true;
168
+ yield {
169
+ type: 'stream:part-complete',
170
+ messageId,
171
+ partIndex: 0,
172
+ part: { type: 'text', text: accumulatedText },
173
+ };
174
+ }
175
+ // Complete the text block if one exists
176
+ if (textBlockId) {
177
+ const textBlock = dependencyFindBlock(blocks, textBlockId);
178
+ if (textBlock) {
179
+ textBlock.complete = true;
180
+ yield { type: 'stream:block-complete', block: { ...textBlock } };
181
+ }
182
+ }
183
+ // Complete all tool call blocks
184
+ for (const [, tracker] of toolTrackers) {
185
+ const block = dependencyFindBlock(blocks, tracker.blockId);
186
+ if (block) {
187
+ block.complete = true;
188
+ yield { type: 'stream:block-complete', block: { ...block } };
189
+ }
190
+ let parsedArgs = tracker.arguments;
191
+ try {
192
+ parsedArgs = JSON.parse(tracker.arguments);
193
+ }
194
+ catch {
195
+ // Keep as string if not valid JSON
196
+ }
197
+ yield {
198
+ type: 'stream:tool-call-complete',
199
+ toolName: tracker.toolName,
200
+ blockId: tracker.blockId,
201
+ arguments: parsedArgs,
202
+ };
203
+ }
204
+ }
205
+ }
206
+ // Emit stream:complete after the loop so any trailing usage-only chunk
207
+ // has been processed and buildState() includes the final usage data.
208
+ const finalState = {
209
+ ...dependencyBuildState(state),
210
+ complete: true,
211
+ };
212
+ yield { type: 'stream:complete', state: finalState };
213
+ }