@ls-stack/server-i18n 0.0.0-stage → 0.6.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.
@@ -0,0 +1,4519 @@
1
+ import { S as _coercedNumber, _ as string, a as any, d as literal, h as record, i as _null, l as discriminatedUnion, m as object, n as _enum, o as array, p as number$1, s as boolean, t as ZodNumber, u as lazy, v as union, y as unknown } from "./schemas-BfUoDuyI.mjs";
2
+ import { $ as UnsupportedFunctionalityError, A as loadOptionalSetting, B as validateTypes, F as postJsonToApi, G as APICallError, H as withoutTrailingSlash, J as InvalidResponseDataError, N as parseProviderOptions, O as lazySchema, P as postFormDataToApi, T as isParsableJson, U as zodSchema, V as withUserAgentSuffix, Z as TooManyEmbeddingValuesForCallError, _ as downloadBlob, a as convertToBase64, c as createBinaryResponseHandler, d as createJsonErrorResponseHandler, f as createJsonResponseHandler, h as createToolNameMapping, i as convertBase64ToUint8Array, j as mediaTypeToExtension, k as loadApiKey, l as createEventSourceResponseHandler, m as createProviderToolFactoryWithOutputSchema, o as convertToFormData, q as InvalidPromptError, r as combineHeaders, w as isNonNullable, y as generateId } from "./dist-BA5qgNhB.mjs";
3
+
4
+ //#region ../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js
5
+ function number(params) {
6
+ return _coercedNumber(ZodNumber, params);
7
+ }
8
+
9
+ //#endregion
10
+ //#region ../node_modules/.pnpm/@ai-sdk+openai@3.0.25_zod@4.3.6/node_modules/@ai-sdk/openai/dist/index.mjs
11
+ var openaiErrorDataSchema = object({ error: object({
12
+ message: string(),
13
+ type: string().nullish(),
14
+ param: any().nullish(),
15
+ code: union([string(), number$1()]).nullish()
16
+ }) });
17
+ var openaiFailedResponseHandler = createJsonErrorResponseHandler({
18
+ errorSchema: openaiErrorDataSchema,
19
+ errorToMessage: (data) => data.error.message
20
+ });
21
+ function getOpenAILanguageModelCapabilities(modelId) {
22
+ const supportsFlexProcessing = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
23
+ const supportsPriorityProcessing = modelId.startsWith("gpt-4") || modelId.startsWith("gpt-5-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat") || modelId.startsWith("o3") || modelId.startsWith("o4-mini");
24
+ const isReasoningModel = modelId.startsWith("o1") || modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("codex-mini") || modelId.startsWith("computer-use-preview") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat");
25
+ const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2");
26
+ return {
27
+ supportsFlexProcessing,
28
+ supportsPriorityProcessing,
29
+ isReasoningModel,
30
+ systemMessageMode: isReasoningModel ? "developer" : "system",
31
+ supportsNonReasoningParameters
32
+ };
33
+ }
34
+ function convertOpenAIChatUsage(usage) {
35
+ var _a, _b, _c, _d, _e, _f;
36
+ if (usage == null) return {
37
+ inputTokens: {
38
+ total: void 0,
39
+ noCache: void 0,
40
+ cacheRead: void 0,
41
+ cacheWrite: void 0
42
+ },
43
+ outputTokens: {
44
+ total: void 0,
45
+ text: void 0,
46
+ reasoning: void 0
47
+ },
48
+ raw: void 0
49
+ };
50
+ const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
51
+ const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
52
+ const cachedTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0;
53
+ const reasoningTokens = (_f = (_e = usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0;
54
+ return {
55
+ inputTokens: {
56
+ total: promptTokens,
57
+ noCache: promptTokens - cachedTokens,
58
+ cacheRead: cachedTokens,
59
+ cacheWrite: void 0
60
+ },
61
+ outputTokens: {
62
+ total: completionTokens,
63
+ text: completionTokens - reasoningTokens,
64
+ reasoning: reasoningTokens
65
+ },
66
+ raw: usage
67
+ };
68
+ }
69
+ function convertToOpenAIChatMessages({ prompt, systemMessageMode = "system" }) {
70
+ var _a;
71
+ const messages = [];
72
+ const warnings = [];
73
+ for (const { role, content } of prompt) switch (role) {
74
+ case "system":
75
+ switch (systemMessageMode) {
76
+ case "system":
77
+ messages.push({
78
+ role: "system",
79
+ content
80
+ });
81
+ break;
82
+ case "developer":
83
+ messages.push({
84
+ role: "developer",
85
+ content
86
+ });
87
+ break;
88
+ case "remove":
89
+ warnings.push({
90
+ type: "other",
91
+ message: "system messages are removed for this model"
92
+ });
93
+ break;
94
+ default: {
95
+ const _exhaustiveCheck = systemMessageMode;
96
+ throw new Error(`Unsupported system message mode: ${_exhaustiveCheck}`);
97
+ }
98
+ }
99
+ break;
100
+ case "user":
101
+ if (content.length === 1 && content[0].type === "text") {
102
+ messages.push({
103
+ role: "user",
104
+ content: content[0].text
105
+ });
106
+ break;
107
+ }
108
+ messages.push({
109
+ role: "user",
110
+ content: content.map((part, index) => {
111
+ var _a2, _b, _c;
112
+ switch (part.type) {
113
+ case "text": return {
114
+ type: "text",
115
+ text: part.text
116
+ };
117
+ case "file": if (part.mediaType.startsWith("image/")) {
118
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
119
+ return {
120
+ type: "image_url",
121
+ image_url: {
122
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`,
123
+ detail: (_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.openai) == null ? void 0 : _b.imageDetail
124
+ }
125
+ };
126
+ } else if (part.mediaType.startsWith("audio/")) {
127
+ if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ functionality: "audio file parts with URLs" });
128
+ switch (part.mediaType) {
129
+ case "audio/wav": return {
130
+ type: "input_audio",
131
+ input_audio: {
132
+ data: convertToBase64(part.data),
133
+ format: "wav"
134
+ }
135
+ };
136
+ case "audio/mp3":
137
+ case "audio/mpeg": return {
138
+ type: "input_audio",
139
+ input_audio: {
140
+ data: convertToBase64(part.data),
141
+ format: "mp3"
142
+ }
143
+ };
144
+ default: throw new UnsupportedFunctionalityError({ functionality: `audio content parts with media type ${part.mediaType}` });
145
+ }
146
+ } else if (part.mediaType === "application/pdf") {
147
+ if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ functionality: "PDF file parts with URLs" });
148
+ return {
149
+ type: "file",
150
+ file: typeof part.data === "string" && part.data.startsWith("file-") ? { file_id: part.data } : {
151
+ filename: (_c = part.filename) != null ? _c : `part-${index}.pdf`,
152
+ file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`
153
+ }
154
+ };
155
+ } else throw new UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` });
156
+ }
157
+ })
158
+ });
159
+ break;
160
+ case "assistant": {
161
+ let text = "";
162
+ const toolCalls = [];
163
+ for (const part of content) switch (part.type) {
164
+ case "text":
165
+ text += part.text;
166
+ break;
167
+ case "tool-call":
168
+ toolCalls.push({
169
+ id: part.toolCallId,
170
+ type: "function",
171
+ function: {
172
+ name: part.toolName,
173
+ arguments: JSON.stringify(part.input)
174
+ }
175
+ });
176
+ break;
177
+ }
178
+ messages.push({
179
+ role: "assistant",
180
+ content: text,
181
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
182
+ });
183
+ break;
184
+ }
185
+ case "tool":
186
+ for (const toolResponse of content) {
187
+ if (toolResponse.type === "tool-approval-response") continue;
188
+ const output = toolResponse.output;
189
+ let contentValue;
190
+ switch (output.type) {
191
+ case "text":
192
+ case "error-text":
193
+ contentValue = output.value;
194
+ break;
195
+ case "execution-denied":
196
+ contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
197
+ break;
198
+ case "content":
199
+ case "json":
200
+ case "error-json":
201
+ contentValue = JSON.stringify(output.value);
202
+ break;
203
+ }
204
+ messages.push({
205
+ role: "tool",
206
+ tool_call_id: toolResponse.toolCallId,
207
+ content: contentValue
208
+ });
209
+ }
210
+ break;
211
+ default: {
212
+ const _exhaustiveCheck = role;
213
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
214
+ }
215
+ }
216
+ return {
217
+ messages,
218
+ warnings
219
+ };
220
+ }
221
+ function getResponseMetadata({ id, model, created }) {
222
+ return {
223
+ id: id != null ? id : void 0,
224
+ modelId: model != null ? model : void 0,
225
+ timestamp: created ? /* @__PURE__ */ new Date(created * 1e3) : void 0
226
+ };
227
+ }
228
+ function mapOpenAIFinishReason(finishReason) {
229
+ switch (finishReason) {
230
+ case "stop": return "stop";
231
+ case "length": return "length";
232
+ case "content_filter": return "content-filter";
233
+ case "function_call":
234
+ case "tool_calls": return "tool-calls";
235
+ default: return "other";
236
+ }
237
+ }
238
+ var openaiChatResponseSchema = lazySchema(() => zodSchema(object({
239
+ id: string().nullish(),
240
+ created: number$1().nullish(),
241
+ model: string().nullish(),
242
+ choices: array(object({
243
+ message: object({
244
+ role: literal("assistant").nullish(),
245
+ content: string().nullish(),
246
+ tool_calls: array(object({
247
+ id: string().nullish(),
248
+ type: literal("function"),
249
+ function: object({
250
+ name: string(),
251
+ arguments: string()
252
+ })
253
+ })).nullish(),
254
+ annotations: array(object({
255
+ type: literal("url_citation"),
256
+ url_citation: object({
257
+ start_index: number$1(),
258
+ end_index: number$1(),
259
+ url: string(),
260
+ title: string()
261
+ })
262
+ })).nullish()
263
+ }),
264
+ index: number$1(),
265
+ logprobs: object({ content: array(object({
266
+ token: string(),
267
+ logprob: number$1(),
268
+ top_logprobs: array(object({
269
+ token: string(),
270
+ logprob: number$1()
271
+ }))
272
+ })).nullish() }).nullish(),
273
+ finish_reason: string().nullish()
274
+ })),
275
+ usage: object({
276
+ prompt_tokens: number$1().nullish(),
277
+ completion_tokens: number$1().nullish(),
278
+ total_tokens: number$1().nullish(),
279
+ prompt_tokens_details: object({ cached_tokens: number$1().nullish() }).nullish(),
280
+ completion_tokens_details: object({
281
+ reasoning_tokens: number$1().nullish(),
282
+ accepted_prediction_tokens: number$1().nullish(),
283
+ rejected_prediction_tokens: number$1().nullish()
284
+ }).nullish()
285
+ }).nullish()
286
+ })));
287
+ var openaiChatChunkSchema = lazySchema(() => zodSchema(union([object({
288
+ id: string().nullish(),
289
+ created: number$1().nullish(),
290
+ model: string().nullish(),
291
+ choices: array(object({
292
+ delta: object({
293
+ role: _enum(["assistant"]).nullish(),
294
+ content: string().nullish(),
295
+ tool_calls: array(object({
296
+ index: number$1(),
297
+ id: string().nullish(),
298
+ type: literal("function").nullish(),
299
+ function: object({
300
+ name: string().nullish(),
301
+ arguments: string().nullish()
302
+ })
303
+ })).nullish(),
304
+ annotations: array(object({
305
+ type: literal("url_citation"),
306
+ url_citation: object({
307
+ start_index: number$1(),
308
+ end_index: number$1(),
309
+ url: string(),
310
+ title: string()
311
+ })
312
+ })).nullish()
313
+ }).nullish(),
314
+ logprobs: object({ content: array(object({
315
+ token: string(),
316
+ logprob: number$1(),
317
+ top_logprobs: array(object({
318
+ token: string(),
319
+ logprob: number$1()
320
+ }))
321
+ })).nullish() }).nullish(),
322
+ finish_reason: string().nullish(),
323
+ index: number$1()
324
+ })),
325
+ usage: object({
326
+ prompt_tokens: number$1().nullish(),
327
+ completion_tokens: number$1().nullish(),
328
+ total_tokens: number$1().nullish(),
329
+ prompt_tokens_details: object({ cached_tokens: number$1().nullish() }).nullish(),
330
+ completion_tokens_details: object({
331
+ reasoning_tokens: number$1().nullish(),
332
+ accepted_prediction_tokens: number$1().nullish(),
333
+ rejected_prediction_tokens: number$1().nullish()
334
+ }).nullish()
335
+ }).nullish()
336
+ }), openaiErrorDataSchema])));
337
+ var openaiChatLanguageModelOptions = lazySchema(() => zodSchema(object({
338
+ logitBias: record(number(), number$1()).optional(),
339
+ logprobs: union([boolean(), number$1()]).optional(),
340
+ parallelToolCalls: boolean().optional(),
341
+ user: string().optional(),
342
+ reasoningEffort: _enum([
343
+ "none",
344
+ "minimal",
345
+ "low",
346
+ "medium",
347
+ "high",
348
+ "xhigh"
349
+ ]).optional(),
350
+ maxCompletionTokens: number$1().optional(),
351
+ store: boolean().optional(),
352
+ metadata: record(string().max(64), string().max(512)).optional(),
353
+ prediction: record(string(), any()).optional(),
354
+ serviceTier: _enum([
355
+ "auto",
356
+ "flex",
357
+ "priority",
358
+ "default"
359
+ ]).optional(),
360
+ strictJsonSchema: boolean().optional(),
361
+ textVerbosity: _enum([
362
+ "low",
363
+ "medium",
364
+ "high"
365
+ ]).optional(),
366
+ promptCacheKey: string().optional(),
367
+ promptCacheRetention: _enum(["in_memory", "24h"]).optional(),
368
+ safetyIdentifier: string().optional(),
369
+ systemMessageMode: _enum([
370
+ "system",
371
+ "developer",
372
+ "remove"
373
+ ]).optional(),
374
+ forceReasoning: boolean().optional()
375
+ })));
376
+ function prepareChatTools({ tools, toolChoice }) {
377
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
378
+ const toolWarnings = [];
379
+ if (tools == null) return {
380
+ tools: void 0,
381
+ toolChoice: void 0,
382
+ toolWarnings
383
+ };
384
+ const openaiTools2 = [];
385
+ for (const tool of tools) switch (tool.type) {
386
+ case "function":
387
+ openaiTools2.push({
388
+ type: "function",
389
+ function: {
390
+ name: tool.name,
391
+ description: tool.description,
392
+ parameters: tool.inputSchema,
393
+ ...tool.strict != null ? { strict: tool.strict } : {}
394
+ }
395
+ });
396
+ break;
397
+ default:
398
+ toolWarnings.push({
399
+ type: "unsupported",
400
+ feature: `tool type: ${tool.type}`
401
+ });
402
+ break;
403
+ }
404
+ if (toolChoice == null) return {
405
+ tools: openaiTools2,
406
+ toolChoice: void 0,
407
+ toolWarnings
408
+ };
409
+ const type = toolChoice.type;
410
+ switch (type) {
411
+ case "auto":
412
+ case "none":
413
+ case "required": return {
414
+ tools: openaiTools2,
415
+ toolChoice: type,
416
+ toolWarnings
417
+ };
418
+ case "tool": return {
419
+ tools: openaiTools2,
420
+ toolChoice: {
421
+ type: "function",
422
+ function: { name: toolChoice.toolName }
423
+ },
424
+ toolWarnings
425
+ };
426
+ default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
427
+ }
428
+ }
429
+ var OpenAIChatLanguageModel = class {
430
+ constructor(modelId, config) {
431
+ this.specificationVersion = "v3";
432
+ this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
433
+ this.modelId = modelId;
434
+ this.config = config;
435
+ }
436
+ get provider() {
437
+ return this.config.provider;
438
+ }
439
+ async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }) {
440
+ var _a, _b, _c, _d, _e;
441
+ const warnings = [];
442
+ const openaiOptions = (_a = await parseProviderOptions({
443
+ provider: "openai",
444
+ providerOptions,
445
+ schema: openaiChatLanguageModelOptions
446
+ })) != null ? _a : {};
447
+ const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);
448
+ const isReasoningModel = (_b = openaiOptions.forceReasoning) != null ? _b : modelCapabilities.isReasoningModel;
449
+ if (topK != null) warnings.push({
450
+ type: "unsupported",
451
+ feature: "topK"
452
+ });
453
+ const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages({
454
+ prompt,
455
+ systemMessageMode: (_c = openaiOptions.systemMessageMode) != null ? _c : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode
456
+ });
457
+ warnings.push(...messageWarnings);
458
+ const strictJsonSchema = (_d = openaiOptions.strictJsonSchema) != null ? _d : true;
459
+ const baseArgs = {
460
+ model: this.modelId,
461
+ logit_bias: openaiOptions.logitBias,
462
+ logprobs: openaiOptions.logprobs === true || typeof openaiOptions.logprobs === "number" ? true : void 0,
463
+ top_logprobs: typeof openaiOptions.logprobs === "number" ? openaiOptions.logprobs : typeof openaiOptions.logprobs === "boolean" ? openaiOptions.logprobs ? 0 : void 0 : void 0,
464
+ user: openaiOptions.user,
465
+ parallel_tool_calls: openaiOptions.parallelToolCalls,
466
+ max_tokens: maxOutputTokens,
467
+ temperature,
468
+ top_p: topP,
469
+ frequency_penalty: frequencyPenalty,
470
+ presence_penalty: presencePenalty,
471
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
472
+ type: "json_schema",
473
+ json_schema: {
474
+ schema: responseFormat.schema,
475
+ strict: strictJsonSchema,
476
+ name: (_e = responseFormat.name) != null ? _e : "response",
477
+ description: responseFormat.description
478
+ }
479
+ } : { type: "json_object" } : void 0,
480
+ stop: stopSequences,
481
+ seed,
482
+ verbosity: openaiOptions.textVerbosity,
483
+ max_completion_tokens: openaiOptions.maxCompletionTokens,
484
+ store: openaiOptions.store,
485
+ metadata: openaiOptions.metadata,
486
+ prediction: openaiOptions.prediction,
487
+ reasoning_effort: openaiOptions.reasoningEffort,
488
+ service_tier: openaiOptions.serviceTier,
489
+ prompt_cache_key: openaiOptions.promptCacheKey,
490
+ prompt_cache_retention: openaiOptions.promptCacheRetention,
491
+ safety_identifier: openaiOptions.safetyIdentifier,
492
+ messages
493
+ };
494
+ if (isReasoningModel) {
495
+ if (openaiOptions.reasoningEffort !== "none" || !modelCapabilities.supportsNonReasoningParameters) {
496
+ if (baseArgs.temperature != null) {
497
+ baseArgs.temperature = void 0;
498
+ warnings.push({
499
+ type: "unsupported",
500
+ feature: "temperature",
501
+ details: "temperature is not supported for reasoning models"
502
+ });
503
+ }
504
+ if (baseArgs.top_p != null) {
505
+ baseArgs.top_p = void 0;
506
+ warnings.push({
507
+ type: "unsupported",
508
+ feature: "topP",
509
+ details: "topP is not supported for reasoning models"
510
+ });
511
+ }
512
+ if (baseArgs.logprobs != null) {
513
+ baseArgs.logprobs = void 0;
514
+ warnings.push({
515
+ type: "other",
516
+ message: "logprobs is not supported for reasoning models"
517
+ });
518
+ }
519
+ }
520
+ if (baseArgs.frequency_penalty != null) {
521
+ baseArgs.frequency_penalty = void 0;
522
+ warnings.push({
523
+ type: "unsupported",
524
+ feature: "frequencyPenalty",
525
+ details: "frequencyPenalty is not supported for reasoning models"
526
+ });
527
+ }
528
+ if (baseArgs.presence_penalty != null) {
529
+ baseArgs.presence_penalty = void 0;
530
+ warnings.push({
531
+ type: "unsupported",
532
+ feature: "presencePenalty",
533
+ details: "presencePenalty is not supported for reasoning models"
534
+ });
535
+ }
536
+ if (baseArgs.logit_bias != null) {
537
+ baseArgs.logit_bias = void 0;
538
+ warnings.push({
539
+ type: "other",
540
+ message: "logitBias is not supported for reasoning models"
541
+ });
542
+ }
543
+ if (baseArgs.top_logprobs != null) {
544
+ baseArgs.top_logprobs = void 0;
545
+ warnings.push({
546
+ type: "other",
547
+ message: "topLogprobs is not supported for reasoning models"
548
+ });
549
+ }
550
+ if (baseArgs.max_tokens != null) {
551
+ if (baseArgs.max_completion_tokens == null) baseArgs.max_completion_tokens = baseArgs.max_tokens;
552
+ baseArgs.max_tokens = void 0;
553
+ }
554
+ } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) {
555
+ if (baseArgs.temperature != null) {
556
+ baseArgs.temperature = void 0;
557
+ warnings.push({
558
+ type: "unsupported",
559
+ feature: "temperature",
560
+ details: "temperature is not supported for the search preview models and has been removed."
561
+ });
562
+ }
563
+ }
564
+ if (openaiOptions.serviceTier === "flex" && !modelCapabilities.supportsFlexProcessing) {
565
+ warnings.push({
566
+ type: "unsupported",
567
+ feature: "serviceTier",
568
+ details: "flex processing is only available for o3, o4-mini, and gpt-5 models"
569
+ });
570
+ baseArgs.service_tier = void 0;
571
+ }
572
+ if (openaiOptions.serviceTier === "priority" && !modelCapabilities.supportsPriorityProcessing) {
573
+ warnings.push({
574
+ type: "unsupported",
575
+ feature: "serviceTier",
576
+ details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"
577
+ });
578
+ baseArgs.service_tier = void 0;
579
+ }
580
+ const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = prepareChatTools({
581
+ tools,
582
+ toolChoice
583
+ });
584
+ return {
585
+ args: {
586
+ ...baseArgs,
587
+ tools: openaiTools2,
588
+ tool_choice: openaiToolChoice
589
+ },
590
+ warnings: [...warnings, ...toolWarnings]
591
+ };
592
+ }
593
+ async doGenerate(options) {
594
+ var _a, _b, _c, _d, _e, _f, _g;
595
+ const { args: body, warnings } = await this.getArgs(options);
596
+ const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
597
+ url: this.config.url({
598
+ path: "/chat/completions",
599
+ modelId: this.modelId
600
+ }),
601
+ headers: combineHeaders(this.config.headers(), options.headers),
602
+ body,
603
+ failedResponseHandler: openaiFailedResponseHandler,
604
+ successfulResponseHandler: createJsonResponseHandler(openaiChatResponseSchema),
605
+ abortSignal: options.abortSignal,
606
+ fetch: this.config.fetch
607
+ });
608
+ const choice = response.choices[0];
609
+ const content = [];
610
+ const text = choice.message.content;
611
+ if (text != null && text.length > 0) content.push({
612
+ type: "text",
613
+ text
614
+ });
615
+ for (const toolCall of (_a = choice.message.tool_calls) != null ? _a : []) content.push({
616
+ type: "tool-call",
617
+ toolCallId: (_b = toolCall.id) != null ? _b : generateId(),
618
+ toolName: toolCall.function.name,
619
+ input: toolCall.function.arguments
620
+ });
621
+ for (const annotation of (_c = choice.message.annotations) != null ? _c : []) content.push({
622
+ type: "source",
623
+ sourceType: "url",
624
+ id: generateId(),
625
+ url: annotation.url_citation.url,
626
+ title: annotation.url_citation.title
627
+ });
628
+ const completionTokenDetails = (_d = response.usage) == null ? void 0 : _d.completion_tokens_details;
629
+ (_e = response.usage) == null || _e.prompt_tokens_details;
630
+ const providerMetadata = { openai: {} };
631
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens;
632
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens;
633
+ if (((_f = choice.logprobs) == null ? void 0 : _f.content) != null) providerMetadata.openai.logprobs = choice.logprobs.content;
634
+ return {
635
+ content,
636
+ finishReason: {
637
+ unified: mapOpenAIFinishReason(choice.finish_reason),
638
+ raw: (_g = choice.finish_reason) != null ? _g : void 0
639
+ },
640
+ usage: convertOpenAIChatUsage(response.usage),
641
+ request: { body },
642
+ response: {
643
+ ...getResponseMetadata(response),
644
+ headers: responseHeaders,
645
+ body: rawResponse
646
+ },
647
+ warnings,
648
+ providerMetadata
649
+ };
650
+ }
651
+ async doStream(options) {
652
+ const { args, warnings } = await this.getArgs(options);
653
+ const body = {
654
+ ...args,
655
+ stream: true,
656
+ stream_options: { include_usage: true }
657
+ };
658
+ const { responseHeaders, value: response } = await postJsonToApi({
659
+ url: this.config.url({
660
+ path: "/chat/completions",
661
+ modelId: this.modelId
662
+ }),
663
+ headers: combineHeaders(this.config.headers(), options.headers),
664
+ body,
665
+ failedResponseHandler: openaiFailedResponseHandler,
666
+ successfulResponseHandler: createEventSourceResponseHandler(openaiChatChunkSchema),
667
+ abortSignal: options.abortSignal,
668
+ fetch: this.config.fetch
669
+ });
670
+ const toolCalls = [];
671
+ let finishReason = {
672
+ unified: "other",
673
+ raw: void 0
674
+ };
675
+ let usage = void 0;
676
+ let metadataExtracted = false;
677
+ let isActiveText = false;
678
+ const providerMetadata = { openai: {} };
679
+ return {
680
+ stream: response.pipeThrough(new TransformStream({
681
+ start(controller) {
682
+ controller.enqueue({
683
+ type: "stream-start",
684
+ warnings
685
+ });
686
+ },
687
+ transform(chunk, controller) {
688
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
689
+ if (options.includeRawChunks) controller.enqueue({
690
+ type: "raw",
691
+ rawValue: chunk.rawValue
692
+ });
693
+ if (!chunk.success) {
694
+ finishReason = {
695
+ unified: "error",
696
+ raw: void 0
697
+ };
698
+ controller.enqueue({
699
+ type: "error",
700
+ error: chunk.error
701
+ });
702
+ return;
703
+ }
704
+ const value = chunk.value;
705
+ if ("error" in value) {
706
+ finishReason = {
707
+ unified: "error",
708
+ raw: void 0
709
+ };
710
+ controller.enqueue({
711
+ type: "error",
712
+ error: value.error
713
+ });
714
+ return;
715
+ }
716
+ if (!metadataExtracted) {
717
+ const metadata = getResponseMetadata(value);
718
+ if (Object.values(metadata).some(Boolean)) {
719
+ metadataExtracted = true;
720
+ controller.enqueue({
721
+ type: "response-metadata",
722
+ ...getResponseMetadata(value)
723
+ });
724
+ }
725
+ }
726
+ if (value.usage != null) {
727
+ usage = value.usage;
728
+ if (((_a = value.usage.completion_tokens_details) == null ? void 0 : _a.accepted_prediction_tokens) != null) providerMetadata.openai.acceptedPredictionTokens = (_b = value.usage.completion_tokens_details) == null ? void 0 : _b.accepted_prediction_tokens;
729
+ if (((_c = value.usage.completion_tokens_details) == null ? void 0 : _c.rejected_prediction_tokens) != null) providerMetadata.openai.rejectedPredictionTokens = (_d = value.usage.completion_tokens_details) == null ? void 0 : _d.rejected_prediction_tokens;
730
+ }
731
+ const choice = value.choices[0];
732
+ if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = {
733
+ unified: mapOpenAIFinishReason(choice.finish_reason),
734
+ raw: choice.finish_reason
735
+ };
736
+ if (((_e = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _e.content) != null) providerMetadata.openai.logprobs = choice.logprobs.content;
737
+ if ((choice == null ? void 0 : choice.delta) == null) return;
738
+ const delta = choice.delta;
739
+ if (delta.content != null) {
740
+ if (!isActiveText) {
741
+ controller.enqueue({
742
+ type: "text-start",
743
+ id: "0"
744
+ });
745
+ isActiveText = true;
746
+ }
747
+ controller.enqueue({
748
+ type: "text-delta",
749
+ id: "0",
750
+ delta: delta.content
751
+ });
752
+ }
753
+ if (delta.tool_calls != null) for (const toolCallDelta of delta.tool_calls) {
754
+ const index = toolCallDelta.index;
755
+ if (toolCalls[index] == null) {
756
+ if (toolCallDelta.type !== "function") throw new InvalidResponseDataError({
757
+ data: toolCallDelta,
758
+ message: `Expected 'function' type.`
759
+ });
760
+ if (toolCallDelta.id == null) throw new InvalidResponseDataError({
761
+ data: toolCallDelta,
762
+ message: `Expected 'id' to be a string.`
763
+ });
764
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.name) == null) throw new InvalidResponseDataError({
765
+ data: toolCallDelta,
766
+ message: `Expected 'function.name' to be a string.`
767
+ });
768
+ controller.enqueue({
769
+ type: "tool-input-start",
770
+ id: toolCallDelta.id,
771
+ toolName: toolCallDelta.function.name
772
+ });
773
+ toolCalls[index] = {
774
+ id: toolCallDelta.id,
775
+ type: "function",
776
+ function: {
777
+ name: toolCallDelta.function.name,
778
+ arguments: (_g = toolCallDelta.function.arguments) != null ? _g : ""
779
+ },
780
+ hasFinished: false
781
+ };
782
+ const toolCall2 = toolCalls[index];
783
+ if (((_h = toolCall2.function) == null ? void 0 : _h.name) != null && ((_i = toolCall2.function) == null ? void 0 : _i.arguments) != null) {
784
+ if (toolCall2.function.arguments.length > 0) controller.enqueue({
785
+ type: "tool-input-delta",
786
+ id: toolCall2.id,
787
+ delta: toolCall2.function.arguments
788
+ });
789
+ if (isParsableJson(toolCall2.function.arguments)) {
790
+ controller.enqueue({
791
+ type: "tool-input-end",
792
+ id: toolCall2.id
793
+ });
794
+ controller.enqueue({
795
+ type: "tool-call",
796
+ toolCallId: (_j = toolCall2.id) != null ? _j : generateId(),
797
+ toolName: toolCall2.function.name,
798
+ input: toolCall2.function.arguments
799
+ });
800
+ toolCall2.hasFinished = true;
801
+ }
802
+ }
803
+ continue;
804
+ }
805
+ const toolCall = toolCalls[index];
806
+ if (toolCall.hasFinished) continue;
807
+ if (((_k = toolCallDelta.function) == null ? void 0 : _k.arguments) != null) toolCall.function.arguments += (_m = (_l = toolCallDelta.function) == null ? void 0 : _l.arguments) != null ? _m : "";
808
+ controller.enqueue({
809
+ type: "tool-input-delta",
810
+ id: toolCall.id,
811
+ delta: (_n = toolCallDelta.function.arguments) != null ? _n : ""
812
+ });
813
+ if (((_o = toolCall.function) == null ? void 0 : _o.name) != null && ((_p = toolCall.function) == null ? void 0 : _p.arguments) != null && isParsableJson(toolCall.function.arguments)) {
814
+ controller.enqueue({
815
+ type: "tool-input-end",
816
+ id: toolCall.id
817
+ });
818
+ controller.enqueue({
819
+ type: "tool-call",
820
+ toolCallId: (_q = toolCall.id) != null ? _q : generateId(),
821
+ toolName: toolCall.function.name,
822
+ input: toolCall.function.arguments
823
+ });
824
+ toolCall.hasFinished = true;
825
+ }
826
+ }
827
+ if (delta.annotations != null) for (const annotation of delta.annotations) controller.enqueue({
828
+ type: "source",
829
+ sourceType: "url",
830
+ id: generateId(),
831
+ url: annotation.url_citation.url,
832
+ title: annotation.url_citation.title
833
+ });
834
+ },
835
+ flush(controller) {
836
+ if (isActiveText) controller.enqueue({
837
+ type: "text-end",
838
+ id: "0"
839
+ });
840
+ controller.enqueue({
841
+ type: "finish",
842
+ finishReason,
843
+ usage: convertOpenAIChatUsage(usage),
844
+ ...providerMetadata != null ? { providerMetadata } : {}
845
+ });
846
+ }
847
+ })),
848
+ request: { body },
849
+ response: { headers: responseHeaders }
850
+ };
851
+ }
852
+ };
853
+ function convertOpenAICompletionUsage(usage) {
854
+ var _a, _b, _c, _d;
855
+ if (usage == null) return {
856
+ inputTokens: {
857
+ total: void 0,
858
+ noCache: void 0,
859
+ cacheRead: void 0,
860
+ cacheWrite: void 0
861
+ },
862
+ outputTokens: {
863
+ total: void 0,
864
+ text: void 0,
865
+ reasoning: void 0
866
+ },
867
+ raw: void 0
868
+ };
869
+ const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
870
+ const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
871
+ return {
872
+ inputTokens: {
873
+ total: (_c = usage.prompt_tokens) != null ? _c : void 0,
874
+ noCache: promptTokens,
875
+ cacheRead: void 0,
876
+ cacheWrite: void 0
877
+ },
878
+ outputTokens: {
879
+ total: (_d = usage.completion_tokens) != null ? _d : void 0,
880
+ text: completionTokens,
881
+ reasoning: void 0
882
+ },
883
+ raw: usage
884
+ };
885
+ }
886
+ function convertToOpenAICompletionPrompt({ prompt, user = "user", assistant = "assistant" }) {
887
+ let text = "";
888
+ if (prompt[0].role === "system") {
889
+ text += `${prompt[0].content}
890
+
891
+ `;
892
+ prompt = prompt.slice(1);
893
+ }
894
+ for (const { role, content } of prompt) switch (role) {
895
+ case "system": throw new InvalidPromptError({
896
+ message: "Unexpected system message in prompt: ${content}",
897
+ prompt
898
+ });
899
+ case "user": {
900
+ const userMessage = content.map((part) => {
901
+ switch (part.type) {
902
+ case "text": return part.text;
903
+ }
904
+ }).filter(Boolean).join("");
905
+ text += `${user}:
906
+ ${userMessage}
907
+
908
+ `;
909
+ break;
910
+ }
911
+ case "assistant": {
912
+ const assistantMessage = content.map((part) => {
913
+ switch (part.type) {
914
+ case "text": return part.text;
915
+ case "tool-call": throw new UnsupportedFunctionalityError({ functionality: "tool-call messages" });
916
+ }
917
+ }).join("");
918
+ text += `${assistant}:
919
+ ${assistantMessage}
920
+
921
+ `;
922
+ break;
923
+ }
924
+ case "tool": throw new UnsupportedFunctionalityError({ functionality: "tool messages" });
925
+ default: {
926
+ const _exhaustiveCheck = role;
927
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
928
+ }
929
+ }
930
+ text += `${assistant}:
931
+ `;
932
+ return {
933
+ prompt: text,
934
+ stopSequences: [`
935
+ ${user}:`]
936
+ };
937
+ }
938
+ function getResponseMetadata2({ id, model, created }) {
939
+ return {
940
+ id: id != null ? id : void 0,
941
+ modelId: model != null ? model : void 0,
942
+ timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
943
+ };
944
+ }
945
+ function mapOpenAIFinishReason2(finishReason) {
946
+ switch (finishReason) {
947
+ case "stop": return "stop";
948
+ case "length": return "length";
949
+ case "content_filter": return "content-filter";
950
+ case "function_call":
951
+ case "tool_calls": return "tool-calls";
952
+ default: return "other";
953
+ }
954
+ }
955
+ var openaiCompletionResponseSchema = lazySchema(() => zodSchema(object({
956
+ id: string().nullish(),
957
+ created: number$1().nullish(),
958
+ model: string().nullish(),
959
+ choices: array(object({
960
+ text: string(),
961
+ finish_reason: string(),
962
+ logprobs: object({
963
+ tokens: array(string()),
964
+ token_logprobs: array(number$1()),
965
+ top_logprobs: array(record(string(), number$1())).nullish()
966
+ }).nullish()
967
+ })),
968
+ usage: object({
969
+ prompt_tokens: number$1(),
970
+ completion_tokens: number$1(),
971
+ total_tokens: number$1()
972
+ }).nullish()
973
+ })));
974
+ var openaiCompletionChunkSchema = lazySchema(() => zodSchema(union([object({
975
+ id: string().nullish(),
976
+ created: number$1().nullish(),
977
+ model: string().nullish(),
978
+ choices: array(object({
979
+ text: string(),
980
+ finish_reason: string().nullish(),
981
+ index: number$1(),
982
+ logprobs: object({
983
+ tokens: array(string()),
984
+ token_logprobs: array(number$1()),
985
+ top_logprobs: array(record(string(), number$1())).nullish()
986
+ }).nullish()
987
+ })),
988
+ usage: object({
989
+ prompt_tokens: number$1(),
990
+ completion_tokens: number$1(),
991
+ total_tokens: number$1()
992
+ }).nullish()
993
+ }), openaiErrorDataSchema])));
994
+ var openaiCompletionProviderOptions = lazySchema(() => zodSchema(object({
995
+ echo: boolean().optional(),
996
+ logitBias: record(string(), number$1()).optional(),
997
+ suffix: string().optional(),
998
+ user: string().optional(),
999
+ logprobs: union([boolean(), number$1()]).optional()
1000
+ })));
1001
+ var OpenAICompletionLanguageModel = class {
1002
+ constructor(modelId, config) {
1003
+ this.specificationVersion = "v3";
1004
+ this.supportedUrls = {};
1005
+ this.modelId = modelId;
1006
+ this.config = config;
1007
+ }
1008
+ get providerOptionsName() {
1009
+ return this.config.provider.split(".")[0].trim();
1010
+ }
1011
+ get provider() {
1012
+ return this.config.provider;
1013
+ }
1014
+ async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, tools, toolChoice, seed, providerOptions }) {
1015
+ const warnings = [];
1016
+ const openaiOptions = {
1017
+ ...await parseProviderOptions({
1018
+ provider: "openai",
1019
+ providerOptions,
1020
+ schema: openaiCompletionProviderOptions
1021
+ }),
1022
+ ...await parseProviderOptions({
1023
+ provider: this.providerOptionsName,
1024
+ providerOptions,
1025
+ schema: openaiCompletionProviderOptions
1026
+ })
1027
+ };
1028
+ if (topK != null) warnings.push({
1029
+ type: "unsupported",
1030
+ feature: "topK"
1031
+ });
1032
+ if (tools == null ? void 0 : tools.length) warnings.push({
1033
+ type: "unsupported",
1034
+ feature: "tools"
1035
+ });
1036
+ if (toolChoice != null) warnings.push({
1037
+ type: "unsupported",
1038
+ feature: "toolChoice"
1039
+ });
1040
+ if (responseFormat != null && responseFormat.type !== "text") warnings.push({
1041
+ type: "unsupported",
1042
+ feature: "responseFormat",
1043
+ details: "JSON response format is not supported."
1044
+ });
1045
+ const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt });
1046
+ const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
1047
+ return {
1048
+ args: {
1049
+ model: this.modelId,
1050
+ echo: openaiOptions.echo,
1051
+ logit_bias: openaiOptions.logitBias,
1052
+ logprobs: (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? 0 : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === false ? void 0 : openaiOptions == null ? void 0 : openaiOptions.logprobs,
1053
+ suffix: openaiOptions.suffix,
1054
+ user: openaiOptions.user,
1055
+ max_tokens: maxOutputTokens,
1056
+ temperature,
1057
+ top_p: topP,
1058
+ frequency_penalty: frequencyPenalty,
1059
+ presence_penalty: presencePenalty,
1060
+ seed,
1061
+ prompt: completionPrompt,
1062
+ stop: stop.length > 0 ? stop : void 0
1063
+ },
1064
+ warnings
1065
+ };
1066
+ }
1067
+ async doGenerate(options) {
1068
+ var _a;
1069
+ const { args, warnings } = await this.getArgs(options);
1070
+ const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
1071
+ url: this.config.url({
1072
+ path: "/completions",
1073
+ modelId: this.modelId
1074
+ }),
1075
+ headers: combineHeaders(this.config.headers(), options.headers),
1076
+ body: args,
1077
+ failedResponseHandler: openaiFailedResponseHandler,
1078
+ successfulResponseHandler: createJsonResponseHandler(openaiCompletionResponseSchema),
1079
+ abortSignal: options.abortSignal,
1080
+ fetch: this.config.fetch
1081
+ });
1082
+ const choice = response.choices[0];
1083
+ const providerMetadata = { openai: {} };
1084
+ if (choice.logprobs != null) providerMetadata.openai.logprobs = choice.logprobs;
1085
+ return {
1086
+ content: [{
1087
+ type: "text",
1088
+ text: choice.text
1089
+ }],
1090
+ usage: convertOpenAICompletionUsage(response.usage),
1091
+ finishReason: {
1092
+ unified: mapOpenAIFinishReason2(choice.finish_reason),
1093
+ raw: (_a = choice.finish_reason) != null ? _a : void 0
1094
+ },
1095
+ request: { body: args },
1096
+ response: {
1097
+ ...getResponseMetadata2(response),
1098
+ headers: responseHeaders,
1099
+ body: rawResponse
1100
+ },
1101
+ providerMetadata,
1102
+ warnings
1103
+ };
1104
+ }
1105
+ async doStream(options) {
1106
+ const { args, warnings } = await this.getArgs(options);
1107
+ const body = {
1108
+ ...args,
1109
+ stream: true,
1110
+ stream_options: { include_usage: true }
1111
+ };
1112
+ const { responseHeaders, value: response } = await postJsonToApi({
1113
+ url: this.config.url({
1114
+ path: "/completions",
1115
+ modelId: this.modelId
1116
+ }),
1117
+ headers: combineHeaders(this.config.headers(), options.headers),
1118
+ body,
1119
+ failedResponseHandler: openaiFailedResponseHandler,
1120
+ successfulResponseHandler: createEventSourceResponseHandler(openaiCompletionChunkSchema),
1121
+ abortSignal: options.abortSignal,
1122
+ fetch: this.config.fetch
1123
+ });
1124
+ let finishReason = {
1125
+ unified: "other",
1126
+ raw: void 0
1127
+ };
1128
+ const providerMetadata = { openai: {} };
1129
+ let usage = void 0;
1130
+ let isFirstChunk = true;
1131
+ return {
1132
+ stream: response.pipeThrough(new TransformStream({
1133
+ start(controller) {
1134
+ controller.enqueue({
1135
+ type: "stream-start",
1136
+ warnings
1137
+ });
1138
+ },
1139
+ transform(chunk, controller) {
1140
+ if (options.includeRawChunks) controller.enqueue({
1141
+ type: "raw",
1142
+ rawValue: chunk.rawValue
1143
+ });
1144
+ if (!chunk.success) {
1145
+ finishReason = {
1146
+ unified: "error",
1147
+ raw: void 0
1148
+ };
1149
+ controller.enqueue({
1150
+ type: "error",
1151
+ error: chunk.error
1152
+ });
1153
+ return;
1154
+ }
1155
+ const value = chunk.value;
1156
+ if ("error" in value) {
1157
+ finishReason = {
1158
+ unified: "error",
1159
+ raw: void 0
1160
+ };
1161
+ controller.enqueue({
1162
+ type: "error",
1163
+ error: value.error
1164
+ });
1165
+ return;
1166
+ }
1167
+ if (isFirstChunk) {
1168
+ isFirstChunk = false;
1169
+ controller.enqueue({
1170
+ type: "response-metadata",
1171
+ ...getResponseMetadata2(value)
1172
+ });
1173
+ controller.enqueue({
1174
+ type: "text-start",
1175
+ id: "0"
1176
+ });
1177
+ }
1178
+ if (value.usage != null) usage = value.usage;
1179
+ const choice = value.choices[0];
1180
+ if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = {
1181
+ unified: mapOpenAIFinishReason2(choice.finish_reason),
1182
+ raw: choice.finish_reason
1183
+ };
1184
+ if ((choice == null ? void 0 : choice.logprobs) != null) providerMetadata.openai.logprobs = choice.logprobs;
1185
+ if ((choice == null ? void 0 : choice.text) != null && choice.text.length > 0) controller.enqueue({
1186
+ type: "text-delta",
1187
+ id: "0",
1188
+ delta: choice.text
1189
+ });
1190
+ },
1191
+ flush(controller) {
1192
+ if (!isFirstChunk) controller.enqueue({
1193
+ type: "text-end",
1194
+ id: "0"
1195
+ });
1196
+ controller.enqueue({
1197
+ type: "finish",
1198
+ finishReason,
1199
+ providerMetadata,
1200
+ usage: convertOpenAICompletionUsage(usage)
1201
+ });
1202
+ }
1203
+ })),
1204
+ request: { body },
1205
+ response: { headers: responseHeaders }
1206
+ };
1207
+ }
1208
+ };
1209
+ var openaiEmbeddingProviderOptions = lazySchema(() => zodSchema(object({
1210
+ dimensions: number$1().optional(),
1211
+ user: string().optional()
1212
+ })));
1213
+ var openaiTextEmbeddingResponseSchema = lazySchema(() => zodSchema(object({
1214
+ data: array(object({ embedding: array(number$1()) })),
1215
+ usage: object({ prompt_tokens: number$1() }).nullish()
1216
+ })));
1217
+ var OpenAIEmbeddingModel = class {
1218
+ constructor(modelId, config) {
1219
+ this.specificationVersion = "v3";
1220
+ this.maxEmbeddingsPerCall = 2048;
1221
+ this.supportsParallelCalls = true;
1222
+ this.modelId = modelId;
1223
+ this.config = config;
1224
+ }
1225
+ get provider() {
1226
+ return this.config.provider;
1227
+ }
1228
+ async doEmbed({ values, headers, abortSignal, providerOptions }) {
1229
+ var _a;
1230
+ if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({
1231
+ provider: this.provider,
1232
+ modelId: this.modelId,
1233
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
1234
+ values
1235
+ });
1236
+ const openaiOptions = (_a = await parseProviderOptions({
1237
+ provider: "openai",
1238
+ providerOptions,
1239
+ schema: openaiEmbeddingProviderOptions
1240
+ })) != null ? _a : {};
1241
+ const { responseHeaders, value: response, rawValue } = await postJsonToApi({
1242
+ url: this.config.url({
1243
+ path: "/embeddings",
1244
+ modelId: this.modelId
1245
+ }),
1246
+ headers: combineHeaders(this.config.headers(), headers),
1247
+ body: {
1248
+ model: this.modelId,
1249
+ input: values,
1250
+ encoding_format: "float",
1251
+ dimensions: openaiOptions.dimensions,
1252
+ user: openaiOptions.user
1253
+ },
1254
+ failedResponseHandler: openaiFailedResponseHandler,
1255
+ successfulResponseHandler: createJsonResponseHandler(openaiTextEmbeddingResponseSchema),
1256
+ abortSignal,
1257
+ fetch: this.config.fetch
1258
+ });
1259
+ return {
1260
+ warnings: [],
1261
+ embeddings: response.data.map((item) => item.embedding),
1262
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
1263
+ response: {
1264
+ headers: responseHeaders,
1265
+ body: rawValue
1266
+ }
1267
+ };
1268
+ }
1269
+ };
1270
+ var openaiImageResponseSchema = lazySchema(() => zodSchema(object({
1271
+ created: number$1().nullish(),
1272
+ data: array(object({
1273
+ b64_json: string(),
1274
+ revised_prompt: string().nullish()
1275
+ })),
1276
+ background: string().nullish(),
1277
+ output_format: string().nullish(),
1278
+ size: string().nullish(),
1279
+ quality: string().nullish(),
1280
+ usage: object({
1281
+ input_tokens: number$1().nullish(),
1282
+ output_tokens: number$1().nullish(),
1283
+ total_tokens: number$1().nullish(),
1284
+ input_tokens_details: object({
1285
+ image_tokens: number$1().nullish(),
1286
+ text_tokens: number$1().nullish()
1287
+ }).nullish()
1288
+ }).nullish()
1289
+ })));
1290
+ var modelMaxImagesPerCall = {
1291
+ "dall-e-3": 1,
1292
+ "dall-e-2": 10,
1293
+ "gpt-image-1": 10,
1294
+ "gpt-image-1-mini": 10,
1295
+ "gpt-image-1.5": 10
1296
+ };
1297
+ var defaultResponseFormatPrefixes = [
1298
+ "gpt-image-1-mini",
1299
+ "gpt-image-1.5",
1300
+ "gpt-image-1"
1301
+ ];
1302
+ function hasDefaultResponseFormat(modelId) {
1303
+ return defaultResponseFormatPrefixes.some((prefix) => modelId.startsWith(prefix));
1304
+ }
1305
+ var OpenAIImageModel = class {
1306
+ constructor(modelId, config) {
1307
+ this.modelId = modelId;
1308
+ this.config = config;
1309
+ this.specificationVersion = "v3";
1310
+ }
1311
+ get maxImagesPerCall() {
1312
+ var _a;
1313
+ return (_a = modelMaxImagesPerCall[this.modelId]) != null ? _a : 1;
1314
+ }
1315
+ get provider() {
1316
+ return this.config.provider;
1317
+ }
1318
+ async doGenerate({ prompt, files, mask, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) {
1319
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1320
+ const warnings = [];
1321
+ if (aspectRatio != null) warnings.push({
1322
+ type: "unsupported",
1323
+ feature: "aspectRatio",
1324
+ details: "This model does not support aspect ratio. Use `size` instead."
1325
+ });
1326
+ if (seed != null) warnings.push({
1327
+ type: "unsupported",
1328
+ feature: "seed"
1329
+ });
1330
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1331
+ if (files != null) {
1332
+ const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({
1333
+ url: this.config.url({
1334
+ path: "/images/edits",
1335
+ modelId: this.modelId
1336
+ }),
1337
+ headers: combineHeaders(this.config.headers(), headers),
1338
+ formData: convertToFormData({
1339
+ model: this.modelId,
1340
+ prompt,
1341
+ image: await Promise.all(files.map((file) => file.type === "file" ? new Blob([file.data instanceof Uint8Array ? new Blob([file.data], { type: file.mediaType }) : new Blob([convertBase64ToUint8Array(file.data)], { type: file.mediaType })], { type: file.mediaType }) : downloadBlob(file.url))),
1342
+ mask: mask != null ? await fileToBlob(mask) : void 0,
1343
+ n,
1344
+ size,
1345
+ ...(_d = providerOptions.openai) != null ? _d : {}
1346
+ }),
1347
+ failedResponseHandler: openaiFailedResponseHandler,
1348
+ successfulResponseHandler: createJsonResponseHandler(openaiImageResponseSchema),
1349
+ abortSignal,
1350
+ fetch: this.config.fetch
1351
+ });
1352
+ return {
1353
+ images: response2.data.map((item) => item.b64_json),
1354
+ warnings,
1355
+ usage: response2.usage != null ? {
1356
+ inputTokens: (_e = response2.usage.input_tokens) != null ? _e : void 0,
1357
+ outputTokens: (_f = response2.usage.output_tokens) != null ? _f : void 0,
1358
+ totalTokens: (_g = response2.usage.total_tokens) != null ? _g : void 0
1359
+ } : void 0,
1360
+ response: {
1361
+ timestamp: currentDate,
1362
+ modelId: this.modelId,
1363
+ headers: responseHeaders2
1364
+ },
1365
+ providerMetadata: { openai: { images: response2.data.map((item) => {
1366
+ var _a2, _b2, _c2, _d2, _e2;
1367
+ return {
1368
+ ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {},
1369
+ created: (_a2 = response2.created) != null ? _a2 : void 0,
1370
+ size: (_b2 = response2.size) != null ? _b2 : void 0,
1371
+ quality: (_c2 = response2.quality) != null ? _c2 : void 0,
1372
+ background: (_d2 = response2.background) != null ? _d2 : void 0,
1373
+ outputFormat: (_e2 = response2.output_format) != null ? _e2 : void 0
1374
+ };
1375
+ }) } }
1376
+ };
1377
+ }
1378
+ const { value: response, responseHeaders } = await postJsonToApi({
1379
+ url: this.config.url({
1380
+ path: "/images/generations",
1381
+ modelId: this.modelId
1382
+ }),
1383
+ headers: combineHeaders(this.config.headers(), headers),
1384
+ body: {
1385
+ model: this.modelId,
1386
+ prompt,
1387
+ n,
1388
+ size,
1389
+ ...(_h = providerOptions.openai) != null ? _h : {},
1390
+ ...!hasDefaultResponseFormat(this.modelId) ? { response_format: "b64_json" } : {}
1391
+ },
1392
+ failedResponseHandler: openaiFailedResponseHandler,
1393
+ successfulResponseHandler: createJsonResponseHandler(openaiImageResponseSchema),
1394
+ abortSignal,
1395
+ fetch: this.config.fetch
1396
+ });
1397
+ return {
1398
+ images: response.data.map((item) => item.b64_json),
1399
+ warnings,
1400
+ usage: response.usage != null ? {
1401
+ inputTokens: (_i = response.usage.input_tokens) != null ? _i : void 0,
1402
+ outputTokens: (_j = response.usage.output_tokens) != null ? _j : void 0,
1403
+ totalTokens: (_k = response.usage.total_tokens) != null ? _k : void 0
1404
+ } : void 0,
1405
+ response: {
1406
+ timestamp: currentDate,
1407
+ modelId: this.modelId,
1408
+ headers: responseHeaders
1409
+ },
1410
+ providerMetadata: { openai: { images: response.data.map((item) => {
1411
+ var _a2, _b2, _c2, _d2, _e2;
1412
+ return {
1413
+ ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {},
1414
+ created: (_a2 = response.created) != null ? _a2 : void 0,
1415
+ size: (_b2 = response.size) != null ? _b2 : void 0,
1416
+ quality: (_c2 = response.quality) != null ? _c2 : void 0,
1417
+ background: (_d2 = response.background) != null ? _d2 : void 0,
1418
+ outputFormat: (_e2 = response.output_format) != null ? _e2 : void 0
1419
+ };
1420
+ }) } }
1421
+ };
1422
+ }
1423
+ };
1424
+ async function fileToBlob(file) {
1425
+ if (!file) return void 0;
1426
+ if (file.type === "url") return downloadBlob(file.url);
1427
+ const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array(file.data);
1428
+ return new Blob([data], { type: file.mediaType });
1429
+ }
1430
+ var applyPatchInputSchema = lazySchema(() => zodSchema(object({
1431
+ callId: string(),
1432
+ operation: discriminatedUnion("type", [
1433
+ object({
1434
+ type: literal("create_file"),
1435
+ path: string(),
1436
+ diff: string()
1437
+ }),
1438
+ object({
1439
+ type: literal("delete_file"),
1440
+ path: string()
1441
+ }),
1442
+ object({
1443
+ type: literal("update_file"),
1444
+ path: string(),
1445
+ diff: string()
1446
+ })
1447
+ ])
1448
+ })));
1449
+ var applyPatchOutputSchema = lazySchema(() => zodSchema(object({
1450
+ status: _enum(["completed", "failed"]),
1451
+ output: string().optional()
1452
+ })));
1453
+ lazySchema(() => zodSchema(object({})));
1454
+ var applyPatch = createProviderToolFactoryWithOutputSchema({
1455
+ id: "openai.apply_patch",
1456
+ inputSchema: applyPatchInputSchema,
1457
+ outputSchema: applyPatchOutputSchema
1458
+ });
1459
+ var codeInterpreterInputSchema = lazySchema(() => zodSchema(object({
1460
+ code: string().nullish(),
1461
+ containerId: string()
1462
+ })));
1463
+ var codeInterpreterOutputSchema = lazySchema(() => zodSchema(object({ outputs: array(discriminatedUnion("type", [object({
1464
+ type: literal("logs"),
1465
+ logs: string()
1466
+ }), object({
1467
+ type: literal("image"),
1468
+ url: string()
1469
+ })])).nullish() })));
1470
+ var codeInterpreterArgsSchema = lazySchema(() => zodSchema(object({ container: union([string(), object({ fileIds: array(string()).optional() })]).optional() })));
1471
+ var codeInterpreterToolFactory = createProviderToolFactoryWithOutputSchema({
1472
+ id: "openai.code_interpreter",
1473
+ inputSchema: codeInterpreterInputSchema,
1474
+ outputSchema: codeInterpreterOutputSchema
1475
+ });
1476
+ var codeInterpreter = (args = {}) => {
1477
+ return codeInterpreterToolFactory(args);
1478
+ };
1479
+ var comparisonFilterSchema = object({
1480
+ key: string(),
1481
+ type: _enum([
1482
+ "eq",
1483
+ "ne",
1484
+ "gt",
1485
+ "gte",
1486
+ "lt",
1487
+ "lte",
1488
+ "in",
1489
+ "nin"
1490
+ ]),
1491
+ value: union([
1492
+ string(),
1493
+ number$1(),
1494
+ boolean(),
1495
+ array(string())
1496
+ ])
1497
+ });
1498
+ var compoundFilterSchema = object({
1499
+ type: _enum(["and", "or"]),
1500
+ filters: array(union([comparisonFilterSchema, lazy(() => compoundFilterSchema)]))
1501
+ });
1502
+ var fileSearchArgsSchema = lazySchema(() => zodSchema(object({
1503
+ vectorStoreIds: array(string()),
1504
+ maxNumResults: number$1().optional(),
1505
+ ranking: object({
1506
+ ranker: string().optional(),
1507
+ scoreThreshold: number$1().optional()
1508
+ }).optional(),
1509
+ filters: union([comparisonFilterSchema, compoundFilterSchema]).optional()
1510
+ })));
1511
+ var fileSearchOutputSchema = lazySchema(() => zodSchema(object({
1512
+ queries: array(string()),
1513
+ results: array(object({
1514
+ attributes: record(string(), unknown()),
1515
+ fileId: string(),
1516
+ filename: string(),
1517
+ score: number$1(),
1518
+ text: string()
1519
+ })).nullable()
1520
+ })));
1521
+ var fileSearch = createProviderToolFactoryWithOutputSchema({
1522
+ id: "openai.file_search",
1523
+ inputSchema: object({}),
1524
+ outputSchema: fileSearchOutputSchema
1525
+ });
1526
+ var imageGenerationArgsSchema = lazySchema(() => zodSchema(object({
1527
+ background: _enum([
1528
+ "auto",
1529
+ "opaque",
1530
+ "transparent"
1531
+ ]).optional(),
1532
+ inputFidelity: _enum(["low", "high"]).optional(),
1533
+ inputImageMask: object({
1534
+ fileId: string().optional(),
1535
+ imageUrl: string().optional()
1536
+ }).optional(),
1537
+ model: string().optional(),
1538
+ moderation: _enum(["auto"]).optional(),
1539
+ outputCompression: number$1().int().min(0).max(100).optional(),
1540
+ outputFormat: _enum([
1541
+ "png",
1542
+ "jpeg",
1543
+ "webp"
1544
+ ]).optional(),
1545
+ partialImages: number$1().int().min(0).max(3).optional(),
1546
+ quality: _enum([
1547
+ "auto",
1548
+ "low",
1549
+ "medium",
1550
+ "high"
1551
+ ]).optional(),
1552
+ size: _enum([
1553
+ "1024x1024",
1554
+ "1024x1536",
1555
+ "1536x1024",
1556
+ "auto"
1557
+ ]).optional()
1558
+ }).strict()));
1559
+ var imageGenerationToolFactory = createProviderToolFactoryWithOutputSchema({
1560
+ id: "openai.image_generation",
1561
+ inputSchema: lazySchema(() => zodSchema(object({}))),
1562
+ outputSchema: lazySchema(() => zodSchema(object({ result: string() })))
1563
+ });
1564
+ var imageGeneration = (args = {}) => {
1565
+ return imageGenerationToolFactory(args);
1566
+ };
1567
+ var localShellInputSchema = lazySchema(() => zodSchema(object({ action: object({
1568
+ type: literal("exec"),
1569
+ command: array(string()),
1570
+ timeoutMs: number$1().optional(),
1571
+ user: string().optional(),
1572
+ workingDirectory: string().optional(),
1573
+ env: record(string(), string()).optional()
1574
+ }) })));
1575
+ var localShellOutputSchema = lazySchema(() => zodSchema(object({ output: string() })));
1576
+ var localShell = createProviderToolFactoryWithOutputSchema({
1577
+ id: "openai.local_shell",
1578
+ inputSchema: localShellInputSchema,
1579
+ outputSchema: localShellOutputSchema
1580
+ });
1581
+ var shellInputSchema = lazySchema(() => zodSchema(object({ action: object({
1582
+ commands: array(string()),
1583
+ timeoutMs: number$1().optional(),
1584
+ maxOutputLength: number$1().optional()
1585
+ }) })));
1586
+ var shellOutputSchema = lazySchema(() => zodSchema(object({ output: array(object({
1587
+ stdout: string(),
1588
+ stderr: string(),
1589
+ outcome: discriminatedUnion("type", [object({ type: literal("timeout") }), object({
1590
+ type: literal("exit"),
1591
+ exitCode: number$1()
1592
+ })])
1593
+ })) })));
1594
+ var shell = createProviderToolFactoryWithOutputSchema({
1595
+ id: "openai.shell",
1596
+ inputSchema: shellInputSchema,
1597
+ outputSchema: shellOutputSchema
1598
+ });
1599
+ var webSearchArgsSchema = lazySchema(() => zodSchema(object({
1600
+ externalWebAccess: boolean().optional(),
1601
+ filters: object({ allowedDomains: array(string()).optional() }).optional(),
1602
+ searchContextSize: _enum([
1603
+ "low",
1604
+ "medium",
1605
+ "high"
1606
+ ]).optional(),
1607
+ userLocation: object({
1608
+ type: literal("approximate"),
1609
+ country: string().optional(),
1610
+ city: string().optional(),
1611
+ region: string().optional(),
1612
+ timezone: string().optional()
1613
+ }).optional()
1614
+ })));
1615
+ var webSearchToolFactory = createProviderToolFactoryWithOutputSchema({
1616
+ id: "openai.web_search",
1617
+ inputSchema: lazySchema(() => zodSchema(object({}))),
1618
+ outputSchema: lazySchema(() => zodSchema(object({
1619
+ action: discriminatedUnion("type", [
1620
+ object({
1621
+ type: literal("search"),
1622
+ query: string().optional()
1623
+ }),
1624
+ object({
1625
+ type: literal("openPage"),
1626
+ url: string().nullish()
1627
+ }),
1628
+ object({
1629
+ type: literal("findInPage"),
1630
+ url: string().nullish(),
1631
+ pattern: string().nullish()
1632
+ })
1633
+ ]),
1634
+ sources: array(discriminatedUnion("type", [object({
1635
+ type: literal("url"),
1636
+ url: string()
1637
+ }), object({
1638
+ type: literal("api"),
1639
+ name: string()
1640
+ })])).optional()
1641
+ })))
1642
+ });
1643
+ var webSearch = (args = {}) => webSearchToolFactory(args);
1644
+ var webSearchPreviewArgsSchema = lazySchema(() => zodSchema(object({
1645
+ searchContextSize: _enum([
1646
+ "low",
1647
+ "medium",
1648
+ "high"
1649
+ ]).optional(),
1650
+ userLocation: object({
1651
+ type: literal("approximate"),
1652
+ country: string().optional(),
1653
+ city: string().optional(),
1654
+ region: string().optional(),
1655
+ timezone: string().optional()
1656
+ }).optional()
1657
+ })));
1658
+ var webSearchPreview = createProviderToolFactoryWithOutputSchema({
1659
+ id: "openai.web_search_preview",
1660
+ inputSchema: lazySchema(() => zodSchema(object({}))),
1661
+ outputSchema: lazySchema(() => zodSchema(object({ action: discriminatedUnion("type", [
1662
+ object({
1663
+ type: literal("search"),
1664
+ query: string().optional()
1665
+ }),
1666
+ object({
1667
+ type: literal("openPage"),
1668
+ url: string().nullish()
1669
+ }),
1670
+ object({
1671
+ type: literal("findInPage"),
1672
+ url: string().nullish(),
1673
+ pattern: string().nullish()
1674
+ })
1675
+ ]) })))
1676
+ });
1677
+ var jsonValueSchema = lazy(() => union([
1678
+ string(),
1679
+ number$1(),
1680
+ boolean(),
1681
+ _null(),
1682
+ array(jsonValueSchema),
1683
+ record(string(), jsonValueSchema)
1684
+ ]));
1685
+ var mcpArgsSchema = lazySchema(() => zodSchema(object({
1686
+ serverLabel: string(),
1687
+ allowedTools: union([array(string()), object({
1688
+ readOnly: boolean().optional(),
1689
+ toolNames: array(string()).optional()
1690
+ })]).optional(),
1691
+ authorization: string().optional(),
1692
+ connectorId: string().optional(),
1693
+ headers: record(string(), string()).optional(),
1694
+ requireApproval: union([_enum(["always", "never"]), object({ never: object({ toolNames: array(string()).optional() }).optional() })]).optional(),
1695
+ serverDescription: string().optional(),
1696
+ serverUrl: string().optional()
1697
+ }).refine((v) => v.serverUrl != null || v.connectorId != null, "One of serverUrl or connectorId must be provided.")));
1698
+ var mcpToolFactory = createProviderToolFactoryWithOutputSchema({
1699
+ id: "openai.mcp",
1700
+ inputSchema: lazySchema(() => zodSchema(object({}))),
1701
+ outputSchema: lazySchema(() => zodSchema(object({
1702
+ type: literal("call"),
1703
+ serverLabel: string(),
1704
+ name: string(),
1705
+ arguments: string(),
1706
+ output: string().nullish(),
1707
+ error: union([string(), jsonValueSchema]).optional()
1708
+ })))
1709
+ });
1710
+ var mcp = (args) => mcpToolFactory(args);
1711
+ var openaiTools = {
1712
+ applyPatch,
1713
+ codeInterpreter,
1714
+ fileSearch,
1715
+ imageGeneration,
1716
+ localShell,
1717
+ shell,
1718
+ webSearchPreview,
1719
+ webSearch,
1720
+ mcp
1721
+ };
1722
+ function convertOpenAIResponsesUsage(usage) {
1723
+ var _a, _b, _c, _d;
1724
+ if (usage == null) return {
1725
+ inputTokens: {
1726
+ total: void 0,
1727
+ noCache: void 0,
1728
+ cacheRead: void 0,
1729
+ cacheWrite: void 0
1730
+ },
1731
+ outputTokens: {
1732
+ total: void 0,
1733
+ text: void 0,
1734
+ reasoning: void 0
1735
+ },
1736
+ raw: void 0
1737
+ };
1738
+ const inputTokens = usage.input_tokens;
1739
+ const outputTokens = usage.output_tokens;
1740
+ const cachedTokens = (_b = (_a = usage.input_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0;
1741
+ const reasoningTokens = (_d = (_c = usage.output_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0;
1742
+ return {
1743
+ inputTokens: {
1744
+ total: inputTokens,
1745
+ noCache: inputTokens - cachedTokens,
1746
+ cacheRead: cachedTokens,
1747
+ cacheWrite: void 0
1748
+ },
1749
+ outputTokens: {
1750
+ total: outputTokens,
1751
+ text: outputTokens - reasoningTokens,
1752
+ reasoning: reasoningTokens
1753
+ },
1754
+ raw: usage
1755
+ };
1756
+ }
1757
+ function isFileId(data, prefixes) {
1758
+ if (!prefixes) return false;
1759
+ return prefixes.some((prefix) => data.startsWith(prefix));
1760
+ }
1761
+ async function convertToOpenAIResponsesInput({ prompt, toolNameMapping, systemMessageMode, providerOptionsName, fileIdPrefixes, store, hasConversation = false, hasLocalShellTool = false, hasShellTool = false, hasApplyPatchTool = false }) {
1762
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1763
+ const input = [];
1764
+ const warnings = [];
1765
+ const processedApprovalIds = /* @__PURE__ */ new Set();
1766
+ for (const { role, content } of prompt) switch (role) {
1767
+ case "system":
1768
+ switch (systemMessageMode) {
1769
+ case "system":
1770
+ input.push({
1771
+ role: "system",
1772
+ content
1773
+ });
1774
+ break;
1775
+ case "developer":
1776
+ input.push({
1777
+ role: "developer",
1778
+ content
1779
+ });
1780
+ break;
1781
+ case "remove":
1782
+ warnings.push({
1783
+ type: "other",
1784
+ message: "system messages are removed for this model"
1785
+ });
1786
+ break;
1787
+ default: {
1788
+ const _exhaustiveCheck = systemMessageMode;
1789
+ throw new Error(`Unsupported system message mode: ${_exhaustiveCheck}`);
1790
+ }
1791
+ }
1792
+ break;
1793
+ case "user":
1794
+ input.push({
1795
+ role: "user",
1796
+ content: content.map((part, index) => {
1797
+ var _a2, _b2, _c2;
1798
+ switch (part.type) {
1799
+ case "text": return {
1800
+ type: "input_text",
1801
+ text: part.text
1802
+ };
1803
+ case "file": if (part.mediaType.startsWith("image/")) {
1804
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
1805
+ return {
1806
+ type: "input_image",
1807
+ ...part.data instanceof URL ? { image_url: part.data.toString() } : typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : { image_url: `data:${mediaType};base64,${convertToBase64(part.data)}` },
1808
+ detail: (_b2 = (_a2 = part.providerOptions) == null ? void 0 : _a2[providerOptionsName]) == null ? void 0 : _b2.imageDetail
1809
+ };
1810
+ } else if (part.mediaType === "application/pdf") {
1811
+ if (part.data instanceof URL) return {
1812
+ type: "input_file",
1813
+ file_url: part.data.toString()
1814
+ };
1815
+ return {
1816
+ type: "input_file",
1817
+ ...typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : {
1818
+ filename: (_c2 = part.filename) != null ? _c2 : `part-${index}.pdf`,
1819
+ file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`
1820
+ }
1821
+ };
1822
+ } else throw new UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` });
1823
+ }
1824
+ })
1825
+ });
1826
+ break;
1827
+ case "assistant": {
1828
+ const reasoningMessages = {};
1829
+ for (const part of content) switch (part.type) {
1830
+ case "text": {
1831
+ const id = (_b = (_a = part.providerOptions) == null ? void 0 : _a[providerOptionsName]) == null ? void 0 : _b.itemId;
1832
+ if (hasConversation && id != null) break;
1833
+ if (store && id != null) {
1834
+ input.push({
1835
+ type: "item_reference",
1836
+ id
1837
+ });
1838
+ break;
1839
+ }
1840
+ input.push({
1841
+ role: "assistant",
1842
+ content: [{
1843
+ type: "output_text",
1844
+ text: part.text
1845
+ }],
1846
+ id
1847
+ });
1848
+ break;
1849
+ }
1850
+ case "tool-call": {
1851
+ const id = (_g = (_d = (_c = part.providerOptions) == null ? void 0 : _c[providerOptionsName]) == null ? void 0 : _d.itemId) != null ? _g : (_f = (_e = part.providerMetadata) == null ? void 0 : _e[providerOptionsName]) == null ? void 0 : _f.itemId;
1852
+ if (hasConversation && id != null) break;
1853
+ if (part.providerExecuted) {
1854
+ if (store && id != null) input.push({
1855
+ type: "item_reference",
1856
+ id
1857
+ });
1858
+ break;
1859
+ }
1860
+ if (store && id != null) {
1861
+ input.push({
1862
+ type: "item_reference",
1863
+ id
1864
+ });
1865
+ break;
1866
+ }
1867
+ const resolvedToolName = toolNameMapping.toProviderToolName(part.toolName);
1868
+ if (hasLocalShellTool && resolvedToolName === "local_shell") {
1869
+ const parsedInput = await validateTypes({
1870
+ value: part.input,
1871
+ schema: localShellInputSchema
1872
+ });
1873
+ input.push({
1874
+ type: "local_shell_call",
1875
+ call_id: part.toolCallId,
1876
+ id,
1877
+ action: {
1878
+ type: "exec",
1879
+ command: parsedInput.action.command,
1880
+ timeout_ms: parsedInput.action.timeoutMs,
1881
+ user: parsedInput.action.user,
1882
+ working_directory: parsedInput.action.workingDirectory,
1883
+ env: parsedInput.action.env
1884
+ }
1885
+ });
1886
+ break;
1887
+ }
1888
+ if (hasShellTool && resolvedToolName === "shell") {
1889
+ const parsedInput = await validateTypes({
1890
+ value: part.input,
1891
+ schema: shellInputSchema
1892
+ });
1893
+ input.push({
1894
+ type: "shell_call",
1895
+ call_id: part.toolCallId,
1896
+ id,
1897
+ status: "completed",
1898
+ action: {
1899
+ commands: parsedInput.action.commands,
1900
+ timeout_ms: parsedInput.action.timeoutMs,
1901
+ max_output_length: parsedInput.action.maxOutputLength
1902
+ }
1903
+ });
1904
+ break;
1905
+ }
1906
+ if (hasApplyPatchTool && resolvedToolName === "apply_patch") {
1907
+ const parsedInput = await validateTypes({
1908
+ value: part.input,
1909
+ schema: applyPatchInputSchema
1910
+ });
1911
+ input.push({
1912
+ type: "apply_patch_call",
1913
+ call_id: parsedInput.callId,
1914
+ id,
1915
+ status: "completed",
1916
+ operation: parsedInput.operation
1917
+ });
1918
+ break;
1919
+ }
1920
+ input.push({
1921
+ type: "function_call",
1922
+ call_id: part.toolCallId,
1923
+ name: resolvedToolName,
1924
+ arguments: JSON.stringify(part.input),
1925
+ id
1926
+ });
1927
+ break;
1928
+ }
1929
+ case "tool-result":
1930
+ if (part.output.type === "execution-denied" || part.output.type === "json" && typeof part.output.value === "object" && part.output.value != null && "type" in part.output.value && part.output.value.type === "execution-denied") break;
1931
+ if (hasConversation) break;
1932
+ if (store) {
1933
+ const itemId = (_j = (_i = (_h = part.providerMetadata) == null ? void 0 : _h[providerOptionsName]) == null ? void 0 : _i.itemId) != null ? _j : part.toolCallId;
1934
+ input.push({
1935
+ type: "item_reference",
1936
+ id: itemId
1937
+ });
1938
+ } else warnings.push({
1939
+ type: "other",
1940
+ message: `Results for OpenAI tool ${part.toolName} are not sent to the API when store is false`
1941
+ });
1942
+ break;
1943
+ case "reasoning": {
1944
+ const providerOptions = await parseProviderOptions({
1945
+ provider: providerOptionsName,
1946
+ providerOptions: part.providerOptions,
1947
+ schema: openaiResponsesReasoningProviderOptionsSchema
1948
+ });
1949
+ const reasoningId = providerOptions == null ? void 0 : providerOptions.itemId;
1950
+ if (hasConversation && reasoningId != null) break;
1951
+ if (reasoningId != null) {
1952
+ const reasoningMessage = reasoningMessages[reasoningId];
1953
+ if (store) {
1954
+ if (reasoningMessage === void 0) {
1955
+ input.push({
1956
+ type: "item_reference",
1957
+ id: reasoningId
1958
+ });
1959
+ reasoningMessages[reasoningId] = {
1960
+ type: "reasoning",
1961
+ id: reasoningId,
1962
+ summary: []
1963
+ };
1964
+ }
1965
+ } else {
1966
+ const summaryParts = [];
1967
+ if (part.text.length > 0) summaryParts.push({
1968
+ type: "summary_text",
1969
+ text: part.text
1970
+ });
1971
+ else if (reasoningMessage !== void 0) warnings.push({
1972
+ type: "other",
1973
+ message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.`
1974
+ });
1975
+ if (reasoningMessage === void 0) {
1976
+ reasoningMessages[reasoningId] = {
1977
+ type: "reasoning",
1978
+ id: reasoningId,
1979
+ encrypted_content: providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent,
1980
+ summary: summaryParts
1981
+ };
1982
+ input.push(reasoningMessages[reasoningId]);
1983
+ } else {
1984
+ reasoningMessage.summary.push(...summaryParts);
1985
+ if ((providerOptions == null ? void 0 : providerOptions.reasoningEncryptedContent) != null) reasoningMessage.encrypted_content = providerOptions.reasoningEncryptedContent;
1986
+ }
1987
+ }
1988
+ } else warnings.push({
1989
+ type: "other",
1990
+ message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`
1991
+ });
1992
+ break;
1993
+ }
1994
+ }
1995
+ break;
1996
+ }
1997
+ case "tool":
1998
+ for (const part of content) {
1999
+ if (part.type === "tool-approval-response") {
2000
+ const approvalResponse = part;
2001
+ if (processedApprovalIds.has(approvalResponse.approvalId)) continue;
2002
+ processedApprovalIds.add(approvalResponse.approvalId);
2003
+ if (store) input.push({
2004
+ type: "item_reference",
2005
+ id: approvalResponse.approvalId
2006
+ });
2007
+ input.push({
2008
+ type: "mcp_approval_response",
2009
+ approval_request_id: approvalResponse.approvalId,
2010
+ approve: approvalResponse.approved
2011
+ });
2012
+ continue;
2013
+ }
2014
+ const output = part.output;
2015
+ if (output.type === "execution-denied") {
2016
+ if ((_l = (_k = output.providerOptions) == null ? void 0 : _k.openai) == null ? void 0 : _l.approvalId) continue;
2017
+ }
2018
+ const resolvedToolName = toolNameMapping.toProviderToolName(part.toolName);
2019
+ if (hasLocalShellTool && resolvedToolName === "local_shell" && output.type === "json") {
2020
+ const parsedOutput = await validateTypes({
2021
+ value: output.value,
2022
+ schema: localShellOutputSchema
2023
+ });
2024
+ input.push({
2025
+ type: "local_shell_call_output",
2026
+ call_id: part.toolCallId,
2027
+ output: parsedOutput.output
2028
+ });
2029
+ continue;
2030
+ }
2031
+ if (hasShellTool && resolvedToolName === "shell" && output.type === "json") {
2032
+ const parsedOutput = await validateTypes({
2033
+ value: output.value,
2034
+ schema: shellOutputSchema
2035
+ });
2036
+ input.push({
2037
+ type: "shell_call_output",
2038
+ call_id: part.toolCallId,
2039
+ output: parsedOutput.output.map((item) => ({
2040
+ stdout: item.stdout,
2041
+ stderr: item.stderr,
2042
+ outcome: item.outcome.type === "timeout" ? { type: "timeout" } : {
2043
+ type: "exit",
2044
+ exit_code: item.outcome.exitCode
2045
+ }
2046
+ }))
2047
+ });
2048
+ continue;
2049
+ }
2050
+ if (hasApplyPatchTool && part.toolName === "apply_patch" && output.type === "json") {
2051
+ const parsedOutput = await validateTypes({
2052
+ value: output.value,
2053
+ schema: applyPatchOutputSchema
2054
+ });
2055
+ input.push({
2056
+ type: "apply_patch_call_output",
2057
+ call_id: part.toolCallId,
2058
+ status: parsedOutput.status,
2059
+ output: parsedOutput.output
2060
+ });
2061
+ continue;
2062
+ }
2063
+ let contentValue;
2064
+ switch (output.type) {
2065
+ case "text":
2066
+ case "error-text":
2067
+ contentValue = output.value;
2068
+ break;
2069
+ case "execution-denied":
2070
+ contentValue = (_m = output.reason) != null ? _m : "Tool execution denied.";
2071
+ break;
2072
+ case "json":
2073
+ case "error-json":
2074
+ contentValue = JSON.stringify(output.value);
2075
+ break;
2076
+ case "content":
2077
+ contentValue = output.value.map((item) => {
2078
+ var _a2;
2079
+ switch (item.type) {
2080
+ case "text": return {
2081
+ type: "input_text",
2082
+ text: item.text
2083
+ };
2084
+ case "image-data": return {
2085
+ type: "input_image",
2086
+ image_url: `data:${item.mediaType};base64,${item.data}`
2087
+ };
2088
+ case "image-url": return {
2089
+ type: "input_image",
2090
+ image_url: item.url
2091
+ };
2092
+ case "file-data": return {
2093
+ type: "input_file",
2094
+ filename: (_a2 = item.filename) != null ? _a2 : "data",
2095
+ file_data: `data:${item.mediaType};base64,${item.data}`
2096
+ };
2097
+ default:
2098
+ warnings.push({
2099
+ type: "other",
2100
+ message: `unsupported tool content part type: ${item.type}`
2101
+ });
2102
+ return;
2103
+ }
2104
+ }).filter(isNonNullable);
2105
+ break;
2106
+ }
2107
+ input.push({
2108
+ type: "function_call_output",
2109
+ call_id: part.toolCallId,
2110
+ output: contentValue
2111
+ });
2112
+ }
2113
+ break;
2114
+ default: {
2115
+ const _exhaustiveCheck = role;
2116
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
2117
+ }
2118
+ }
2119
+ return {
2120
+ input,
2121
+ warnings
2122
+ };
2123
+ }
2124
+ var openaiResponsesReasoningProviderOptionsSchema = object({
2125
+ itemId: string().nullish(),
2126
+ reasoningEncryptedContent: string().nullish()
2127
+ });
2128
+ function mapOpenAIResponseFinishReason({ finishReason, hasFunctionCall }) {
2129
+ switch (finishReason) {
2130
+ case void 0:
2131
+ case null: return hasFunctionCall ? "tool-calls" : "stop";
2132
+ case "max_output_tokens": return "length";
2133
+ case "content_filter": return "content-filter";
2134
+ default: return hasFunctionCall ? "tool-calls" : "other";
2135
+ }
2136
+ }
2137
+ var openaiResponsesChunkSchema = lazySchema(() => zodSchema(union([
2138
+ object({
2139
+ type: literal("response.output_text.delta"),
2140
+ item_id: string(),
2141
+ delta: string(),
2142
+ logprobs: array(object({
2143
+ token: string(),
2144
+ logprob: number$1(),
2145
+ top_logprobs: array(object({
2146
+ token: string(),
2147
+ logprob: number$1()
2148
+ }))
2149
+ })).nullish()
2150
+ }),
2151
+ object({
2152
+ type: _enum(["response.completed", "response.incomplete"]),
2153
+ response: object({
2154
+ incomplete_details: object({ reason: string() }).nullish(),
2155
+ usage: object({
2156
+ input_tokens: number$1(),
2157
+ input_tokens_details: object({ cached_tokens: number$1().nullish() }).nullish(),
2158
+ output_tokens: number$1(),
2159
+ output_tokens_details: object({ reasoning_tokens: number$1().nullish() }).nullish()
2160
+ }),
2161
+ service_tier: string().nullish()
2162
+ })
2163
+ }),
2164
+ object({
2165
+ type: literal("response.created"),
2166
+ response: object({
2167
+ id: string(),
2168
+ created_at: number$1(),
2169
+ model: string(),
2170
+ service_tier: string().nullish()
2171
+ })
2172
+ }),
2173
+ object({
2174
+ type: literal("response.output_item.added"),
2175
+ output_index: number$1(),
2176
+ item: discriminatedUnion("type", [
2177
+ object({
2178
+ type: literal("message"),
2179
+ id: string()
2180
+ }),
2181
+ object({
2182
+ type: literal("reasoning"),
2183
+ id: string(),
2184
+ encrypted_content: string().nullish()
2185
+ }),
2186
+ object({
2187
+ type: literal("function_call"),
2188
+ id: string(),
2189
+ call_id: string(),
2190
+ name: string(),
2191
+ arguments: string()
2192
+ }),
2193
+ object({
2194
+ type: literal("web_search_call"),
2195
+ id: string(),
2196
+ status: string()
2197
+ }),
2198
+ object({
2199
+ type: literal("computer_call"),
2200
+ id: string(),
2201
+ status: string()
2202
+ }),
2203
+ object({
2204
+ type: literal("file_search_call"),
2205
+ id: string()
2206
+ }),
2207
+ object({
2208
+ type: literal("image_generation_call"),
2209
+ id: string()
2210
+ }),
2211
+ object({
2212
+ type: literal("code_interpreter_call"),
2213
+ id: string(),
2214
+ container_id: string(),
2215
+ code: string().nullable(),
2216
+ outputs: array(discriminatedUnion("type", [object({
2217
+ type: literal("logs"),
2218
+ logs: string()
2219
+ }), object({
2220
+ type: literal("image"),
2221
+ url: string()
2222
+ })])).nullable(),
2223
+ status: string()
2224
+ }),
2225
+ object({
2226
+ type: literal("mcp_call"),
2227
+ id: string(),
2228
+ status: string(),
2229
+ approval_request_id: string().nullish()
2230
+ }),
2231
+ object({
2232
+ type: literal("mcp_list_tools"),
2233
+ id: string()
2234
+ }),
2235
+ object({
2236
+ type: literal("mcp_approval_request"),
2237
+ id: string()
2238
+ }),
2239
+ object({
2240
+ type: literal("apply_patch_call"),
2241
+ id: string(),
2242
+ call_id: string(),
2243
+ status: _enum(["in_progress", "completed"]),
2244
+ operation: discriminatedUnion("type", [
2245
+ object({
2246
+ type: literal("create_file"),
2247
+ path: string(),
2248
+ diff: string()
2249
+ }),
2250
+ object({
2251
+ type: literal("delete_file"),
2252
+ path: string()
2253
+ }),
2254
+ object({
2255
+ type: literal("update_file"),
2256
+ path: string(),
2257
+ diff: string()
2258
+ })
2259
+ ])
2260
+ }),
2261
+ object({
2262
+ type: literal("shell_call"),
2263
+ id: string(),
2264
+ call_id: string(),
2265
+ status: _enum([
2266
+ "in_progress",
2267
+ "completed",
2268
+ "incomplete"
2269
+ ]),
2270
+ action: object({ commands: array(string()) })
2271
+ })
2272
+ ])
2273
+ }),
2274
+ object({
2275
+ type: literal("response.output_item.done"),
2276
+ output_index: number$1(),
2277
+ item: discriminatedUnion("type", [
2278
+ object({
2279
+ type: literal("message"),
2280
+ id: string()
2281
+ }),
2282
+ object({
2283
+ type: literal("reasoning"),
2284
+ id: string(),
2285
+ encrypted_content: string().nullish()
2286
+ }),
2287
+ object({
2288
+ type: literal("function_call"),
2289
+ id: string(),
2290
+ call_id: string(),
2291
+ name: string(),
2292
+ arguments: string(),
2293
+ status: literal("completed")
2294
+ }),
2295
+ object({
2296
+ type: literal("code_interpreter_call"),
2297
+ id: string(),
2298
+ code: string().nullable(),
2299
+ container_id: string(),
2300
+ outputs: array(discriminatedUnion("type", [object({
2301
+ type: literal("logs"),
2302
+ logs: string()
2303
+ }), object({
2304
+ type: literal("image"),
2305
+ url: string()
2306
+ })])).nullable()
2307
+ }),
2308
+ object({
2309
+ type: literal("image_generation_call"),
2310
+ id: string(),
2311
+ result: string()
2312
+ }),
2313
+ object({
2314
+ type: literal("web_search_call"),
2315
+ id: string(),
2316
+ status: string(),
2317
+ action: discriminatedUnion("type", [
2318
+ object({
2319
+ type: literal("search"),
2320
+ query: string().nullish(),
2321
+ sources: array(discriminatedUnion("type", [object({
2322
+ type: literal("url"),
2323
+ url: string()
2324
+ }), object({
2325
+ type: literal("api"),
2326
+ name: string()
2327
+ })])).nullish()
2328
+ }),
2329
+ object({
2330
+ type: literal("open_page"),
2331
+ url: string().nullish()
2332
+ }),
2333
+ object({
2334
+ type: literal("find_in_page"),
2335
+ url: string().nullish(),
2336
+ pattern: string().nullish()
2337
+ })
2338
+ ])
2339
+ }),
2340
+ object({
2341
+ type: literal("file_search_call"),
2342
+ id: string(),
2343
+ queries: array(string()),
2344
+ results: array(object({
2345
+ attributes: record(string(), union([
2346
+ string(),
2347
+ number$1(),
2348
+ boolean()
2349
+ ])),
2350
+ file_id: string(),
2351
+ filename: string(),
2352
+ score: number$1(),
2353
+ text: string()
2354
+ })).nullish()
2355
+ }),
2356
+ object({
2357
+ type: literal("local_shell_call"),
2358
+ id: string(),
2359
+ call_id: string(),
2360
+ action: object({
2361
+ type: literal("exec"),
2362
+ command: array(string()),
2363
+ timeout_ms: number$1().optional(),
2364
+ user: string().optional(),
2365
+ working_directory: string().optional(),
2366
+ env: record(string(), string()).optional()
2367
+ })
2368
+ }),
2369
+ object({
2370
+ type: literal("computer_call"),
2371
+ id: string(),
2372
+ status: literal("completed")
2373
+ }),
2374
+ object({
2375
+ type: literal("mcp_call"),
2376
+ id: string(),
2377
+ status: string(),
2378
+ arguments: string(),
2379
+ name: string(),
2380
+ server_label: string(),
2381
+ output: string().nullish(),
2382
+ error: union([string(), object({
2383
+ type: string().optional(),
2384
+ code: union([number$1(), string()]).optional(),
2385
+ message: string().optional()
2386
+ }).loose()]).nullish(),
2387
+ approval_request_id: string().nullish()
2388
+ }),
2389
+ object({
2390
+ type: literal("mcp_list_tools"),
2391
+ id: string(),
2392
+ server_label: string(),
2393
+ tools: array(object({
2394
+ name: string(),
2395
+ description: string().optional(),
2396
+ input_schema: any(),
2397
+ annotations: record(string(), unknown()).optional()
2398
+ })),
2399
+ error: union([string(), object({
2400
+ type: string().optional(),
2401
+ code: union([number$1(), string()]).optional(),
2402
+ message: string().optional()
2403
+ }).loose()]).optional()
2404
+ }),
2405
+ object({
2406
+ type: literal("mcp_approval_request"),
2407
+ id: string(),
2408
+ server_label: string(),
2409
+ name: string(),
2410
+ arguments: string(),
2411
+ approval_request_id: string().optional()
2412
+ }),
2413
+ object({
2414
+ type: literal("apply_patch_call"),
2415
+ id: string(),
2416
+ call_id: string(),
2417
+ status: _enum(["in_progress", "completed"]),
2418
+ operation: discriminatedUnion("type", [
2419
+ object({
2420
+ type: literal("create_file"),
2421
+ path: string(),
2422
+ diff: string()
2423
+ }),
2424
+ object({
2425
+ type: literal("delete_file"),
2426
+ path: string()
2427
+ }),
2428
+ object({
2429
+ type: literal("update_file"),
2430
+ path: string(),
2431
+ diff: string()
2432
+ })
2433
+ ])
2434
+ }),
2435
+ object({
2436
+ type: literal("shell_call"),
2437
+ id: string(),
2438
+ call_id: string(),
2439
+ status: _enum([
2440
+ "in_progress",
2441
+ "completed",
2442
+ "incomplete"
2443
+ ]),
2444
+ action: object({ commands: array(string()) })
2445
+ })
2446
+ ])
2447
+ }),
2448
+ object({
2449
+ type: literal("response.function_call_arguments.delta"),
2450
+ item_id: string(),
2451
+ output_index: number$1(),
2452
+ delta: string()
2453
+ }),
2454
+ object({
2455
+ type: literal("response.image_generation_call.partial_image"),
2456
+ item_id: string(),
2457
+ output_index: number$1(),
2458
+ partial_image_b64: string()
2459
+ }),
2460
+ object({
2461
+ type: literal("response.code_interpreter_call_code.delta"),
2462
+ item_id: string(),
2463
+ output_index: number$1(),
2464
+ delta: string()
2465
+ }),
2466
+ object({
2467
+ type: literal("response.code_interpreter_call_code.done"),
2468
+ item_id: string(),
2469
+ output_index: number$1(),
2470
+ code: string()
2471
+ }),
2472
+ object({
2473
+ type: literal("response.output_text.annotation.added"),
2474
+ annotation: discriminatedUnion("type", [
2475
+ object({
2476
+ type: literal("url_citation"),
2477
+ start_index: number$1(),
2478
+ end_index: number$1(),
2479
+ url: string(),
2480
+ title: string()
2481
+ }),
2482
+ object({
2483
+ type: literal("file_citation"),
2484
+ file_id: string(),
2485
+ filename: string(),
2486
+ index: number$1()
2487
+ }),
2488
+ object({
2489
+ type: literal("container_file_citation"),
2490
+ container_id: string(),
2491
+ file_id: string(),
2492
+ filename: string(),
2493
+ start_index: number$1(),
2494
+ end_index: number$1()
2495
+ }),
2496
+ object({
2497
+ type: literal("file_path"),
2498
+ file_id: string(),
2499
+ index: number$1()
2500
+ })
2501
+ ])
2502
+ }),
2503
+ object({
2504
+ type: literal("response.reasoning_summary_part.added"),
2505
+ item_id: string(),
2506
+ summary_index: number$1()
2507
+ }),
2508
+ object({
2509
+ type: literal("response.reasoning_summary_text.delta"),
2510
+ item_id: string(),
2511
+ summary_index: number$1(),
2512
+ delta: string()
2513
+ }),
2514
+ object({
2515
+ type: literal("response.reasoning_summary_part.done"),
2516
+ item_id: string(),
2517
+ summary_index: number$1()
2518
+ }),
2519
+ object({
2520
+ type: literal("response.apply_patch_call_operation_diff.delta"),
2521
+ item_id: string(),
2522
+ output_index: number$1(),
2523
+ delta: string(),
2524
+ obfuscation: string().nullish()
2525
+ }),
2526
+ object({
2527
+ type: literal("response.apply_patch_call_operation_diff.done"),
2528
+ item_id: string(),
2529
+ output_index: number$1(),
2530
+ diff: string()
2531
+ }),
2532
+ object({
2533
+ type: literal("error"),
2534
+ sequence_number: number$1(),
2535
+ error: object({
2536
+ type: string(),
2537
+ code: string(),
2538
+ message: string(),
2539
+ param: string().nullish()
2540
+ })
2541
+ }),
2542
+ object({ type: string() }).loose().transform((value) => ({
2543
+ type: "unknown_chunk",
2544
+ message: value.type
2545
+ }))
2546
+ ])));
2547
+ var openaiResponsesResponseSchema = lazySchema(() => zodSchema(object({
2548
+ id: string().optional(),
2549
+ created_at: number$1().optional(),
2550
+ error: object({
2551
+ message: string(),
2552
+ type: string(),
2553
+ param: string().nullish(),
2554
+ code: string()
2555
+ }).nullish(),
2556
+ model: string().optional(),
2557
+ output: array(discriminatedUnion("type", [
2558
+ object({
2559
+ type: literal("message"),
2560
+ role: literal("assistant"),
2561
+ id: string(),
2562
+ content: array(object({
2563
+ type: literal("output_text"),
2564
+ text: string(),
2565
+ logprobs: array(object({
2566
+ token: string(),
2567
+ logprob: number$1(),
2568
+ top_logprobs: array(object({
2569
+ token: string(),
2570
+ logprob: number$1()
2571
+ }))
2572
+ })).nullish(),
2573
+ annotations: array(discriminatedUnion("type", [
2574
+ object({
2575
+ type: literal("url_citation"),
2576
+ start_index: number$1(),
2577
+ end_index: number$1(),
2578
+ url: string(),
2579
+ title: string()
2580
+ }),
2581
+ object({
2582
+ type: literal("file_citation"),
2583
+ file_id: string(),
2584
+ filename: string(),
2585
+ index: number$1()
2586
+ }),
2587
+ object({
2588
+ type: literal("container_file_citation"),
2589
+ container_id: string(),
2590
+ file_id: string(),
2591
+ filename: string(),
2592
+ start_index: number$1(),
2593
+ end_index: number$1()
2594
+ }),
2595
+ object({
2596
+ type: literal("file_path"),
2597
+ file_id: string(),
2598
+ index: number$1()
2599
+ })
2600
+ ]))
2601
+ }))
2602
+ }),
2603
+ object({
2604
+ type: literal("web_search_call"),
2605
+ id: string(),
2606
+ status: string(),
2607
+ action: discriminatedUnion("type", [
2608
+ object({
2609
+ type: literal("search"),
2610
+ query: string().nullish(),
2611
+ sources: array(discriminatedUnion("type", [object({
2612
+ type: literal("url"),
2613
+ url: string()
2614
+ }), object({
2615
+ type: literal("api"),
2616
+ name: string()
2617
+ })])).nullish()
2618
+ }),
2619
+ object({
2620
+ type: literal("open_page"),
2621
+ url: string().nullish()
2622
+ }),
2623
+ object({
2624
+ type: literal("find_in_page"),
2625
+ url: string().nullish(),
2626
+ pattern: string().nullish()
2627
+ })
2628
+ ])
2629
+ }),
2630
+ object({
2631
+ type: literal("file_search_call"),
2632
+ id: string(),
2633
+ queries: array(string()),
2634
+ results: array(object({
2635
+ attributes: record(string(), union([
2636
+ string(),
2637
+ number$1(),
2638
+ boolean()
2639
+ ])),
2640
+ file_id: string(),
2641
+ filename: string(),
2642
+ score: number$1(),
2643
+ text: string()
2644
+ })).nullish()
2645
+ }),
2646
+ object({
2647
+ type: literal("code_interpreter_call"),
2648
+ id: string(),
2649
+ code: string().nullable(),
2650
+ container_id: string(),
2651
+ outputs: array(discriminatedUnion("type", [object({
2652
+ type: literal("logs"),
2653
+ logs: string()
2654
+ }), object({
2655
+ type: literal("image"),
2656
+ url: string()
2657
+ })])).nullable()
2658
+ }),
2659
+ object({
2660
+ type: literal("image_generation_call"),
2661
+ id: string(),
2662
+ result: string()
2663
+ }),
2664
+ object({
2665
+ type: literal("local_shell_call"),
2666
+ id: string(),
2667
+ call_id: string(),
2668
+ action: object({
2669
+ type: literal("exec"),
2670
+ command: array(string()),
2671
+ timeout_ms: number$1().optional(),
2672
+ user: string().optional(),
2673
+ working_directory: string().optional(),
2674
+ env: record(string(), string()).optional()
2675
+ })
2676
+ }),
2677
+ object({
2678
+ type: literal("function_call"),
2679
+ call_id: string(),
2680
+ name: string(),
2681
+ arguments: string(),
2682
+ id: string()
2683
+ }),
2684
+ object({
2685
+ type: literal("computer_call"),
2686
+ id: string(),
2687
+ status: string().optional()
2688
+ }),
2689
+ object({
2690
+ type: literal("reasoning"),
2691
+ id: string(),
2692
+ encrypted_content: string().nullish(),
2693
+ summary: array(object({
2694
+ type: literal("summary_text"),
2695
+ text: string()
2696
+ }))
2697
+ }),
2698
+ object({
2699
+ type: literal("mcp_call"),
2700
+ id: string(),
2701
+ status: string(),
2702
+ arguments: string(),
2703
+ name: string(),
2704
+ server_label: string(),
2705
+ output: string().nullish(),
2706
+ error: union([string(), object({
2707
+ type: string().optional(),
2708
+ code: union([number$1(), string()]).optional(),
2709
+ message: string().optional()
2710
+ }).loose()]).nullish(),
2711
+ approval_request_id: string().nullish()
2712
+ }),
2713
+ object({
2714
+ type: literal("mcp_list_tools"),
2715
+ id: string(),
2716
+ server_label: string(),
2717
+ tools: array(object({
2718
+ name: string(),
2719
+ description: string().optional(),
2720
+ input_schema: any(),
2721
+ annotations: record(string(), unknown()).optional()
2722
+ })),
2723
+ error: union([string(), object({
2724
+ type: string().optional(),
2725
+ code: union([number$1(), string()]).optional(),
2726
+ message: string().optional()
2727
+ }).loose()]).optional()
2728
+ }),
2729
+ object({
2730
+ type: literal("mcp_approval_request"),
2731
+ id: string(),
2732
+ server_label: string(),
2733
+ name: string(),
2734
+ arguments: string(),
2735
+ approval_request_id: string().optional()
2736
+ }),
2737
+ object({
2738
+ type: literal("apply_patch_call"),
2739
+ id: string(),
2740
+ call_id: string(),
2741
+ status: _enum(["in_progress", "completed"]),
2742
+ operation: discriminatedUnion("type", [
2743
+ object({
2744
+ type: literal("create_file"),
2745
+ path: string(),
2746
+ diff: string()
2747
+ }),
2748
+ object({
2749
+ type: literal("delete_file"),
2750
+ path: string()
2751
+ }),
2752
+ object({
2753
+ type: literal("update_file"),
2754
+ path: string(),
2755
+ diff: string()
2756
+ })
2757
+ ])
2758
+ }),
2759
+ object({
2760
+ type: literal("shell_call"),
2761
+ id: string(),
2762
+ call_id: string(),
2763
+ status: _enum([
2764
+ "in_progress",
2765
+ "completed",
2766
+ "incomplete"
2767
+ ]),
2768
+ action: object({ commands: array(string()) })
2769
+ })
2770
+ ])).optional(),
2771
+ service_tier: string().nullish(),
2772
+ incomplete_details: object({ reason: string() }).nullish(),
2773
+ usage: object({
2774
+ input_tokens: number$1(),
2775
+ input_tokens_details: object({ cached_tokens: number$1().nullish() }).nullish(),
2776
+ output_tokens: number$1(),
2777
+ output_tokens_details: object({ reasoning_tokens: number$1().nullish() }).nullish()
2778
+ }).optional()
2779
+ })));
2780
+ var TOP_LOGPROBS_MAX = 20;
2781
+ var openaiResponsesProviderOptionsSchema = lazySchema(() => zodSchema(object({
2782
+ conversation: string().nullish(),
2783
+ include: array(_enum([
2784
+ "reasoning.encrypted_content",
2785
+ "file_search_call.results",
2786
+ "message.output_text.logprobs"
2787
+ ])).nullish(),
2788
+ instructions: string().nullish(),
2789
+ logprobs: union([boolean(), number$1().min(1).max(TOP_LOGPROBS_MAX)]).optional(),
2790
+ maxToolCalls: number$1().nullish(),
2791
+ metadata: any().nullish(),
2792
+ parallelToolCalls: boolean().nullish(),
2793
+ previousResponseId: string().nullish(),
2794
+ promptCacheKey: string().nullish(),
2795
+ promptCacheRetention: _enum(["in_memory", "24h"]).nullish(),
2796
+ reasoningEffort: string().nullish(),
2797
+ reasoningSummary: string().nullish(),
2798
+ safetyIdentifier: string().nullish(),
2799
+ serviceTier: _enum([
2800
+ "auto",
2801
+ "flex",
2802
+ "priority",
2803
+ "default"
2804
+ ]).nullish(),
2805
+ store: boolean().nullish(),
2806
+ strictJsonSchema: boolean().nullish(),
2807
+ textVerbosity: _enum([
2808
+ "low",
2809
+ "medium",
2810
+ "high"
2811
+ ]).nullish(),
2812
+ truncation: _enum(["auto", "disabled"]).nullish(),
2813
+ user: string().nullish(),
2814
+ systemMessageMode: _enum([
2815
+ "system",
2816
+ "developer",
2817
+ "remove"
2818
+ ]).optional(),
2819
+ forceReasoning: boolean().optional()
2820
+ })));
2821
+ async function prepareResponsesTools({ tools, toolChoice }) {
2822
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
2823
+ const toolWarnings = [];
2824
+ if (tools == null) return {
2825
+ tools: void 0,
2826
+ toolChoice: void 0,
2827
+ toolWarnings
2828
+ };
2829
+ const openaiTools2 = [];
2830
+ for (const tool of tools) switch (tool.type) {
2831
+ case "function":
2832
+ openaiTools2.push({
2833
+ type: "function",
2834
+ name: tool.name,
2835
+ description: tool.description,
2836
+ parameters: tool.inputSchema,
2837
+ ...tool.strict != null ? { strict: tool.strict } : {}
2838
+ });
2839
+ break;
2840
+ case "provider":
2841
+ switch (tool.id) {
2842
+ case "openai.file_search": {
2843
+ const args = await validateTypes({
2844
+ value: tool.args,
2845
+ schema: fileSearchArgsSchema
2846
+ });
2847
+ openaiTools2.push({
2848
+ type: "file_search",
2849
+ vector_store_ids: args.vectorStoreIds,
2850
+ max_num_results: args.maxNumResults,
2851
+ ranking_options: args.ranking ? {
2852
+ ranker: args.ranking.ranker,
2853
+ score_threshold: args.ranking.scoreThreshold
2854
+ } : void 0,
2855
+ filters: args.filters
2856
+ });
2857
+ break;
2858
+ }
2859
+ case "openai.local_shell":
2860
+ openaiTools2.push({ type: "local_shell" });
2861
+ break;
2862
+ case "openai.shell":
2863
+ openaiTools2.push({ type: "shell" });
2864
+ break;
2865
+ case "openai.apply_patch":
2866
+ openaiTools2.push({ type: "apply_patch" });
2867
+ break;
2868
+ case "openai.web_search_preview": {
2869
+ const args = await validateTypes({
2870
+ value: tool.args,
2871
+ schema: webSearchPreviewArgsSchema
2872
+ });
2873
+ openaiTools2.push({
2874
+ type: "web_search_preview",
2875
+ search_context_size: args.searchContextSize,
2876
+ user_location: args.userLocation
2877
+ });
2878
+ break;
2879
+ }
2880
+ case "openai.web_search": {
2881
+ const args = await validateTypes({
2882
+ value: tool.args,
2883
+ schema: webSearchArgsSchema
2884
+ });
2885
+ openaiTools2.push({
2886
+ type: "web_search",
2887
+ filters: args.filters != null ? { allowed_domains: args.filters.allowedDomains } : void 0,
2888
+ external_web_access: args.externalWebAccess,
2889
+ search_context_size: args.searchContextSize,
2890
+ user_location: args.userLocation
2891
+ });
2892
+ break;
2893
+ }
2894
+ case "openai.code_interpreter": {
2895
+ const args = await validateTypes({
2896
+ value: tool.args,
2897
+ schema: codeInterpreterArgsSchema
2898
+ });
2899
+ openaiTools2.push({
2900
+ type: "code_interpreter",
2901
+ container: args.container == null ? {
2902
+ type: "auto",
2903
+ file_ids: void 0
2904
+ } : typeof args.container === "string" ? args.container : {
2905
+ type: "auto",
2906
+ file_ids: args.container.fileIds
2907
+ }
2908
+ });
2909
+ break;
2910
+ }
2911
+ case "openai.image_generation": {
2912
+ const args = await validateTypes({
2913
+ value: tool.args,
2914
+ schema: imageGenerationArgsSchema
2915
+ });
2916
+ openaiTools2.push({
2917
+ type: "image_generation",
2918
+ background: args.background,
2919
+ input_fidelity: args.inputFidelity,
2920
+ input_image_mask: args.inputImageMask ? {
2921
+ file_id: args.inputImageMask.fileId,
2922
+ image_url: args.inputImageMask.imageUrl
2923
+ } : void 0,
2924
+ model: args.model,
2925
+ moderation: args.moderation,
2926
+ partial_images: args.partialImages,
2927
+ quality: args.quality,
2928
+ output_compression: args.outputCompression,
2929
+ output_format: args.outputFormat,
2930
+ size: args.size
2931
+ });
2932
+ break;
2933
+ }
2934
+ case "openai.mcp": {
2935
+ const args = await validateTypes({
2936
+ value: tool.args,
2937
+ schema: mcpArgsSchema
2938
+ });
2939
+ const mapApprovalFilter = (filter) => ({ tool_names: filter.toolNames });
2940
+ const requireApproval = args.requireApproval;
2941
+ const requireApprovalParam = requireApproval == null ? void 0 : typeof requireApproval === "string" ? requireApproval : requireApproval.never != null ? { never: mapApprovalFilter(requireApproval.never) } : void 0;
2942
+ openaiTools2.push({
2943
+ type: "mcp",
2944
+ server_label: args.serverLabel,
2945
+ allowed_tools: Array.isArray(args.allowedTools) ? args.allowedTools : args.allowedTools ? {
2946
+ read_only: args.allowedTools.readOnly,
2947
+ tool_names: args.allowedTools.toolNames
2948
+ } : void 0,
2949
+ authorization: args.authorization,
2950
+ connector_id: args.connectorId,
2951
+ headers: args.headers,
2952
+ require_approval: requireApprovalParam != null ? requireApprovalParam : "never",
2953
+ server_description: args.serverDescription,
2954
+ server_url: args.serverUrl
2955
+ });
2956
+ break;
2957
+ }
2958
+ }
2959
+ break;
2960
+ default:
2961
+ toolWarnings.push({
2962
+ type: "unsupported",
2963
+ feature: `function tool ${tool}`
2964
+ });
2965
+ break;
2966
+ }
2967
+ if (toolChoice == null) return {
2968
+ tools: openaiTools2,
2969
+ toolChoice: void 0,
2970
+ toolWarnings
2971
+ };
2972
+ const type = toolChoice.type;
2973
+ switch (type) {
2974
+ case "auto":
2975
+ case "none":
2976
+ case "required": return {
2977
+ tools: openaiTools2,
2978
+ toolChoice: type,
2979
+ toolWarnings
2980
+ };
2981
+ case "tool": return {
2982
+ tools: openaiTools2,
2983
+ toolChoice: toolChoice.toolName === "code_interpreter" || toolChoice.toolName === "file_search" || toolChoice.toolName === "image_generation" || toolChoice.toolName === "web_search_preview" || toolChoice.toolName === "web_search" || toolChoice.toolName === "mcp" || toolChoice.toolName === "apply_patch" ? { type: toolChoice.toolName } : {
2984
+ type: "function",
2985
+ name: toolChoice.toolName
2986
+ },
2987
+ toolWarnings
2988
+ };
2989
+ default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
2990
+ }
2991
+ }
2992
+ function extractApprovalRequestIdToToolCallIdMapping(prompt) {
2993
+ var _a, _b;
2994
+ const mapping = {};
2995
+ for (const message of prompt) {
2996
+ if (message.role !== "assistant") continue;
2997
+ for (const part of message.content) {
2998
+ if (part.type !== "tool-call") continue;
2999
+ const approvalRequestId = (_b = (_a = part.providerOptions) == null ? void 0 : _a.openai) == null ? void 0 : _b.approvalRequestId;
3000
+ if (approvalRequestId != null) mapping[approvalRequestId] = part.toolCallId;
3001
+ }
3002
+ }
3003
+ return mapping;
3004
+ }
3005
+ var OpenAIResponsesLanguageModel = class {
3006
+ constructor(modelId, config) {
3007
+ this.specificationVersion = "v3";
3008
+ this.supportedUrls = {
3009
+ "image/*": [/^https?:\/\/.*$/],
3010
+ "application/pdf": [/^https?:\/\/.*$/]
3011
+ };
3012
+ this.modelId = modelId;
3013
+ this.config = config;
3014
+ }
3015
+ get provider() {
3016
+ return this.config.provider;
3017
+ }
3018
+ async getArgs({ maxOutputTokens, temperature, stopSequences, topP, topK, presencePenalty, frequencyPenalty, seed, prompt, providerOptions, tools, toolChoice, responseFormat }) {
3019
+ var _a, _b, _c, _d, _e, _f;
3020
+ const warnings = [];
3021
+ const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);
3022
+ if (topK != null) warnings.push({
3023
+ type: "unsupported",
3024
+ feature: "topK"
3025
+ });
3026
+ if (seed != null) warnings.push({
3027
+ type: "unsupported",
3028
+ feature: "seed"
3029
+ });
3030
+ if (presencePenalty != null) warnings.push({
3031
+ type: "unsupported",
3032
+ feature: "presencePenalty"
3033
+ });
3034
+ if (frequencyPenalty != null) warnings.push({
3035
+ type: "unsupported",
3036
+ feature: "frequencyPenalty"
3037
+ });
3038
+ if (stopSequences != null) warnings.push({
3039
+ type: "unsupported",
3040
+ feature: "stopSequences"
3041
+ });
3042
+ const providerOptionsName = this.config.provider.includes("azure") ? "azure" : "openai";
3043
+ let openaiOptions = await parseProviderOptions({
3044
+ provider: providerOptionsName,
3045
+ providerOptions,
3046
+ schema: openaiResponsesProviderOptionsSchema
3047
+ });
3048
+ if (openaiOptions == null && providerOptionsName !== "openai") openaiOptions = await parseProviderOptions({
3049
+ provider: "openai",
3050
+ providerOptions,
3051
+ schema: openaiResponsesProviderOptionsSchema
3052
+ });
3053
+ const isReasoningModel = (_a = openaiOptions == null ? void 0 : openaiOptions.forceReasoning) != null ? _a : modelCapabilities.isReasoningModel;
3054
+ if ((openaiOptions == null ? void 0 : openaiOptions.conversation) && (openaiOptions == null ? void 0 : openaiOptions.previousResponseId)) warnings.push({
3055
+ type: "unsupported",
3056
+ feature: "conversation",
3057
+ details: "conversation and previousResponseId cannot be used together"
3058
+ });
3059
+ const toolNameMapping = createToolNameMapping({
3060
+ tools,
3061
+ providerToolNames: {
3062
+ "openai.code_interpreter": "code_interpreter",
3063
+ "openai.file_search": "file_search",
3064
+ "openai.image_generation": "image_generation",
3065
+ "openai.local_shell": "local_shell",
3066
+ "openai.shell": "shell",
3067
+ "openai.web_search": "web_search",
3068
+ "openai.web_search_preview": "web_search_preview",
3069
+ "openai.mcp": "mcp",
3070
+ "openai.apply_patch": "apply_patch"
3071
+ }
3072
+ });
3073
+ const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
3074
+ prompt,
3075
+ toolNameMapping,
3076
+ systemMessageMode: (_b = openaiOptions == null ? void 0 : openaiOptions.systemMessageMode) != null ? _b : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode,
3077
+ providerOptionsName,
3078
+ fileIdPrefixes: this.config.fileIdPrefixes,
3079
+ store: (_c = openaiOptions == null ? void 0 : openaiOptions.store) != null ? _c : true,
3080
+ hasConversation: (openaiOptions == null ? void 0 : openaiOptions.conversation) != null,
3081
+ hasLocalShellTool: hasOpenAITool("openai.local_shell"),
3082
+ hasShellTool: hasOpenAITool("openai.shell"),
3083
+ hasApplyPatchTool: hasOpenAITool("openai.apply_patch")
3084
+ });
3085
+ warnings.push(...inputWarnings);
3086
+ const strictJsonSchema = (_d = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _d : true;
3087
+ let include = openaiOptions == null ? void 0 : openaiOptions.include;
3088
+ function addInclude(key) {
3089
+ if (include == null) include = [key];
3090
+ else if (!include.includes(key)) include = [...include, key];
3091
+ }
3092
+ function hasOpenAITool(id) {
3093
+ return (tools == null ? void 0 : tools.find((tool) => tool.type === "provider" && tool.id === id)) != null;
3094
+ }
3095
+ const topLogprobs = typeof (openaiOptions == null ? void 0 : openaiOptions.logprobs) === "number" ? openaiOptions == null ? void 0 : openaiOptions.logprobs : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? TOP_LOGPROBS_MAX : void 0;
3096
+ if (topLogprobs) addInclude("message.output_text.logprobs");
3097
+ const webSearchToolName = (_e = tools == null ? void 0 : tools.find((tool) => tool.type === "provider" && (tool.id === "openai.web_search" || tool.id === "openai.web_search_preview"))) == null ? void 0 : _e.name;
3098
+ if (webSearchToolName) addInclude("web_search_call.action.sources");
3099
+ if (hasOpenAITool("openai.code_interpreter")) addInclude("code_interpreter_call.outputs");
3100
+ const store = openaiOptions == null ? void 0 : openaiOptions.store;
3101
+ if (store === false && isReasoningModel) addInclude("reasoning.encrypted_content");
3102
+ const baseArgs = {
3103
+ model: this.modelId,
3104
+ input,
3105
+ temperature,
3106
+ top_p: topP,
3107
+ max_output_tokens: maxOutputTokens,
3108
+ ...((responseFormat == null ? void 0 : responseFormat.type) === "json" || (openaiOptions == null ? void 0 : openaiOptions.textVerbosity)) && { text: {
3109
+ ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && { format: responseFormat.schema != null ? {
3110
+ type: "json_schema",
3111
+ strict: strictJsonSchema,
3112
+ name: (_f = responseFormat.name) != null ? _f : "response",
3113
+ description: responseFormat.description,
3114
+ schema: responseFormat.schema
3115
+ } : { type: "json_object" } },
3116
+ ...(openaiOptions == null ? void 0 : openaiOptions.textVerbosity) && { verbosity: openaiOptions.textVerbosity }
3117
+ } },
3118
+ conversation: openaiOptions == null ? void 0 : openaiOptions.conversation,
3119
+ max_tool_calls: openaiOptions == null ? void 0 : openaiOptions.maxToolCalls,
3120
+ metadata: openaiOptions == null ? void 0 : openaiOptions.metadata,
3121
+ parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls,
3122
+ previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId,
3123
+ store,
3124
+ user: openaiOptions == null ? void 0 : openaiOptions.user,
3125
+ instructions: openaiOptions == null ? void 0 : openaiOptions.instructions,
3126
+ service_tier: openaiOptions == null ? void 0 : openaiOptions.serviceTier,
3127
+ include,
3128
+ prompt_cache_key: openaiOptions == null ? void 0 : openaiOptions.promptCacheKey,
3129
+ prompt_cache_retention: openaiOptions == null ? void 0 : openaiOptions.promptCacheRetention,
3130
+ safety_identifier: openaiOptions == null ? void 0 : openaiOptions.safetyIdentifier,
3131
+ top_logprobs: topLogprobs,
3132
+ truncation: openaiOptions == null ? void 0 : openaiOptions.truncation,
3133
+ ...isReasoningModel && ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) && { reasoning: {
3134
+ ...(openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null && { effort: openaiOptions.reasoningEffort },
3135
+ ...(openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && { summary: openaiOptions.reasoningSummary }
3136
+ } }
3137
+ };
3138
+ if (isReasoningModel) {
3139
+ if (!((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) === "none" && modelCapabilities.supportsNonReasoningParameters)) {
3140
+ if (baseArgs.temperature != null) {
3141
+ baseArgs.temperature = void 0;
3142
+ warnings.push({
3143
+ type: "unsupported",
3144
+ feature: "temperature",
3145
+ details: "temperature is not supported for reasoning models"
3146
+ });
3147
+ }
3148
+ if (baseArgs.top_p != null) {
3149
+ baseArgs.top_p = void 0;
3150
+ warnings.push({
3151
+ type: "unsupported",
3152
+ feature: "topP",
3153
+ details: "topP is not supported for reasoning models"
3154
+ });
3155
+ }
3156
+ }
3157
+ } else {
3158
+ if ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null) warnings.push({
3159
+ type: "unsupported",
3160
+ feature: "reasoningEffort",
3161
+ details: "reasoningEffort is not supported for non-reasoning models"
3162
+ });
3163
+ if ((openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) warnings.push({
3164
+ type: "unsupported",
3165
+ feature: "reasoningSummary",
3166
+ details: "reasoningSummary is not supported for non-reasoning models"
3167
+ });
3168
+ }
3169
+ if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "flex" && !modelCapabilities.supportsFlexProcessing) {
3170
+ warnings.push({
3171
+ type: "unsupported",
3172
+ feature: "serviceTier",
3173
+ details: "flex processing is only available for o3, o4-mini, and gpt-5 models"
3174
+ });
3175
+ delete baseArgs.service_tier;
3176
+ }
3177
+ if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "priority" && !modelCapabilities.supportsPriorityProcessing) {
3178
+ warnings.push({
3179
+ type: "unsupported",
3180
+ feature: "serviceTier",
3181
+ details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"
3182
+ });
3183
+ delete baseArgs.service_tier;
3184
+ }
3185
+ const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = await prepareResponsesTools({
3186
+ tools,
3187
+ toolChoice
3188
+ });
3189
+ return {
3190
+ webSearchToolName,
3191
+ args: {
3192
+ ...baseArgs,
3193
+ tools: openaiTools2,
3194
+ tool_choice: openaiToolChoice
3195
+ },
3196
+ warnings: [...warnings, ...toolWarnings],
3197
+ store,
3198
+ toolNameMapping,
3199
+ providerOptionsName
3200
+ };
3201
+ }
3202
+ async doGenerate(options) {
3203
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
3204
+ const { args: body, warnings, webSearchToolName, toolNameMapping, providerOptionsName } = await this.getArgs(options);
3205
+ const url = this.config.url({
3206
+ path: "/responses",
3207
+ modelId: this.modelId
3208
+ });
3209
+ const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt);
3210
+ const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
3211
+ url,
3212
+ headers: combineHeaders(this.config.headers(), options.headers),
3213
+ body,
3214
+ failedResponseHandler: openaiFailedResponseHandler,
3215
+ successfulResponseHandler: createJsonResponseHandler(openaiResponsesResponseSchema),
3216
+ abortSignal: options.abortSignal,
3217
+ fetch: this.config.fetch
3218
+ });
3219
+ if (response.error) throw new APICallError({
3220
+ message: response.error.message,
3221
+ url,
3222
+ requestBodyValues: body,
3223
+ statusCode: 400,
3224
+ responseHeaders,
3225
+ responseBody: rawResponse,
3226
+ isRetryable: false
3227
+ });
3228
+ const content = [];
3229
+ const logprobs = [];
3230
+ let hasFunctionCall = false;
3231
+ for (const part of response.output) switch (part.type) {
3232
+ case "reasoning":
3233
+ if (part.summary.length === 0) part.summary.push({
3234
+ type: "summary_text",
3235
+ text: ""
3236
+ });
3237
+ for (const summary of part.summary) content.push({
3238
+ type: "reasoning",
3239
+ text: summary.text,
3240
+ providerMetadata: { [providerOptionsName]: {
3241
+ itemId: part.id,
3242
+ reasoningEncryptedContent: (_a = part.encrypted_content) != null ? _a : null
3243
+ } }
3244
+ });
3245
+ break;
3246
+ case "image_generation_call":
3247
+ content.push({
3248
+ type: "tool-call",
3249
+ toolCallId: part.id,
3250
+ toolName: toolNameMapping.toCustomToolName("image_generation"),
3251
+ input: "{}",
3252
+ providerExecuted: true
3253
+ });
3254
+ content.push({
3255
+ type: "tool-result",
3256
+ toolCallId: part.id,
3257
+ toolName: toolNameMapping.toCustomToolName("image_generation"),
3258
+ result: { result: part.result }
3259
+ });
3260
+ break;
3261
+ case "local_shell_call":
3262
+ content.push({
3263
+ type: "tool-call",
3264
+ toolCallId: part.call_id,
3265
+ toolName: toolNameMapping.toCustomToolName("local_shell"),
3266
+ input: JSON.stringify({ action: part.action }),
3267
+ providerMetadata: { [providerOptionsName]: { itemId: part.id } }
3268
+ });
3269
+ break;
3270
+ case "shell_call":
3271
+ content.push({
3272
+ type: "tool-call",
3273
+ toolCallId: part.call_id,
3274
+ toolName: toolNameMapping.toCustomToolName("shell"),
3275
+ input: JSON.stringify({ action: { commands: part.action.commands } }),
3276
+ providerMetadata: { [providerOptionsName]: { itemId: part.id } }
3277
+ });
3278
+ break;
3279
+ case "message":
3280
+ for (const contentPart of part.content) {
3281
+ if (((_c = (_b = options.providerOptions) == null ? void 0 : _b[providerOptionsName]) == null ? void 0 : _c.logprobs) && contentPart.logprobs) logprobs.push(contentPart.logprobs);
3282
+ const providerMetadata2 = {
3283
+ itemId: part.id,
3284
+ ...contentPart.annotations.length > 0 && { annotations: contentPart.annotations }
3285
+ };
3286
+ content.push({
3287
+ type: "text",
3288
+ text: contentPart.text,
3289
+ providerMetadata: { [providerOptionsName]: providerMetadata2 }
3290
+ });
3291
+ for (const annotation of contentPart.annotations) if (annotation.type === "url_citation") content.push({
3292
+ type: "source",
3293
+ sourceType: "url",
3294
+ id: (_f = (_e = (_d = this.config).generateId) == null ? void 0 : _e.call(_d)) != null ? _f : generateId(),
3295
+ url: annotation.url,
3296
+ title: annotation.title
3297
+ });
3298
+ else if (annotation.type === "file_citation") content.push({
3299
+ type: "source",
3300
+ sourceType: "document",
3301
+ id: (_i = (_h = (_g = this.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : generateId(),
3302
+ mediaType: "text/plain",
3303
+ title: annotation.filename,
3304
+ filename: annotation.filename,
3305
+ providerMetadata: { [providerOptionsName]: {
3306
+ type: annotation.type,
3307
+ fileId: annotation.file_id,
3308
+ index: annotation.index
3309
+ } }
3310
+ });
3311
+ else if (annotation.type === "container_file_citation") content.push({
3312
+ type: "source",
3313
+ sourceType: "document",
3314
+ id: (_l = (_k = (_j = this.config).generateId) == null ? void 0 : _k.call(_j)) != null ? _l : generateId(),
3315
+ mediaType: "text/plain",
3316
+ title: annotation.filename,
3317
+ filename: annotation.filename,
3318
+ providerMetadata: { [providerOptionsName]: {
3319
+ type: annotation.type,
3320
+ fileId: annotation.file_id,
3321
+ containerId: annotation.container_id
3322
+ } }
3323
+ });
3324
+ else if (annotation.type === "file_path") content.push({
3325
+ type: "source",
3326
+ sourceType: "document",
3327
+ id: (_o = (_n = (_m = this.config).generateId) == null ? void 0 : _n.call(_m)) != null ? _o : generateId(),
3328
+ mediaType: "application/octet-stream",
3329
+ title: annotation.file_id,
3330
+ filename: annotation.file_id,
3331
+ providerMetadata: { [providerOptionsName]: {
3332
+ type: annotation.type,
3333
+ fileId: annotation.file_id,
3334
+ index: annotation.index
3335
+ } }
3336
+ });
3337
+ }
3338
+ break;
3339
+ case "function_call":
3340
+ hasFunctionCall = true;
3341
+ content.push({
3342
+ type: "tool-call",
3343
+ toolCallId: part.call_id,
3344
+ toolName: part.name,
3345
+ input: part.arguments,
3346
+ providerMetadata: { [providerOptionsName]: { itemId: part.id } }
3347
+ });
3348
+ break;
3349
+ case "web_search_call":
3350
+ content.push({
3351
+ type: "tool-call",
3352
+ toolCallId: part.id,
3353
+ toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
3354
+ input: JSON.stringify({}),
3355
+ providerExecuted: true
3356
+ });
3357
+ content.push({
3358
+ type: "tool-result",
3359
+ toolCallId: part.id,
3360
+ toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
3361
+ result: mapWebSearchOutput(part.action)
3362
+ });
3363
+ break;
3364
+ case "mcp_call": {
3365
+ const toolCallId = part.approval_request_id != null ? (_p = approvalRequestIdToDummyToolCallIdFromPrompt[part.approval_request_id]) != null ? _p : part.id : part.id;
3366
+ const toolName = `mcp.${part.name}`;
3367
+ content.push({
3368
+ type: "tool-call",
3369
+ toolCallId,
3370
+ toolName,
3371
+ input: part.arguments,
3372
+ providerExecuted: true,
3373
+ dynamic: true
3374
+ });
3375
+ content.push({
3376
+ type: "tool-result",
3377
+ toolCallId,
3378
+ toolName,
3379
+ result: {
3380
+ type: "call",
3381
+ serverLabel: part.server_label,
3382
+ name: part.name,
3383
+ arguments: part.arguments,
3384
+ ...part.output != null ? { output: part.output } : {},
3385
+ ...part.error != null ? { error: part.error } : {}
3386
+ },
3387
+ providerMetadata: { [providerOptionsName]: { itemId: part.id } }
3388
+ });
3389
+ break;
3390
+ }
3391
+ case "mcp_list_tools": break;
3392
+ case "mcp_approval_request": {
3393
+ const approvalRequestId = (_q = part.approval_request_id) != null ? _q : part.id;
3394
+ const dummyToolCallId = (_t = (_s = (_r = this.config).generateId) == null ? void 0 : _s.call(_r)) != null ? _t : generateId();
3395
+ const toolName = `mcp.${part.name}`;
3396
+ content.push({
3397
+ type: "tool-call",
3398
+ toolCallId: dummyToolCallId,
3399
+ toolName,
3400
+ input: part.arguments,
3401
+ providerExecuted: true,
3402
+ dynamic: true
3403
+ });
3404
+ content.push({
3405
+ type: "tool-approval-request",
3406
+ approvalId: approvalRequestId,
3407
+ toolCallId: dummyToolCallId
3408
+ });
3409
+ break;
3410
+ }
3411
+ case "computer_call":
3412
+ content.push({
3413
+ type: "tool-call",
3414
+ toolCallId: part.id,
3415
+ toolName: toolNameMapping.toCustomToolName("computer_use"),
3416
+ input: "",
3417
+ providerExecuted: true
3418
+ });
3419
+ content.push({
3420
+ type: "tool-result",
3421
+ toolCallId: part.id,
3422
+ toolName: toolNameMapping.toCustomToolName("computer_use"),
3423
+ result: {
3424
+ type: "computer_use_tool_result",
3425
+ status: part.status || "completed"
3426
+ }
3427
+ });
3428
+ break;
3429
+ case "file_search_call":
3430
+ content.push({
3431
+ type: "tool-call",
3432
+ toolCallId: part.id,
3433
+ toolName: toolNameMapping.toCustomToolName("file_search"),
3434
+ input: "{}",
3435
+ providerExecuted: true
3436
+ });
3437
+ content.push({
3438
+ type: "tool-result",
3439
+ toolCallId: part.id,
3440
+ toolName: toolNameMapping.toCustomToolName("file_search"),
3441
+ result: {
3442
+ queries: part.queries,
3443
+ results: (_v = (_u = part.results) == null ? void 0 : _u.map((result) => ({
3444
+ attributes: result.attributes,
3445
+ fileId: result.file_id,
3446
+ filename: result.filename,
3447
+ score: result.score,
3448
+ text: result.text
3449
+ }))) != null ? _v : null
3450
+ }
3451
+ });
3452
+ break;
3453
+ case "code_interpreter_call":
3454
+ content.push({
3455
+ type: "tool-call",
3456
+ toolCallId: part.id,
3457
+ toolName: toolNameMapping.toCustomToolName("code_interpreter"),
3458
+ input: JSON.stringify({
3459
+ code: part.code,
3460
+ containerId: part.container_id
3461
+ }),
3462
+ providerExecuted: true
3463
+ });
3464
+ content.push({
3465
+ type: "tool-result",
3466
+ toolCallId: part.id,
3467
+ toolName: toolNameMapping.toCustomToolName("code_interpreter"),
3468
+ result: { outputs: part.outputs }
3469
+ });
3470
+ break;
3471
+ case "apply_patch_call":
3472
+ content.push({
3473
+ type: "tool-call",
3474
+ toolCallId: part.call_id,
3475
+ toolName: toolNameMapping.toCustomToolName("apply_patch"),
3476
+ input: JSON.stringify({
3477
+ callId: part.call_id,
3478
+ operation: part.operation
3479
+ }),
3480
+ providerMetadata: { [providerOptionsName]: { itemId: part.id } }
3481
+ });
3482
+ break;
3483
+ }
3484
+ const providerMetadata = { [providerOptionsName]: {
3485
+ responseId: response.id,
3486
+ ...logprobs.length > 0 ? { logprobs } : {},
3487
+ ...typeof response.service_tier === "string" ? { serviceTier: response.service_tier } : {}
3488
+ } };
3489
+ const usage = response.usage;
3490
+ return {
3491
+ content,
3492
+ finishReason: {
3493
+ unified: mapOpenAIResponseFinishReason({
3494
+ finishReason: (_w = response.incomplete_details) == null ? void 0 : _w.reason,
3495
+ hasFunctionCall
3496
+ }),
3497
+ raw: (_y = (_x = response.incomplete_details) == null ? void 0 : _x.reason) != null ? _y : void 0
3498
+ },
3499
+ usage: convertOpenAIResponsesUsage(usage),
3500
+ request: { body },
3501
+ response: {
3502
+ id: response.id,
3503
+ timestamp: /* @__PURE__ */ new Date(response.created_at * 1e3),
3504
+ modelId: response.model,
3505
+ headers: responseHeaders,
3506
+ body: rawResponse
3507
+ },
3508
+ providerMetadata,
3509
+ warnings
3510
+ };
3511
+ }
3512
+ async doStream(options) {
3513
+ const { args: body, warnings, webSearchToolName, toolNameMapping, store, providerOptionsName } = await this.getArgs(options);
3514
+ const { responseHeaders, value: response } = await postJsonToApi({
3515
+ url: this.config.url({
3516
+ path: "/responses",
3517
+ modelId: this.modelId
3518
+ }),
3519
+ headers: combineHeaders(this.config.headers(), options.headers),
3520
+ body: {
3521
+ ...body,
3522
+ stream: true
3523
+ },
3524
+ failedResponseHandler: openaiFailedResponseHandler,
3525
+ successfulResponseHandler: createEventSourceResponseHandler(openaiResponsesChunkSchema),
3526
+ abortSignal: options.abortSignal,
3527
+ fetch: this.config.fetch
3528
+ });
3529
+ const self = this;
3530
+ const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt);
3531
+ const approvalRequestIdToDummyToolCallIdFromStream = /* @__PURE__ */ new Map();
3532
+ let finishReason = {
3533
+ unified: "other",
3534
+ raw: void 0
3535
+ };
3536
+ let usage = void 0;
3537
+ const logprobs = [];
3538
+ let responseId = null;
3539
+ const ongoingToolCalls = {};
3540
+ const ongoingAnnotations = [];
3541
+ let hasFunctionCall = false;
3542
+ const activeReasoning = {};
3543
+ let serviceTier;
3544
+ return {
3545
+ stream: response.pipeThrough(new TransformStream({
3546
+ start(controller) {
3547
+ controller.enqueue({
3548
+ type: "stream-start",
3549
+ warnings
3550
+ });
3551
+ },
3552
+ transform(chunk, controller) {
3553
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D;
3554
+ if (options.includeRawChunks) controller.enqueue({
3555
+ type: "raw",
3556
+ rawValue: chunk.rawValue
3557
+ });
3558
+ if (!chunk.success) {
3559
+ finishReason = {
3560
+ unified: "error",
3561
+ raw: void 0
3562
+ };
3563
+ controller.enqueue({
3564
+ type: "error",
3565
+ error: chunk.error
3566
+ });
3567
+ return;
3568
+ }
3569
+ const value = chunk.value;
3570
+ if (isResponseOutputItemAddedChunk(value)) {
3571
+ if (value.item.type === "function_call") {
3572
+ ongoingToolCalls[value.output_index] = {
3573
+ toolName: value.item.name,
3574
+ toolCallId: value.item.call_id
3575
+ };
3576
+ controller.enqueue({
3577
+ type: "tool-input-start",
3578
+ id: value.item.call_id,
3579
+ toolName: value.item.name
3580
+ });
3581
+ } else if (value.item.type === "web_search_call") {
3582
+ ongoingToolCalls[value.output_index] = {
3583
+ toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
3584
+ toolCallId: value.item.id
3585
+ };
3586
+ controller.enqueue({
3587
+ type: "tool-input-start",
3588
+ id: value.item.id,
3589
+ toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
3590
+ providerExecuted: true
3591
+ });
3592
+ controller.enqueue({
3593
+ type: "tool-input-end",
3594
+ id: value.item.id
3595
+ });
3596
+ controller.enqueue({
3597
+ type: "tool-call",
3598
+ toolCallId: value.item.id,
3599
+ toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
3600
+ input: JSON.stringify({}),
3601
+ providerExecuted: true
3602
+ });
3603
+ } else if (value.item.type === "computer_call") {
3604
+ ongoingToolCalls[value.output_index] = {
3605
+ toolName: toolNameMapping.toCustomToolName("computer_use"),
3606
+ toolCallId: value.item.id
3607
+ };
3608
+ controller.enqueue({
3609
+ type: "tool-input-start",
3610
+ id: value.item.id,
3611
+ toolName: toolNameMapping.toCustomToolName("computer_use"),
3612
+ providerExecuted: true
3613
+ });
3614
+ } else if (value.item.type === "code_interpreter_call") {
3615
+ ongoingToolCalls[value.output_index] = {
3616
+ toolName: toolNameMapping.toCustomToolName("code_interpreter"),
3617
+ toolCallId: value.item.id,
3618
+ codeInterpreter: { containerId: value.item.container_id }
3619
+ };
3620
+ controller.enqueue({
3621
+ type: "tool-input-start",
3622
+ id: value.item.id,
3623
+ toolName: toolNameMapping.toCustomToolName("code_interpreter"),
3624
+ providerExecuted: true
3625
+ });
3626
+ controller.enqueue({
3627
+ type: "tool-input-delta",
3628
+ id: value.item.id,
3629
+ delta: `{"containerId":"${value.item.container_id}","code":"`
3630
+ });
3631
+ } else if (value.item.type === "file_search_call") controller.enqueue({
3632
+ type: "tool-call",
3633
+ toolCallId: value.item.id,
3634
+ toolName: toolNameMapping.toCustomToolName("file_search"),
3635
+ input: "{}",
3636
+ providerExecuted: true
3637
+ });
3638
+ else if (value.item.type === "image_generation_call") controller.enqueue({
3639
+ type: "tool-call",
3640
+ toolCallId: value.item.id,
3641
+ toolName: toolNameMapping.toCustomToolName("image_generation"),
3642
+ input: "{}",
3643
+ providerExecuted: true
3644
+ });
3645
+ else if (value.item.type === "mcp_call" || value.item.type === "mcp_list_tools" || value.item.type === "mcp_approval_request") {} else if (value.item.type === "apply_patch_call") {
3646
+ const { call_id: callId, operation } = value.item;
3647
+ ongoingToolCalls[value.output_index] = {
3648
+ toolName: toolNameMapping.toCustomToolName("apply_patch"),
3649
+ toolCallId: callId,
3650
+ applyPatch: {
3651
+ hasDiff: operation.type === "delete_file",
3652
+ endEmitted: operation.type === "delete_file"
3653
+ }
3654
+ };
3655
+ controller.enqueue({
3656
+ type: "tool-input-start",
3657
+ id: callId,
3658
+ toolName: toolNameMapping.toCustomToolName("apply_patch")
3659
+ });
3660
+ if (operation.type === "delete_file") {
3661
+ const inputString = JSON.stringify({
3662
+ callId,
3663
+ operation
3664
+ });
3665
+ controller.enqueue({
3666
+ type: "tool-input-delta",
3667
+ id: callId,
3668
+ delta: inputString
3669
+ });
3670
+ controller.enqueue({
3671
+ type: "tool-input-end",
3672
+ id: callId
3673
+ });
3674
+ } else controller.enqueue({
3675
+ type: "tool-input-delta",
3676
+ id: callId,
3677
+ delta: `{"callId":"${escapeJSONDelta(callId)}","operation":{"type":"${escapeJSONDelta(operation.type)}","path":"${escapeJSONDelta(operation.path)}","diff":"`
3678
+ });
3679
+ } else if (value.item.type === "shell_call") ongoingToolCalls[value.output_index] = {
3680
+ toolName: toolNameMapping.toCustomToolName("shell"),
3681
+ toolCallId: value.item.call_id
3682
+ };
3683
+ else if (value.item.type === "message") {
3684
+ ongoingAnnotations.splice(0, ongoingAnnotations.length);
3685
+ controller.enqueue({
3686
+ type: "text-start",
3687
+ id: value.item.id,
3688
+ providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
3689
+ });
3690
+ } else if (isResponseOutputItemAddedChunk(value) && value.item.type === "reasoning") {
3691
+ activeReasoning[value.item.id] = {
3692
+ encryptedContent: value.item.encrypted_content,
3693
+ summaryParts: { 0: "active" }
3694
+ };
3695
+ controller.enqueue({
3696
+ type: "reasoning-start",
3697
+ id: `${value.item.id}:0`,
3698
+ providerMetadata: { [providerOptionsName]: {
3699
+ itemId: value.item.id,
3700
+ reasoningEncryptedContent: (_a = value.item.encrypted_content) != null ? _a : null
3701
+ } }
3702
+ });
3703
+ }
3704
+ } else if (isResponseOutputItemDoneChunk(value)) {
3705
+ if (value.item.type === "message") controller.enqueue({
3706
+ type: "text-end",
3707
+ id: value.item.id,
3708
+ providerMetadata: { [providerOptionsName]: {
3709
+ itemId: value.item.id,
3710
+ ...ongoingAnnotations.length > 0 && { annotations: ongoingAnnotations }
3711
+ } }
3712
+ });
3713
+ else if (value.item.type === "function_call") {
3714
+ ongoingToolCalls[value.output_index] = void 0;
3715
+ hasFunctionCall = true;
3716
+ controller.enqueue({
3717
+ type: "tool-input-end",
3718
+ id: value.item.call_id
3719
+ });
3720
+ controller.enqueue({
3721
+ type: "tool-call",
3722
+ toolCallId: value.item.call_id,
3723
+ toolName: value.item.name,
3724
+ input: value.item.arguments,
3725
+ providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
3726
+ });
3727
+ } else if (value.item.type === "web_search_call") {
3728
+ ongoingToolCalls[value.output_index] = void 0;
3729
+ controller.enqueue({
3730
+ type: "tool-result",
3731
+ toolCallId: value.item.id,
3732
+ toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
3733
+ result: mapWebSearchOutput(value.item.action)
3734
+ });
3735
+ } else if (value.item.type === "computer_call") {
3736
+ ongoingToolCalls[value.output_index] = void 0;
3737
+ controller.enqueue({
3738
+ type: "tool-input-end",
3739
+ id: value.item.id
3740
+ });
3741
+ controller.enqueue({
3742
+ type: "tool-call",
3743
+ toolCallId: value.item.id,
3744
+ toolName: toolNameMapping.toCustomToolName("computer_use"),
3745
+ input: "",
3746
+ providerExecuted: true
3747
+ });
3748
+ controller.enqueue({
3749
+ type: "tool-result",
3750
+ toolCallId: value.item.id,
3751
+ toolName: toolNameMapping.toCustomToolName("computer_use"),
3752
+ result: {
3753
+ type: "computer_use_tool_result",
3754
+ status: value.item.status || "completed"
3755
+ }
3756
+ });
3757
+ } else if (value.item.type === "file_search_call") {
3758
+ ongoingToolCalls[value.output_index] = void 0;
3759
+ controller.enqueue({
3760
+ type: "tool-result",
3761
+ toolCallId: value.item.id,
3762
+ toolName: toolNameMapping.toCustomToolName("file_search"),
3763
+ result: {
3764
+ queries: value.item.queries,
3765
+ results: (_c = (_b = value.item.results) == null ? void 0 : _b.map((result) => ({
3766
+ attributes: result.attributes,
3767
+ fileId: result.file_id,
3768
+ filename: result.filename,
3769
+ score: result.score,
3770
+ text: result.text
3771
+ }))) != null ? _c : null
3772
+ }
3773
+ });
3774
+ } else if (value.item.type === "code_interpreter_call") {
3775
+ ongoingToolCalls[value.output_index] = void 0;
3776
+ controller.enqueue({
3777
+ type: "tool-result",
3778
+ toolCallId: value.item.id,
3779
+ toolName: toolNameMapping.toCustomToolName("code_interpreter"),
3780
+ result: { outputs: value.item.outputs }
3781
+ });
3782
+ } else if (value.item.type === "image_generation_call") controller.enqueue({
3783
+ type: "tool-result",
3784
+ toolCallId: value.item.id,
3785
+ toolName: toolNameMapping.toCustomToolName("image_generation"),
3786
+ result: { result: value.item.result }
3787
+ });
3788
+ else if (value.item.type === "mcp_call") {
3789
+ ongoingToolCalls[value.output_index] = void 0;
3790
+ const approvalRequestId = (_d = value.item.approval_request_id) != null ? _d : void 0;
3791
+ const aliasedToolCallId = approvalRequestId != null ? (_f = (_e = approvalRequestIdToDummyToolCallIdFromStream.get(approvalRequestId)) != null ? _e : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _f : value.item.id : value.item.id;
3792
+ const toolName = `mcp.${value.item.name}`;
3793
+ controller.enqueue({
3794
+ type: "tool-call",
3795
+ toolCallId: aliasedToolCallId,
3796
+ toolName,
3797
+ input: value.item.arguments,
3798
+ providerExecuted: true,
3799
+ dynamic: true
3800
+ });
3801
+ controller.enqueue({
3802
+ type: "tool-result",
3803
+ toolCallId: aliasedToolCallId,
3804
+ toolName,
3805
+ result: {
3806
+ type: "call",
3807
+ serverLabel: value.item.server_label,
3808
+ name: value.item.name,
3809
+ arguments: value.item.arguments,
3810
+ ...value.item.output != null ? { output: value.item.output } : {},
3811
+ ...value.item.error != null ? { error: value.item.error } : {}
3812
+ },
3813
+ providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
3814
+ });
3815
+ } else if (value.item.type === "mcp_list_tools") ongoingToolCalls[value.output_index] = void 0;
3816
+ else if (value.item.type === "apply_patch_call") {
3817
+ const toolCall = ongoingToolCalls[value.output_index];
3818
+ if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted && value.item.operation.type !== "delete_file") {
3819
+ if (!toolCall.applyPatch.hasDiff) controller.enqueue({
3820
+ type: "tool-input-delta",
3821
+ id: toolCall.toolCallId,
3822
+ delta: escapeJSONDelta(value.item.operation.diff)
3823
+ });
3824
+ controller.enqueue({
3825
+ type: "tool-input-delta",
3826
+ id: toolCall.toolCallId,
3827
+ delta: "\"}}"
3828
+ });
3829
+ controller.enqueue({
3830
+ type: "tool-input-end",
3831
+ id: toolCall.toolCallId
3832
+ });
3833
+ toolCall.applyPatch.endEmitted = true;
3834
+ }
3835
+ if (toolCall && value.item.status === "completed") controller.enqueue({
3836
+ type: "tool-call",
3837
+ toolCallId: toolCall.toolCallId,
3838
+ toolName: toolNameMapping.toCustomToolName("apply_patch"),
3839
+ input: JSON.stringify({
3840
+ callId: value.item.call_id,
3841
+ operation: value.item.operation
3842
+ }),
3843
+ providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
3844
+ });
3845
+ ongoingToolCalls[value.output_index] = void 0;
3846
+ } else if (value.item.type === "mcp_approval_request") {
3847
+ ongoingToolCalls[value.output_index] = void 0;
3848
+ const dummyToolCallId = (_i = (_h = (_g = self.config).generateId) == null ? void 0 : _h.call(_g)) != null ? _i : generateId();
3849
+ const approvalRequestId = (_j = value.item.approval_request_id) != null ? _j : value.item.id;
3850
+ approvalRequestIdToDummyToolCallIdFromStream.set(approvalRequestId, dummyToolCallId);
3851
+ const toolName = `mcp.${value.item.name}`;
3852
+ controller.enqueue({
3853
+ type: "tool-call",
3854
+ toolCallId: dummyToolCallId,
3855
+ toolName,
3856
+ input: value.item.arguments,
3857
+ providerExecuted: true,
3858
+ dynamic: true
3859
+ });
3860
+ controller.enqueue({
3861
+ type: "tool-approval-request",
3862
+ approvalId: approvalRequestId,
3863
+ toolCallId: dummyToolCallId
3864
+ });
3865
+ } else if (value.item.type === "local_shell_call") {
3866
+ ongoingToolCalls[value.output_index] = void 0;
3867
+ controller.enqueue({
3868
+ type: "tool-call",
3869
+ toolCallId: value.item.call_id,
3870
+ toolName: toolNameMapping.toCustomToolName("local_shell"),
3871
+ input: JSON.stringify({ action: {
3872
+ type: "exec",
3873
+ command: value.item.action.command,
3874
+ timeoutMs: value.item.action.timeout_ms,
3875
+ user: value.item.action.user,
3876
+ workingDirectory: value.item.action.working_directory,
3877
+ env: value.item.action.env
3878
+ } }),
3879
+ providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
3880
+ });
3881
+ } else if (value.item.type === "shell_call") {
3882
+ ongoingToolCalls[value.output_index] = void 0;
3883
+ controller.enqueue({
3884
+ type: "tool-call",
3885
+ toolCallId: value.item.call_id,
3886
+ toolName: toolNameMapping.toCustomToolName("shell"),
3887
+ input: JSON.stringify({ action: { commands: value.item.action.commands } }),
3888
+ providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
3889
+ });
3890
+ } else if (value.item.type === "reasoning") {
3891
+ const activeReasoningPart = activeReasoning[value.item.id];
3892
+ const summaryPartIndices = Object.entries(activeReasoningPart.summaryParts).filter(([_, status]) => status === "active" || status === "can-conclude").map(([summaryIndex]) => summaryIndex);
3893
+ for (const summaryIndex of summaryPartIndices) controller.enqueue({
3894
+ type: "reasoning-end",
3895
+ id: `${value.item.id}:${summaryIndex}`,
3896
+ providerMetadata: { [providerOptionsName]: {
3897
+ itemId: value.item.id,
3898
+ reasoningEncryptedContent: (_k = value.item.encrypted_content) != null ? _k : null
3899
+ } }
3900
+ });
3901
+ delete activeReasoning[value.item.id];
3902
+ }
3903
+ } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) {
3904
+ const toolCall = ongoingToolCalls[value.output_index];
3905
+ if (toolCall != null) controller.enqueue({
3906
+ type: "tool-input-delta",
3907
+ id: toolCall.toolCallId,
3908
+ delta: value.delta
3909
+ });
3910
+ } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) {
3911
+ const toolCall = ongoingToolCalls[value.output_index];
3912
+ if (toolCall == null ? void 0 : toolCall.applyPatch) {
3913
+ controller.enqueue({
3914
+ type: "tool-input-delta",
3915
+ id: toolCall.toolCallId,
3916
+ delta: escapeJSONDelta(value.delta)
3917
+ });
3918
+ toolCall.applyPatch.hasDiff = true;
3919
+ }
3920
+ } else if (isResponseApplyPatchCallOperationDiffDoneChunk(value)) {
3921
+ const toolCall = ongoingToolCalls[value.output_index];
3922
+ if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted) {
3923
+ if (!toolCall.applyPatch.hasDiff) {
3924
+ controller.enqueue({
3925
+ type: "tool-input-delta",
3926
+ id: toolCall.toolCallId,
3927
+ delta: escapeJSONDelta(value.diff)
3928
+ });
3929
+ toolCall.applyPatch.hasDiff = true;
3930
+ }
3931
+ controller.enqueue({
3932
+ type: "tool-input-delta",
3933
+ id: toolCall.toolCallId,
3934
+ delta: "\"}}"
3935
+ });
3936
+ controller.enqueue({
3937
+ type: "tool-input-end",
3938
+ id: toolCall.toolCallId
3939
+ });
3940
+ toolCall.applyPatch.endEmitted = true;
3941
+ }
3942
+ } else if (isResponseImageGenerationCallPartialImageChunk(value)) controller.enqueue({
3943
+ type: "tool-result",
3944
+ toolCallId: value.item_id,
3945
+ toolName: toolNameMapping.toCustomToolName("image_generation"),
3946
+ result: { result: value.partial_image_b64 },
3947
+ preliminary: true
3948
+ });
3949
+ else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) {
3950
+ const toolCall = ongoingToolCalls[value.output_index];
3951
+ if (toolCall != null) controller.enqueue({
3952
+ type: "tool-input-delta",
3953
+ id: toolCall.toolCallId,
3954
+ delta: escapeJSONDelta(value.delta)
3955
+ });
3956
+ } else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) {
3957
+ const toolCall = ongoingToolCalls[value.output_index];
3958
+ if (toolCall != null) {
3959
+ controller.enqueue({
3960
+ type: "tool-input-delta",
3961
+ id: toolCall.toolCallId,
3962
+ delta: "\"}"
3963
+ });
3964
+ controller.enqueue({
3965
+ type: "tool-input-end",
3966
+ id: toolCall.toolCallId
3967
+ });
3968
+ controller.enqueue({
3969
+ type: "tool-call",
3970
+ toolCallId: toolCall.toolCallId,
3971
+ toolName: toolNameMapping.toCustomToolName("code_interpreter"),
3972
+ input: JSON.stringify({
3973
+ code: value.code,
3974
+ containerId: toolCall.codeInterpreter.containerId
3975
+ }),
3976
+ providerExecuted: true
3977
+ });
3978
+ }
3979
+ } else if (isResponseCreatedChunk(value)) {
3980
+ responseId = value.response.id;
3981
+ controller.enqueue({
3982
+ type: "response-metadata",
3983
+ id: value.response.id,
3984
+ timestamp: /* @__PURE__ */ new Date(value.response.created_at * 1e3),
3985
+ modelId: value.response.model
3986
+ });
3987
+ } else if (isTextDeltaChunk(value)) {
3988
+ controller.enqueue({
3989
+ type: "text-delta",
3990
+ id: value.item_id,
3991
+ delta: value.delta
3992
+ });
3993
+ if (((_m = (_l = options.providerOptions) == null ? void 0 : _l[providerOptionsName]) == null ? void 0 : _m.logprobs) && value.logprobs) logprobs.push(value.logprobs);
3994
+ } else if (value.type === "response.reasoning_summary_part.added") {
3995
+ if (value.summary_index > 0) {
3996
+ const activeReasoningPart = activeReasoning[value.item_id];
3997
+ activeReasoningPart.summaryParts[value.summary_index] = "active";
3998
+ for (const summaryIndex of Object.keys(activeReasoningPart.summaryParts)) if (activeReasoningPart.summaryParts[summaryIndex] === "can-conclude") {
3999
+ controller.enqueue({
4000
+ type: "reasoning-end",
4001
+ id: `${value.item_id}:${summaryIndex}`,
4002
+ providerMetadata: { [providerOptionsName]: { itemId: value.item_id } }
4003
+ });
4004
+ activeReasoningPart.summaryParts[summaryIndex] = "concluded";
4005
+ }
4006
+ controller.enqueue({
4007
+ type: "reasoning-start",
4008
+ id: `${value.item_id}:${value.summary_index}`,
4009
+ providerMetadata: { [providerOptionsName]: {
4010
+ itemId: value.item_id,
4011
+ reasoningEncryptedContent: (_o = (_n = activeReasoning[value.item_id]) == null ? void 0 : _n.encryptedContent) != null ? _o : null
4012
+ } }
4013
+ });
4014
+ }
4015
+ } else if (value.type === "response.reasoning_summary_text.delta") controller.enqueue({
4016
+ type: "reasoning-delta",
4017
+ id: `${value.item_id}:${value.summary_index}`,
4018
+ delta: value.delta,
4019
+ providerMetadata: { [providerOptionsName]: { itemId: value.item_id } }
4020
+ });
4021
+ else if (value.type === "response.reasoning_summary_part.done") if (store) {
4022
+ controller.enqueue({
4023
+ type: "reasoning-end",
4024
+ id: `${value.item_id}:${value.summary_index}`,
4025
+ providerMetadata: { [providerOptionsName]: { itemId: value.item_id } }
4026
+ });
4027
+ activeReasoning[value.item_id].summaryParts[value.summary_index] = "concluded";
4028
+ } else activeReasoning[value.item_id].summaryParts[value.summary_index] = "can-conclude";
4029
+ else if (isResponseFinishedChunk(value)) {
4030
+ finishReason = {
4031
+ unified: mapOpenAIResponseFinishReason({
4032
+ finishReason: (_p = value.response.incomplete_details) == null ? void 0 : _p.reason,
4033
+ hasFunctionCall
4034
+ }),
4035
+ raw: (_r = (_q = value.response.incomplete_details) == null ? void 0 : _q.reason) != null ? _r : void 0
4036
+ };
4037
+ usage = value.response.usage;
4038
+ if (typeof value.response.service_tier === "string") serviceTier = value.response.service_tier;
4039
+ } else if (isResponseAnnotationAddedChunk(value)) {
4040
+ ongoingAnnotations.push(value.annotation);
4041
+ if (value.annotation.type === "url_citation") controller.enqueue({
4042
+ type: "source",
4043
+ sourceType: "url",
4044
+ id: (_u = (_t = (_s = self.config).generateId) == null ? void 0 : _t.call(_s)) != null ? _u : generateId(),
4045
+ url: value.annotation.url,
4046
+ title: value.annotation.title
4047
+ });
4048
+ else if (value.annotation.type === "file_citation") controller.enqueue({
4049
+ type: "source",
4050
+ sourceType: "document",
4051
+ id: (_x = (_w = (_v = self.config).generateId) == null ? void 0 : _w.call(_v)) != null ? _x : generateId(),
4052
+ mediaType: "text/plain",
4053
+ title: value.annotation.filename,
4054
+ filename: value.annotation.filename,
4055
+ providerMetadata: { [providerOptionsName]: {
4056
+ type: value.annotation.type,
4057
+ fileId: value.annotation.file_id,
4058
+ index: value.annotation.index
4059
+ } }
4060
+ });
4061
+ else if (value.annotation.type === "container_file_citation") controller.enqueue({
4062
+ type: "source",
4063
+ sourceType: "document",
4064
+ id: (_A = (_z = (_y = self.config).generateId) == null ? void 0 : _z.call(_y)) != null ? _A : generateId(),
4065
+ mediaType: "text/plain",
4066
+ title: value.annotation.filename,
4067
+ filename: value.annotation.filename,
4068
+ providerMetadata: { [providerOptionsName]: {
4069
+ type: value.annotation.type,
4070
+ fileId: value.annotation.file_id,
4071
+ containerId: value.annotation.container_id
4072
+ } }
4073
+ });
4074
+ else if (value.annotation.type === "file_path") controller.enqueue({
4075
+ type: "source",
4076
+ sourceType: "document",
4077
+ id: (_D = (_C = (_B = self.config).generateId) == null ? void 0 : _C.call(_B)) != null ? _D : generateId(),
4078
+ mediaType: "application/octet-stream",
4079
+ title: value.annotation.file_id,
4080
+ filename: value.annotation.file_id,
4081
+ providerMetadata: { [providerOptionsName]: {
4082
+ type: value.annotation.type,
4083
+ fileId: value.annotation.file_id,
4084
+ index: value.annotation.index
4085
+ } }
4086
+ });
4087
+ } else if (isErrorChunk(value)) controller.enqueue({
4088
+ type: "error",
4089
+ error: value
4090
+ });
4091
+ },
4092
+ flush(controller) {
4093
+ const providerMetadata = { [providerOptionsName]: {
4094
+ responseId,
4095
+ ...logprobs.length > 0 ? { logprobs } : {},
4096
+ ...serviceTier !== void 0 ? { serviceTier } : {}
4097
+ } };
4098
+ controller.enqueue({
4099
+ type: "finish",
4100
+ finishReason,
4101
+ usage: convertOpenAIResponsesUsage(usage),
4102
+ providerMetadata
4103
+ });
4104
+ }
4105
+ })),
4106
+ request: { body },
4107
+ response: { headers: responseHeaders }
4108
+ };
4109
+ }
4110
+ };
4111
+ function isTextDeltaChunk(chunk) {
4112
+ return chunk.type === "response.output_text.delta";
4113
+ }
4114
+ function isResponseOutputItemDoneChunk(chunk) {
4115
+ return chunk.type === "response.output_item.done";
4116
+ }
4117
+ function isResponseFinishedChunk(chunk) {
4118
+ return chunk.type === "response.completed" || chunk.type === "response.incomplete";
4119
+ }
4120
+ function isResponseCreatedChunk(chunk) {
4121
+ return chunk.type === "response.created";
4122
+ }
4123
+ function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
4124
+ return chunk.type === "response.function_call_arguments.delta";
4125
+ }
4126
+ function isResponseImageGenerationCallPartialImageChunk(chunk) {
4127
+ return chunk.type === "response.image_generation_call.partial_image";
4128
+ }
4129
+ function isResponseCodeInterpreterCallCodeDeltaChunk(chunk) {
4130
+ return chunk.type === "response.code_interpreter_call_code.delta";
4131
+ }
4132
+ function isResponseCodeInterpreterCallCodeDoneChunk(chunk) {
4133
+ return chunk.type === "response.code_interpreter_call_code.done";
4134
+ }
4135
+ function isResponseApplyPatchCallOperationDiffDeltaChunk(chunk) {
4136
+ return chunk.type === "response.apply_patch_call_operation_diff.delta";
4137
+ }
4138
+ function isResponseApplyPatchCallOperationDiffDoneChunk(chunk) {
4139
+ return chunk.type === "response.apply_patch_call_operation_diff.done";
4140
+ }
4141
+ function isResponseOutputItemAddedChunk(chunk) {
4142
+ return chunk.type === "response.output_item.added";
4143
+ }
4144
+ function isResponseAnnotationAddedChunk(chunk) {
4145
+ return chunk.type === "response.output_text.annotation.added";
4146
+ }
4147
+ function isErrorChunk(chunk) {
4148
+ return chunk.type === "error";
4149
+ }
4150
+ function mapWebSearchOutput(action) {
4151
+ var _a;
4152
+ switch (action.type) {
4153
+ case "search": return {
4154
+ action: {
4155
+ type: "search",
4156
+ query: (_a = action.query) != null ? _a : void 0
4157
+ },
4158
+ ...action.sources != null && { sources: action.sources }
4159
+ };
4160
+ case "open_page": return { action: {
4161
+ type: "openPage",
4162
+ url: action.url
4163
+ } };
4164
+ case "find_in_page": return { action: {
4165
+ type: "findInPage",
4166
+ url: action.url,
4167
+ pattern: action.pattern
4168
+ } };
4169
+ }
4170
+ }
4171
+ function escapeJSONDelta(delta) {
4172
+ return JSON.stringify(delta).slice(1, -1);
4173
+ }
4174
+ var openaiSpeechProviderOptionsSchema = lazySchema(() => zodSchema(object({
4175
+ instructions: string().nullish(),
4176
+ speed: number$1().min(.25).max(4).default(1).nullish()
4177
+ })));
4178
+ var OpenAISpeechModel = class {
4179
+ constructor(modelId, config) {
4180
+ this.modelId = modelId;
4181
+ this.config = config;
4182
+ this.specificationVersion = "v3";
4183
+ }
4184
+ get provider() {
4185
+ return this.config.provider;
4186
+ }
4187
+ async getArgs({ text, voice = "alloy", outputFormat = "mp3", speed, instructions, language, providerOptions }) {
4188
+ const warnings = [];
4189
+ const openAIOptions = await parseProviderOptions({
4190
+ provider: "openai",
4191
+ providerOptions,
4192
+ schema: openaiSpeechProviderOptionsSchema
4193
+ });
4194
+ const requestBody = {
4195
+ model: this.modelId,
4196
+ input: text,
4197
+ voice,
4198
+ response_format: "mp3",
4199
+ speed,
4200
+ instructions
4201
+ };
4202
+ if (outputFormat) if ([
4203
+ "mp3",
4204
+ "opus",
4205
+ "aac",
4206
+ "flac",
4207
+ "wav",
4208
+ "pcm"
4209
+ ].includes(outputFormat)) requestBody.response_format = outputFormat;
4210
+ else warnings.push({
4211
+ type: "unsupported",
4212
+ feature: "outputFormat",
4213
+ details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`
4214
+ });
4215
+ if (openAIOptions) {
4216
+ const speechModelOptions = {};
4217
+ for (const key in speechModelOptions) {
4218
+ const value = speechModelOptions[key];
4219
+ if (value !== void 0) requestBody[key] = value;
4220
+ }
4221
+ }
4222
+ if (language) warnings.push({
4223
+ type: "unsupported",
4224
+ feature: "language",
4225
+ details: `OpenAI speech models do not support language selection. Language parameter "${language}" was ignored.`
4226
+ });
4227
+ return {
4228
+ requestBody,
4229
+ warnings
4230
+ };
4231
+ }
4232
+ async doGenerate(options) {
4233
+ var _a, _b, _c;
4234
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
4235
+ const { requestBody, warnings } = await this.getArgs(options);
4236
+ const { value: audio, responseHeaders, rawValue: rawResponse } = await postJsonToApi({
4237
+ url: this.config.url({
4238
+ path: "/audio/speech",
4239
+ modelId: this.modelId
4240
+ }),
4241
+ headers: combineHeaders(this.config.headers(), options.headers),
4242
+ body: requestBody,
4243
+ failedResponseHandler: openaiFailedResponseHandler,
4244
+ successfulResponseHandler: createBinaryResponseHandler(),
4245
+ abortSignal: options.abortSignal,
4246
+ fetch: this.config.fetch
4247
+ });
4248
+ return {
4249
+ audio,
4250
+ warnings,
4251
+ request: { body: JSON.stringify(requestBody) },
4252
+ response: {
4253
+ timestamp: currentDate,
4254
+ modelId: this.modelId,
4255
+ headers: responseHeaders,
4256
+ body: rawResponse
4257
+ }
4258
+ };
4259
+ }
4260
+ };
4261
+ var openaiTranscriptionResponseSchema = lazySchema(() => zodSchema(object({
4262
+ text: string(),
4263
+ language: string().nullish(),
4264
+ duration: number$1().nullish(),
4265
+ words: array(object({
4266
+ word: string(),
4267
+ start: number$1(),
4268
+ end: number$1()
4269
+ })).nullish(),
4270
+ segments: array(object({
4271
+ id: number$1(),
4272
+ seek: number$1(),
4273
+ start: number$1(),
4274
+ end: number$1(),
4275
+ text: string(),
4276
+ tokens: array(number$1()),
4277
+ temperature: number$1(),
4278
+ avg_logprob: number$1(),
4279
+ compression_ratio: number$1(),
4280
+ no_speech_prob: number$1()
4281
+ })).nullish()
4282
+ })));
4283
+ var openAITranscriptionProviderOptions = lazySchema(() => zodSchema(object({
4284
+ include: array(string()).optional(),
4285
+ language: string().optional(),
4286
+ prompt: string().optional(),
4287
+ temperature: number$1().min(0).max(1).default(0).optional(),
4288
+ timestampGranularities: array(_enum(["word", "segment"])).default(["segment"]).optional()
4289
+ })));
4290
+ var languageMap = {
4291
+ afrikaans: "af",
4292
+ arabic: "ar",
4293
+ armenian: "hy",
4294
+ azerbaijani: "az",
4295
+ belarusian: "be",
4296
+ bosnian: "bs",
4297
+ bulgarian: "bg",
4298
+ catalan: "ca",
4299
+ chinese: "zh",
4300
+ croatian: "hr",
4301
+ czech: "cs",
4302
+ danish: "da",
4303
+ dutch: "nl",
4304
+ english: "en",
4305
+ estonian: "et",
4306
+ finnish: "fi",
4307
+ french: "fr",
4308
+ galician: "gl",
4309
+ german: "de",
4310
+ greek: "el",
4311
+ hebrew: "he",
4312
+ hindi: "hi",
4313
+ hungarian: "hu",
4314
+ icelandic: "is",
4315
+ indonesian: "id",
4316
+ italian: "it",
4317
+ japanese: "ja",
4318
+ kannada: "kn",
4319
+ kazakh: "kk",
4320
+ korean: "ko",
4321
+ latvian: "lv",
4322
+ lithuanian: "lt",
4323
+ macedonian: "mk",
4324
+ malay: "ms",
4325
+ marathi: "mr",
4326
+ maori: "mi",
4327
+ nepali: "ne",
4328
+ norwegian: "no",
4329
+ persian: "fa",
4330
+ polish: "pl",
4331
+ portuguese: "pt",
4332
+ romanian: "ro",
4333
+ russian: "ru",
4334
+ serbian: "sr",
4335
+ slovak: "sk",
4336
+ slovenian: "sl",
4337
+ spanish: "es",
4338
+ swahili: "sw",
4339
+ swedish: "sv",
4340
+ tagalog: "tl",
4341
+ tamil: "ta",
4342
+ thai: "th",
4343
+ turkish: "tr",
4344
+ ukrainian: "uk",
4345
+ urdu: "ur",
4346
+ vietnamese: "vi",
4347
+ welsh: "cy"
4348
+ };
4349
+ var OpenAITranscriptionModel = class {
4350
+ constructor(modelId, config) {
4351
+ this.modelId = modelId;
4352
+ this.config = config;
4353
+ this.specificationVersion = "v3";
4354
+ }
4355
+ get provider() {
4356
+ return this.config.provider;
4357
+ }
4358
+ async getArgs({ audio, mediaType, providerOptions }) {
4359
+ const warnings = [];
4360
+ const openAIOptions = await parseProviderOptions({
4361
+ provider: "openai",
4362
+ providerOptions,
4363
+ schema: openAITranscriptionProviderOptions
4364
+ });
4365
+ const formData = new FormData();
4366
+ const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
4367
+ formData.append("model", this.modelId);
4368
+ const fileExtension = mediaTypeToExtension(mediaType);
4369
+ formData.append("file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}`);
4370
+ if (openAIOptions) {
4371
+ const transcriptionModelOptions = {
4372
+ include: openAIOptions.include,
4373
+ language: openAIOptions.language,
4374
+ prompt: openAIOptions.prompt,
4375
+ response_format: ["gpt-4o-transcribe", "gpt-4o-mini-transcribe"].includes(this.modelId) ? "json" : "verbose_json",
4376
+ temperature: openAIOptions.temperature,
4377
+ timestamp_granularities: openAIOptions.timestampGranularities
4378
+ };
4379
+ for (const [key, value] of Object.entries(transcriptionModelOptions)) if (value != null) if (Array.isArray(value)) for (const item of value) formData.append(`${key}[]`, String(item));
4380
+ else formData.append(key, String(value));
4381
+ }
4382
+ return {
4383
+ formData,
4384
+ warnings
4385
+ };
4386
+ }
4387
+ async doGenerate(options) {
4388
+ var _a, _b, _c, _d, _e, _f, _g, _h;
4389
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
4390
+ const { formData, warnings } = await this.getArgs(options);
4391
+ const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi({
4392
+ url: this.config.url({
4393
+ path: "/audio/transcriptions",
4394
+ modelId: this.modelId
4395
+ }),
4396
+ headers: combineHeaders(this.config.headers(), options.headers),
4397
+ formData,
4398
+ failedResponseHandler: openaiFailedResponseHandler,
4399
+ successfulResponseHandler: createJsonResponseHandler(openaiTranscriptionResponseSchema),
4400
+ abortSignal: options.abortSignal,
4401
+ fetch: this.config.fetch
4402
+ });
4403
+ const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0;
4404
+ return {
4405
+ text: response.text,
4406
+ segments: (_g = (_f = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({
4407
+ text: segment.text,
4408
+ startSecond: segment.start,
4409
+ endSecond: segment.end
4410
+ }))) != null ? _f : (_e = response.words) == null ? void 0 : _e.map((word) => ({
4411
+ text: word.word,
4412
+ startSecond: word.start,
4413
+ endSecond: word.end
4414
+ }))) != null ? _g : [],
4415
+ language,
4416
+ durationInSeconds: (_h = response.duration) != null ? _h : void 0,
4417
+ warnings,
4418
+ response: {
4419
+ timestamp: currentDate,
4420
+ modelId: this.modelId,
4421
+ headers: responseHeaders,
4422
+ body: rawResponse
4423
+ }
4424
+ };
4425
+ }
4426
+ };
4427
+ var VERSION = "3.0.25";
4428
+ function createOpenAI(options = {}) {
4429
+ var _a, _b;
4430
+ const baseURL = (_a = withoutTrailingSlash(loadOptionalSetting({
4431
+ settingValue: options.baseURL,
4432
+ environmentVariableName: "OPENAI_BASE_URL"
4433
+ }))) != null ? _a : "https://api.openai.com/v1";
4434
+ const providerName = (_b = options.name) != null ? _b : "openai";
4435
+ const getHeaders = () => withUserAgentSuffix({
4436
+ Authorization: `Bearer ${loadApiKey({
4437
+ apiKey: options.apiKey,
4438
+ environmentVariableName: "OPENAI_API_KEY",
4439
+ description: "OpenAI"
4440
+ })}`,
4441
+ "OpenAI-Organization": options.organization,
4442
+ "OpenAI-Project": options.project,
4443
+ ...options.headers
4444
+ }, `ai-sdk/openai/${VERSION}`);
4445
+ const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
4446
+ provider: `${providerName}.chat`,
4447
+ url: ({ path }) => `${baseURL}${path}`,
4448
+ headers: getHeaders,
4449
+ fetch: options.fetch
4450
+ });
4451
+ const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
4452
+ provider: `${providerName}.completion`,
4453
+ url: ({ path }) => `${baseURL}${path}`,
4454
+ headers: getHeaders,
4455
+ fetch: options.fetch
4456
+ });
4457
+ const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
4458
+ provider: `${providerName}.embedding`,
4459
+ url: ({ path }) => `${baseURL}${path}`,
4460
+ headers: getHeaders,
4461
+ fetch: options.fetch
4462
+ });
4463
+ const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
4464
+ provider: `${providerName}.image`,
4465
+ url: ({ path }) => `${baseURL}${path}`,
4466
+ headers: getHeaders,
4467
+ fetch: options.fetch
4468
+ });
4469
+ const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
4470
+ provider: `${providerName}.transcription`,
4471
+ url: ({ path }) => `${baseURL}${path}`,
4472
+ headers: getHeaders,
4473
+ fetch: options.fetch
4474
+ });
4475
+ const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
4476
+ provider: `${providerName}.speech`,
4477
+ url: ({ path }) => `${baseURL}${path}`,
4478
+ headers: getHeaders,
4479
+ fetch: options.fetch
4480
+ });
4481
+ const createLanguageModel = (modelId) => {
4482
+ if (new.target) throw new Error("The OpenAI model function cannot be called with the new keyword.");
4483
+ return createResponsesModel(modelId);
4484
+ };
4485
+ const createResponsesModel = (modelId) => {
4486
+ return new OpenAIResponsesLanguageModel(modelId, {
4487
+ provider: `${providerName}.responses`,
4488
+ url: ({ path }) => `${baseURL}${path}`,
4489
+ headers: getHeaders,
4490
+ fetch: options.fetch,
4491
+ fileIdPrefixes: ["file-"]
4492
+ });
4493
+ };
4494
+ const provider = function(modelId) {
4495
+ return createLanguageModel(modelId);
4496
+ };
4497
+ provider.specificationVersion = "v3";
4498
+ provider.languageModel = createLanguageModel;
4499
+ provider.chat = createChatModel;
4500
+ provider.completion = createCompletionModel;
4501
+ provider.responses = createResponsesModel;
4502
+ provider.embedding = createEmbeddingModel;
4503
+ provider.embeddingModel = createEmbeddingModel;
4504
+ provider.textEmbedding = createEmbeddingModel;
4505
+ provider.textEmbeddingModel = createEmbeddingModel;
4506
+ provider.image = createImageModel;
4507
+ provider.imageModel = createImageModel;
4508
+ provider.transcription = createTranscriptionModel;
4509
+ provider.transcriptionModel = createTranscriptionModel;
4510
+ provider.speech = createSpeechModel;
4511
+ provider.speechModel = createSpeechModel;
4512
+ provider.tools = openaiTools;
4513
+ return provider;
4514
+ }
4515
+ var openai = createOpenAI();
4516
+
4517
+ //#endregion
4518
+ export { openai };
4519
+ //# sourceMappingURL=dist-Dtrz_N2T.mjs.map