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