solid-translate 0.2.0 → 1.0.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,2805 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ APICallError,
4
+ InvalidPromptError,
5
+ InvalidResponseDataError,
6
+ TooManyEmbeddingValuesForCallError,
7
+ UnsupportedFunctionalityError,
8
+ combineHeaders,
9
+ convertBase64ToUint8Array,
10
+ convertUint8ArrayToBase64,
11
+ createBinaryResponseHandler,
12
+ createEventSourceResponseHandler,
13
+ createJsonErrorResponseHandler,
14
+ createJsonResponseHandler,
15
+ generateId,
16
+ isParsableJson,
17
+ loadApiKey,
18
+ parseProviderOptions,
19
+ postFormDataToApi,
20
+ postJsonToApi,
21
+ withoutTrailingSlash
22
+ } from "./chunk-CIKZ6PF7.js";
23
+ import "./chunk-FYS2JH42.js";
24
+
25
+ // node_modules/@ai-sdk/openai/dist/index.mjs
26
+ import { z as z2 } from "zod";
27
+ import { z } from "zod";
28
+ import { z as z3 } from "zod";
29
+ import { z as z4 } from "zod";
30
+ import { z as z5 } from "zod";
31
+ import { z as z6 } from "zod";
32
+ import { z as z7 } from "zod";
33
+ import { z as z8 } from "zod";
34
+ import { z as z9 } from "zod";
35
+ function convertToOpenAIChatMessages({
36
+ prompt,
37
+ useLegacyFunctionCalling = false,
38
+ systemMessageMode = "system"
39
+ }) {
40
+ const messages = [];
41
+ const warnings = [];
42
+ for (const { role, content } of prompt) {
43
+ switch (role) {
44
+ case "system": {
45
+ switch (systemMessageMode) {
46
+ case "system": {
47
+ messages.push({ role: "system", content });
48
+ break;
49
+ }
50
+ case "developer": {
51
+ messages.push({ role: "developer", content });
52
+ break;
53
+ }
54
+ case "remove": {
55
+ warnings.push({
56
+ type: "other",
57
+ message: "system messages are removed for this model"
58
+ });
59
+ break;
60
+ }
61
+ default: {
62
+ const _exhaustiveCheck = systemMessageMode;
63
+ throw new Error(
64
+ `Unsupported system message mode: ${_exhaustiveCheck}`
65
+ );
66
+ }
67
+ }
68
+ break;
69
+ }
70
+ case "user": {
71
+ if (content.length === 1 && content[0].type === "text") {
72
+ messages.push({ role: "user", content: content[0].text });
73
+ break;
74
+ }
75
+ messages.push({
76
+ role: "user",
77
+ content: content.map((part, index) => {
78
+ var _a, _b, _c, _d;
79
+ switch (part.type) {
80
+ case "text": {
81
+ return { type: "text", text: part.text };
82
+ }
83
+ case "image": {
84
+ return {
85
+ type: "image_url",
86
+ image_url: {
87
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
88
+ // OpenAI specific extension: image detail
89
+ detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
90
+ }
91
+ };
92
+ }
93
+ case "file": {
94
+ if (part.data instanceof URL) {
95
+ throw new UnsupportedFunctionalityError({
96
+ functionality: "'File content parts with URL data' functionality not supported."
97
+ });
98
+ }
99
+ switch (part.mimeType) {
100
+ case "audio/wav": {
101
+ return {
102
+ type: "input_audio",
103
+ input_audio: { data: part.data, format: "wav" }
104
+ };
105
+ }
106
+ case "audio/mp3":
107
+ case "audio/mpeg": {
108
+ return {
109
+ type: "input_audio",
110
+ input_audio: { data: part.data, format: "mp3" }
111
+ };
112
+ }
113
+ case "application/pdf": {
114
+ return {
115
+ type: "file",
116
+ file: {
117
+ filename: (_d = part.filename) != null ? _d : `part-${index}.pdf`,
118
+ file_data: `data:application/pdf;base64,${part.data}`
119
+ }
120
+ };
121
+ }
122
+ default: {
123
+ throw new UnsupportedFunctionalityError({
124
+ functionality: `File content part type ${part.mimeType} in user messages`
125
+ });
126
+ }
127
+ }
128
+ }
129
+ }
130
+ })
131
+ });
132
+ break;
133
+ }
134
+ case "assistant": {
135
+ let text = "";
136
+ const toolCalls = [];
137
+ for (const part of content) {
138
+ switch (part.type) {
139
+ case "text": {
140
+ text += part.text;
141
+ break;
142
+ }
143
+ case "tool-call": {
144
+ toolCalls.push({
145
+ id: part.toolCallId,
146
+ type: "function",
147
+ function: {
148
+ name: part.toolName,
149
+ arguments: JSON.stringify(part.args)
150
+ }
151
+ });
152
+ break;
153
+ }
154
+ }
155
+ }
156
+ if (useLegacyFunctionCalling) {
157
+ if (toolCalls.length > 1) {
158
+ throw new UnsupportedFunctionalityError({
159
+ functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
160
+ });
161
+ }
162
+ messages.push({
163
+ role: "assistant",
164
+ content: text,
165
+ function_call: toolCalls.length > 0 ? toolCalls[0].function : void 0
166
+ });
167
+ } else {
168
+ messages.push({
169
+ role: "assistant",
170
+ content: text,
171
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
172
+ });
173
+ }
174
+ break;
175
+ }
176
+ case "tool": {
177
+ for (const toolResponse of content) {
178
+ if (useLegacyFunctionCalling) {
179
+ messages.push({
180
+ role: "function",
181
+ name: toolResponse.toolName,
182
+ content: JSON.stringify(toolResponse.result)
183
+ });
184
+ } else {
185
+ messages.push({
186
+ role: "tool",
187
+ tool_call_id: toolResponse.toolCallId,
188
+ content: JSON.stringify(toolResponse.result)
189
+ });
190
+ }
191
+ }
192
+ break;
193
+ }
194
+ default: {
195
+ const _exhaustiveCheck = role;
196
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
197
+ }
198
+ }
199
+ }
200
+ return { messages, warnings };
201
+ }
202
+ function mapOpenAIChatLogProbsOutput(logprobs) {
203
+ var _a, _b;
204
+ return (_b = (_a = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a.map(({ token, logprob, top_logprobs }) => ({
205
+ token,
206
+ logprob,
207
+ topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({
208
+ token: token2,
209
+ logprob: logprob2
210
+ })) : []
211
+ }))) != null ? _b : void 0;
212
+ }
213
+ function mapOpenAIFinishReason(finishReason) {
214
+ switch (finishReason) {
215
+ case "stop":
216
+ return "stop";
217
+ case "length":
218
+ return "length";
219
+ case "content_filter":
220
+ return "content-filter";
221
+ case "function_call":
222
+ case "tool_calls":
223
+ return "tool-calls";
224
+ default:
225
+ return "unknown";
226
+ }
227
+ }
228
+ var openaiErrorDataSchema = z.object({
229
+ error: z.object({
230
+ message: z.string(),
231
+ // The additional information below is handled loosely to support
232
+ // OpenAI-compatible providers that have slightly different error
233
+ // responses:
234
+ type: z.string().nullish(),
235
+ param: z.any().nullish(),
236
+ code: z.union([z.string(), z.number()]).nullish()
237
+ })
238
+ });
239
+ var openaiFailedResponseHandler = createJsonErrorResponseHandler({
240
+ errorSchema: openaiErrorDataSchema,
241
+ errorToMessage: (data) => data.error.message
242
+ });
243
+ function getResponseMetadata({
244
+ id,
245
+ model,
246
+ created
247
+ }) {
248
+ return {
249
+ id: id != null ? id : void 0,
250
+ modelId: model != null ? model : void 0,
251
+ timestamp: created != null ? new Date(created * 1e3) : void 0
252
+ };
253
+ }
254
+ function prepareTools({
255
+ mode,
256
+ useLegacyFunctionCalling = false,
257
+ structuredOutputs
258
+ }) {
259
+ var _a;
260
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
261
+ const toolWarnings = [];
262
+ if (tools == null) {
263
+ return { tools: void 0, tool_choice: void 0, toolWarnings };
264
+ }
265
+ const toolChoice = mode.toolChoice;
266
+ if (useLegacyFunctionCalling) {
267
+ const openaiFunctions = [];
268
+ for (const tool of tools) {
269
+ if (tool.type === "provider-defined") {
270
+ toolWarnings.push({ type: "unsupported-tool", tool });
271
+ } else {
272
+ openaiFunctions.push({
273
+ name: tool.name,
274
+ description: tool.description,
275
+ parameters: tool.parameters
276
+ });
277
+ }
278
+ }
279
+ if (toolChoice == null) {
280
+ return {
281
+ functions: openaiFunctions,
282
+ function_call: void 0,
283
+ toolWarnings
284
+ };
285
+ }
286
+ const type2 = toolChoice.type;
287
+ switch (type2) {
288
+ case "auto":
289
+ case "none":
290
+ case void 0:
291
+ return {
292
+ functions: openaiFunctions,
293
+ function_call: void 0,
294
+ toolWarnings
295
+ };
296
+ case "required":
297
+ throw new UnsupportedFunctionalityError({
298
+ functionality: "useLegacyFunctionCalling and toolChoice: required"
299
+ });
300
+ default:
301
+ return {
302
+ functions: openaiFunctions,
303
+ function_call: { name: toolChoice.toolName },
304
+ toolWarnings
305
+ };
306
+ }
307
+ }
308
+ const openaiTools2 = [];
309
+ for (const tool of tools) {
310
+ if (tool.type === "provider-defined") {
311
+ toolWarnings.push({ type: "unsupported-tool", tool });
312
+ } else {
313
+ openaiTools2.push({
314
+ type: "function",
315
+ function: {
316
+ name: tool.name,
317
+ description: tool.description,
318
+ parameters: tool.parameters,
319
+ strict: structuredOutputs ? true : void 0
320
+ }
321
+ });
322
+ }
323
+ }
324
+ if (toolChoice == null) {
325
+ return { tools: openaiTools2, tool_choice: void 0, toolWarnings };
326
+ }
327
+ const type = toolChoice.type;
328
+ switch (type) {
329
+ case "auto":
330
+ case "none":
331
+ case "required":
332
+ return { tools: openaiTools2, tool_choice: type, toolWarnings };
333
+ case "tool":
334
+ return {
335
+ tools: openaiTools2,
336
+ tool_choice: {
337
+ type: "function",
338
+ function: {
339
+ name: toolChoice.toolName
340
+ }
341
+ },
342
+ toolWarnings
343
+ };
344
+ default: {
345
+ const _exhaustiveCheck = type;
346
+ throw new UnsupportedFunctionalityError({
347
+ functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
348
+ });
349
+ }
350
+ }
351
+ }
352
+ var OpenAIChatLanguageModel = class {
353
+ constructor(modelId, settings, config) {
354
+ this.specificationVersion = "v1";
355
+ this.modelId = modelId;
356
+ this.settings = settings;
357
+ this.config = config;
358
+ }
359
+ get supportsStructuredOutputs() {
360
+ var _a;
361
+ return (_a = this.settings.structuredOutputs) != null ? _a : isReasoningModel(this.modelId);
362
+ }
363
+ get defaultObjectGenerationMode() {
364
+ if (isAudioModel(this.modelId)) {
365
+ return "tool";
366
+ }
367
+ return this.supportsStructuredOutputs ? "json" : "tool";
368
+ }
369
+ get provider() {
370
+ return this.config.provider;
371
+ }
372
+ get supportsImageUrls() {
373
+ return !this.settings.downloadImages;
374
+ }
375
+ getArgs({
376
+ mode,
377
+ prompt,
378
+ maxTokens,
379
+ temperature,
380
+ topP,
381
+ topK,
382
+ frequencyPenalty,
383
+ presencePenalty,
384
+ stopSequences,
385
+ responseFormat,
386
+ seed,
387
+ providerMetadata
388
+ }) {
389
+ var _a, _b, _c, _d, _e, _f, _g, _h;
390
+ const type = mode.type;
391
+ const warnings = [];
392
+ if (topK != null) {
393
+ warnings.push({
394
+ type: "unsupported-setting",
395
+ setting: "topK"
396
+ });
397
+ }
398
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) {
399
+ warnings.push({
400
+ type: "unsupported-setting",
401
+ setting: "responseFormat",
402
+ details: "JSON response format schema is only supported with structuredOutputs"
403
+ });
404
+ }
405
+ const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
406
+ if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
407
+ throw new UnsupportedFunctionalityError({
408
+ functionality: "useLegacyFunctionCalling with parallelToolCalls"
409
+ });
410
+ }
411
+ if (useLegacyFunctionCalling && this.supportsStructuredOutputs) {
412
+ throw new UnsupportedFunctionalityError({
413
+ functionality: "structuredOutputs with useLegacyFunctionCalling"
414
+ });
415
+ }
416
+ const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages(
417
+ {
418
+ prompt,
419
+ useLegacyFunctionCalling,
420
+ systemMessageMode: getSystemMessageMode(this.modelId)
421
+ }
422
+ );
423
+ warnings.push(...messageWarnings);
424
+ const baseArgs = {
425
+ // model id:
426
+ model: this.modelId,
427
+ // model specific settings:
428
+ logit_bias: this.settings.logitBias,
429
+ logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
430
+ top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
431
+ user: this.settings.user,
432
+ parallel_tool_calls: this.settings.parallelToolCalls,
433
+ // standardized settings:
434
+ max_tokens: maxTokens,
435
+ temperature,
436
+ top_p: topP,
437
+ frequency_penalty: frequencyPenalty,
438
+ presence_penalty: presencePenalty,
439
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs && responseFormat.schema != null ? {
440
+ type: "json_schema",
441
+ json_schema: {
442
+ schema: responseFormat.schema,
443
+ strict: true,
444
+ name: (_a = responseFormat.name) != null ? _a : "response",
445
+ description: responseFormat.description
446
+ }
447
+ } : { type: "json_object" } : void 0,
448
+ stop: stopSequences,
449
+ seed,
450
+ // openai specific settings:
451
+ // TODO remove in next major version; we auto-map maxTokens now
452
+ max_completion_tokens: (_b = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _b.maxCompletionTokens,
453
+ store: (_c = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _c.store,
454
+ metadata: (_d = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _d.metadata,
455
+ prediction: (_e = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _e.prediction,
456
+ reasoning_effort: (_g = (_f = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _f.reasoningEffort) != null ? _g : this.settings.reasoningEffort,
457
+ // messages:
458
+ messages
459
+ };
460
+ if (isReasoningModel(this.modelId)) {
461
+ if (baseArgs.temperature != null) {
462
+ baseArgs.temperature = void 0;
463
+ warnings.push({
464
+ type: "unsupported-setting",
465
+ setting: "temperature",
466
+ details: "temperature is not supported for reasoning models"
467
+ });
468
+ }
469
+ if (baseArgs.top_p != null) {
470
+ baseArgs.top_p = void 0;
471
+ warnings.push({
472
+ type: "unsupported-setting",
473
+ setting: "topP",
474
+ details: "topP is not supported for reasoning models"
475
+ });
476
+ }
477
+ if (baseArgs.frequency_penalty != null) {
478
+ baseArgs.frequency_penalty = void 0;
479
+ warnings.push({
480
+ type: "unsupported-setting",
481
+ setting: "frequencyPenalty",
482
+ details: "frequencyPenalty is not supported for reasoning models"
483
+ });
484
+ }
485
+ if (baseArgs.presence_penalty != null) {
486
+ baseArgs.presence_penalty = void 0;
487
+ warnings.push({
488
+ type: "unsupported-setting",
489
+ setting: "presencePenalty",
490
+ details: "presencePenalty is not supported for reasoning models"
491
+ });
492
+ }
493
+ if (baseArgs.logit_bias != null) {
494
+ baseArgs.logit_bias = void 0;
495
+ warnings.push({
496
+ type: "other",
497
+ message: "logitBias is not supported for reasoning models"
498
+ });
499
+ }
500
+ if (baseArgs.logprobs != null) {
501
+ baseArgs.logprobs = void 0;
502
+ warnings.push({
503
+ type: "other",
504
+ message: "logprobs is not supported for reasoning models"
505
+ });
506
+ }
507
+ if (baseArgs.top_logprobs != null) {
508
+ baseArgs.top_logprobs = void 0;
509
+ warnings.push({
510
+ type: "other",
511
+ message: "topLogprobs is not supported for reasoning models"
512
+ });
513
+ }
514
+ if (baseArgs.max_tokens != null) {
515
+ if (baseArgs.max_completion_tokens == null) {
516
+ baseArgs.max_completion_tokens = baseArgs.max_tokens;
517
+ }
518
+ baseArgs.max_tokens = void 0;
519
+ }
520
+ } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) {
521
+ if (baseArgs.temperature != null) {
522
+ baseArgs.temperature = void 0;
523
+ warnings.push({
524
+ type: "unsupported-setting",
525
+ setting: "temperature",
526
+ details: "temperature is not supported for the search preview models and has been removed."
527
+ });
528
+ }
529
+ }
530
+ switch (type) {
531
+ case "regular": {
532
+ const { tools, tool_choice, functions, function_call, toolWarnings } = prepareTools({
533
+ mode,
534
+ useLegacyFunctionCalling,
535
+ structuredOutputs: this.supportsStructuredOutputs
536
+ });
537
+ return {
538
+ args: {
539
+ ...baseArgs,
540
+ tools,
541
+ tool_choice,
542
+ functions,
543
+ function_call
544
+ },
545
+ warnings: [...warnings, ...toolWarnings]
546
+ };
547
+ }
548
+ case "object-json": {
549
+ return {
550
+ args: {
551
+ ...baseArgs,
552
+ response_format: this.supportsStructuredOutputs && mode.schema != null ? {
553
+ type: "json_schema",
554
+ json_schema: {
555
+ schema: mode.schema,
556
+ strict: true,
557
+ name: (_h = mode.name) != null ? _h : "response",
558
+ description: mode.description
559
+ }
560
+ } : { type: "json_object" }
561
+ },
562
+ warnings
563
+ };
564
+ }
565
+ case "object-tool": {
566
+ return {
567
+ args: useLegacyFunctionCalling ? {
568
+ ...baseArgs,
569
+ function_call: {
570
+ name: mode.tool.name
571
+ },
572
+ functions: [
573
+ {
574
+ name: mode.tool.name,
575
+ description: mode.tool.description,
576
+ parameters: mode.tool.parameters
577
+ }
578
+ ]
579
+ } : {
580
+ ...baseArgs,
581
+ tool_choice: {
582
+ type: "function",
583
+ function: { name: mode.tool.name }
584
+ },
585
+ tools: [
586
+ {
587
+ type: "function",
588
+ function: {
589
+ name: mode.tool.name,
590
+ description: mode.tool.description,
591
+ parameters: mode.tool.parameters,
592
+ strict: this.supportsStructuredOutputs ? true : void 0
593
+ }
594
+ }
595
+ ]
596
+ },
597
+ warnings
598
+ };
599
+ }
600
+ default: {
601
+ const _exhaustiveCheck = type;
602
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
603
+ }
604
+ }
605
+ }
606
+ async doGenerate(options) {
607
+ var _a, _b, _c, _d, _e, _f, _g, _h;
608
+ const { args: body, warnings } = this.getArgs(options);
609
+ const {
610
+ responseHeaders,
611
+ value: response,
612
+ rawValue: rawResponse
613
+ } = await postJsonToApi({
614
+ url: this.config.url({
615
+ path: "/chat/completions",
616
+ modelId: this.modelId
617
+ }),
618
+ headers: combineHeaders(this.config.headers(), options.headers),
619
+ body,
620
+ failedResponseHandler: openaiFailedResponseHandler,
621
+ successfulResponseHandler: createJsonResponseHandler(
622
+ openaiChatResponseSchema
623
+ ),
624
+ abortSignal: options.abortSignal,
625
+ fetch: this.config.fetch
626
+ });
627
+ const { messages: rawPrompt, ...rawSettings } = body;
628
+ const choice = response.choices[0];
629
+ const completionTokenDetails = (_a = response.usage) == null ? void 0 : _a.completion_tokens_details;
630
+ const promptTokenDetails = (_b = response.usage) == null ? void 0 : _b.prompt_tokens_details;
631
+ const providerMetadata = { openai: {} };
632
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens) != null) {
633
+ providerMetadata.openai.reasoningTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens;
634
+ }
635
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) {
636
+ providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens;
637
+ }
638
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) {
639
+ providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens;
640
+ }
641
+ if ((promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens) != null) {
642
+ providerMetadata.openai.cachedPromptTokens = promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens;
643
+ }
644
+ return {
645
+ text: (_c = choice.message.content) != null ? _c : void 0,
646
+ toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
647
+ {
648
+ toolCallType: "function",
649
+ toolCallId: generateId(),
650
+ toolName: choice.message.function_call.name,
651
+ args: choice.message.function_call.arguments
652
+ }
653
+ ] : (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => {
654
+ var _a2;
655
+ return {
656
+ toolCallType: "function",
657
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
658
+ toolName: toolCall.function.name,
659
+ args: toolCall.function.arguments
660
+ };
661
+ }),
662
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
663
+ usage: {
664
+ promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : NaN,
665
+ completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : NaN
666
+ },
667
+ rawCall: { rawPrompt, rawSettings },
668
+ rawResponse: { headers: responseHeaders, body: rawResponse },
669
+ request: { body: JSON.stringify(body) },
670
+ response: getResponseMetadata(response),
671
+ warnings,
672
+ logprobs: mapOpenAIChatLogProbsOutput(choice.logprobs),
673
+ providerMetadata
674
+ };
675
+ }
676
+ async doStream(options) {
677
+ if (this.settings.simulateStreaming) {
678
+ const result = await this.doGenerate(options);
679
+ const simulatedStream = new ReadableStream({
680
+ start(controller) {
681
+ controller.enqueue({ type: "response-metadata", ...result.response });
682
+ if (result.text) {
683
+ controller.enqueue({
684
+ type: "text-delta",
685
+ textDelta: result.text
686
+ });
687
+ }
688
+ if (result.toolCalls) {
689
+ for (const toolCall of result.toolCalls) {
690
+ controller.enqueue({
691
+ type: "tool-call-delta",
692
+ toolCallType: "function",
693
+ toolCallId: toolCall.toolCallId,
694
+ toolName: toolCall.toolName,
695
+ argsTextDelta: toolCall.args
696
+ });
697
+ controller.enqueue({
698
+ type: "tool-call",
699
+ ...toolCall
700
+ });
701
+ }
702
+ }
703
+ controller.enqueue({
704
+ type: "finish",
705
+ finishReason: result.finishReason,
706
+ usage: result.usage,
707
+ logprobs: result.logprobs,
708
+ providerMetadata: result.providerMetadata
709
+ });
710
+ controller.close();
711
+ }
712
+ });
713
+ return {
714
+ stream: simulatedStream,
715
+ rawCall: result.rawCall,
716
+ rawResponse: result.rawResponse,
717
+ warnings: result.warnings
718
+ };
719
+ }
720
+ const { args, warnings } = this.getArgs(options);
721
+ const body = {
722
+ ...args,
723
+ stream: true,
724
+ // only include stream_options when in strict compatibility mode:
725
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
726
+ };
727
+ const { responseHeaders, value: response } = await postJsonToApi({
728
+ url: this.config.url({
729
+ path: "/chat/completions",
730
+ modelId: this.modelId
731
+ }),
732
+ headers: combineHeaders(this.config.headers(), options.headers),
733
+ body,
734
+ failedResponseHandler: openaiFailedResponseHandler,
735
+ successfulResponseHandler: createEventSourceResponseHandler(
736
+ openaiChatChunkSchema
737
+ ),
738
+ abortSignal: options.abortSignal,
739
+ fetch: this.config.fetch
740
+ });
741
+ const { messages: rawPrompt, ...rawSettings } = args;
742
+ const toolCalls = [];
743
+ let finishReason = "unknown";
744
+ let usage = {
745
+ promptTokens: void 0,
746
+ completionTokens: void 0
747
+ };
748
+ let logprobs;
749
+ let isFirstChunk = true;
750
+ const { useLegacyFunctionCalling } = this.settings;
751
+ const providerMetadata = { openai: {} };
752
+ return {
753
+ stream: response.pipeThrough(
754
+ new TransformStream({
755
+ transform(chunk, controller) {
756
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
757
+ if (!chunk.success) {
758
+ finishReason = "error";
759
+ controller.enqueue({ type: "error", error: chunk.error });
760
+ return;
761
+ }
762
+ const value = chunk.value;
763
+ if ("error" in value) {
764
+ finishReason = "error";
765
+ controller.enqueue({ type: "error", error: value.error });
766
+ return;
767
+ }
768
+ if (isFirstChunk) {
769
+ isFirstChunk = false;
770
+ controller.enqueue({
771
+ type: "response-metadata",
772
+ ...getResponseMetadata(value)
773
+ });
774
+ }
775
+ if (value.usage != null) {
776
+ const {
777
+ prompt_tokens,
778
+ completion_tokens,
779
+ prompt_tokens_details,
780
+ completion_tokens_details
781
+ } = value.usage;
782
+ usage = {
783
+ promptTokens: prompt_tokens != null ? prompt_tokens : void 0,
784
+ completionTokens: completion_tokens != null ? completion_tokens : void 0
785
+ };
786
+ if ((completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens) != null) {
787
+ providerMetadata.openai.reasoningTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens;
788
+ }
789
+ if ((completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens) != null) {
790
+ providerMetadata.openai.acceptedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens;
791
+ }
792
+ if ((completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens) != null) {
793
+ providerMetadata.openai.rejectedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens;
794
+ }
795
+ if ((prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens) != null) {
796
+ providerMetadata.openai.cachedPromptTokens = prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens;
797
+ }
798
+ }
799
+ const choice = value.choices[0];
800
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
801
+ finishReason = mapOpenAIFinishReason(choice.finish_reason);
802
+ }
803
+ if ((choice == null ? void 0 : choice.delta) == null) {
804
+ return;
805
+ }
806
+ const delta = choice.delta;
807
+ if (delta.content != null) {
808
+ controller.enqueue({
809
+ type: "text-delta",
810
+ textDelta: delta.content
811
+ });
812
+ }
813
+ const mappedLogprobs = mapOpenAIChatLogProbsOutput(
814
+ choice == null ? void 0 : choice.logprobs
815
+ );
816
+ if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
817
+ if (logprobs === void 0) logprobs = [];
818
+ logprobs.push(...mappedLogprobs);
819
+ }
820
+ const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
821
+ {
822
+ type: "function",
823
+ id: generateId(),
824
+ function: delta.function_call,
825
+ index: 0
826
+ }
827
+ ] : delta.tool_calls;
828
+ if (mappedToolCalls != null) {
829
+ for (const toolCallDelta of mappedToolCalls) {
830
+ const index = toolCallDelta.index;
831
+ if (toolCalls[index] == null) {
832
+ if (toolCallDelta.type !== "function") {
833
+ throw new InvalidResponseDataError({
834
+ data: toolCallDelta,
835
+ message: `Expected 'function' type.`
836
+ });
837
+ }
838
+ if (toolCallDelta.id == null) {
839
+ throw new InvalidResponseDataError({
840
+ data: toolCallDelta,
841
+ message: `Expected 'id' to be a string.`
842
+ });
843
+ }
844
+ if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
845
+ throw new InvalidResponseDataError({
846
+ data: toolCallDelta,
847
+ message: `Expected 'function.name' to be a string.`
848
+ });
849
+ }
850
+ toolCalls[index] = {
851
+ id: toolCallDelta.id,
852
+ type: "function",
853
+ function: {
854
+ name: toolCallDelta.function.name,
855
+ arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
856
+ },
857
+ hasFinished: false
858
+ };
859
+ const toolCall2 = toolCalls[index];
860
+ if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null) {
861
+ if (toolCall2.function.arguments.length > 0) {
862
+ controller.enqueue({
863
+ type: "tool-call-delta",
864
+ toolCallType: "function",
865
+ toolCallId: toolCall2.id,
866
+ toolName: toolCall2.function.name,
867
+ argsTextDelta: toolCall2.function.arguments
868
+ });
869
+ }
870
+ if (isParsableJson(toolCall2.function.arguments)) {
871
+ controller.enqueue({
872
+ type: "tool-call",
873
+ toolCallType: "function",
874
+ toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
875
+ toolName: toolCall2.function.name,
876
+ args: toolCall2.function.arguments
877
+ });
878
+ toolCall2.hasFinished = true;
879
+ }
880
+ }
881
+ continue;
882
+ }
883
+ const toolCall = toolCalls[index];
884
+ if (toolCall.hasFinished) {
885
+ continue;
886
+ }
887
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
888
+ toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
889
+ }
890
+ controller.enqueue({
891
+ type: "tool-call-delta",
892
+ toolCallType: "function",
893
+ toolCallId: toolCall.id,
894
+ toolName: toolCall.function.name,
895
+ argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
896
+ });
897
+ if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
898
+ controller.enqueue({
899
+ type: "tool-call",
900
+ toolCallType: "function",
901
+ toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
902
+ toolName: toolCall.function.name,
903
+ args: toolCall.function.arguments
904
+ });
905
+ toolCall.hasFinished = true;
906
+ }
907
+ }
908
+ }
909
+ },
910
+ flush(controller) {
911
+ var _a, _b;
912
+ controller.enqueue({
913
+ type: "finish",
914
+ finishReason,
915
+ logprobs,
916
+ usage: {
917
+ promptTokens: (_a = usage.promptTokens) != null ? _a : NaN,
918
+ completionTokens: (_b = usage.completionTokens) != null ? _b : NaN
919
+ },
920
+ ...providerMetadata != null ? { providerMetadata } : {}
921
+ });
922
+ }
923
+ })
924
+ ),
925
+ rawCall: { rawPrompt, rawSettings },
926
+ rawResponse: { headers: responseHeaders },
927
+ request: { body: JSON.stringify(body) },
928
+ warnings
929
+ };
930
+ }
931
+ };
932
+ var openaiTokenUsageSchema = z2.object({
933
+ prompt_tokens: z2.number().nullish(),
934
+ completion_tokens: z2.number().nullish(),
935
+ prompt_tokens_details: z2.object({
936
+ cached_tokens: z2.number().nullish()
937
+ }).nullish(),
938
+ completion_tokens_details: z2.object({
939
+ reasoning_tokens: z2.number().nullish(),
940
+ accepted_prediction_tokens: z2.number().nullish(),
941
+ rejected_prediction_tokens: z2.number().nullish()
942
+ }).nullish()
943
+ }).nullish();
944
+ var openaiChatResponseSchema = z2.object({
945
+ id: z2.string().nullish(),
946
+ created: z2.number().nullish(),
947
+ model: z2.string().nullish(),
948
+ choices: z2.array(
949
+ z2.object({
950
+ message: z2.object({
951
+ role: z2.literal("assistant").nullish(),
952
+ content: z2.string().nullish(),
953
+ function_call: z2.object({
954
+ arguments: z2.string(),
955
+ name: z2.string()
956
+ }).nullish(),
957
+ tool_calls: z2.array(
958
+ z2.object({
959
+ id: z2.string().nullish(),
960
+ type: z2.literal("function"),
961
+ function: z2.object({
962
+ name: z2.string(),
963
+ arguments: z2.string()
964
+ })
965
+ })
966
+ ).nullish()
967
+ }),
968
+ index: z2.number(),
969
+ logprobs: z2.object({
970
+ content: z2.array(
971
+ z2.object({
972
+ token: z2.string(),
973
+ logprob: z2.number(),
974
+ top_logprobs: z2.array(
975
+ z2.object({
976
+ token: z2.string(),
977
+ logprob: z2.number()
978
+ })
979
+ )
980
+ })
981
+ ).nullable()
982
+ }).nullish(),
983
+ finish_reason: z2.string().nullish()
984
+ })
985
+ ),
986
+ usage: openaiTokenUsageSchema
987
+ });
988
+ var openaiChatChunkSchema = z2.union([
989
+ z2.object({
990
+ id: z2.string().nullish(),
991
+ created: z2.number().nullish(),
992
+ model: z2.string().nullish(),
993
+ choices: z2.array(
994
+ z2.object({
995
+ delta: z2.object({
996
+ role: z2.enum(["assistant"]).nullish(),
997
+ content: z2.string().nullish(),
998
+ function_call: z2.object({
999
+ name: z2.string().optional(),
1000
+ arguments: z2.string().optional()
1001
+ }).nullish(),
1002
+ tool_calls: z2.array(
1003
+ z2.object({
1004
+ index: z2.number(),
1005
+ id: z2.string().nullish(),
1006
+ type: z2.literal("function").nullish(),
1007
+ function: z2.object({
1008
+ name: z2.string().nullish(),
1009
+ arguments: z2.string().nullish()
1010
+ })
1011
+ })
1012
+ ).nullish()
1013
+ }).nullish(),
1014
+ logprobs: z2.object({
1015
+ content: z2.array(
1016
+ z2.object({
1017
+ token: z2.string(),
1018
+ logprob: z2.number(),
1019
+ top_logprobs: z2.array(
1020
+ z2.object({
1021
+ token: z2.string(),
1022
+ logprob: z2.number()
1023
+ })
1024
+ )
1025
+ })
1026
+ ).nullable()
1027
+ }).nullish(),
1028
+ finish_reason: z2.string().nullish(),
1029
+ index: z2.number()
1030
+ })
1031
+ ),
1032
+ usage: openaiTokenUsageSchema
1033
+ }),
1034
+ openaiErrorDataSchema
1035
+ ]);
1036
+ function isReasoningModel(modelId) {
1037
+ return modelId.startsWith("o") || modelId.startsWith("gpt-5");
1038
+ }
1039
+ function isAudioModel(modelId) {
1040
+ return modelId.startsWith("gpt-4o-audio-preview");
1041
+ }
1042
+ function getSystemMessageMode(modelId) {
1043
+ var _a, _b;
1044
+ if (!isReasoningModel(modelId)) {
1045
+ return "system";
1046
+ }
1047
+ return (_b = (_a = reasoningModels[modelId]) == null ? void 0 : _a.systemMessageMode) != null ? _b : "developer";
1048
+ }
1049
+ var reasoningModels = {
1050
+ "o1-mini": {
1051
+ systemMessageMode: "remove"
1052
+ },
1053
+ "o1-mini-2024-09-12": {
1054
+ systemMessageMode: "remove"
1055
+ },
1056
+ "o1-preview": {
1057
+ systemMessageMode: "remove"
1058
+ },
1059
+ "o1-preview-2024-09-12": {
1060
+ systemMessageMode: "remove"
1061
+ },
1062
+ o3: {
1063
+ systemMessageMode: "developer"
1064
+ },
1065
+ "o3-2025-04-16": {
1066
+ systemMessageMode: "developer"
1067
+ },
1068
+ "o3-mini": {
1069
+ systemMessageMode: "developer"
1070
+ },
1071
+ "o3-mini-2025-01-31": {
1072
+ systemMessageMode: "developer"
1073
+ },
1074
+ "o4-mini": {
1075
+ systemMessageMode: "developer"
1076
+ },
1077
+ "o4-mini-2025-04-16": {
1078
+ systemMessageMode: "developer"
1079
+ }
1080
+ };
1081
+ function convertToOpenAICompletionPrompt({
1082
+ prompt,
1083
+ inputFormat,
1084
+ user = "user",
1085
+ assistant = "assistant"
1086
+ }) {
1087
+ if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") {
1088
+ return { prompt: prompt[0].content[0].text };
1089
+ }
1090
+ let text = "";
1091
+ if (prompt[0].role === "system") {
1092
+ text += `${prompt[0].content}
1093
+
1094
+ `;
1095
+ prompt = prompt.slice(1);
1096
+ }
1097
+ for (const { role, content } of prompt) {
1098
+ switch (role) {
1099
+ case "system": {
1100
+ throw new InvalidPromptError({
1101
+ message: "Unexpected system message in prompt: ${content}",
1102
+ prompt
1103
+ });
1104
+ }
1105
+ case "user": {
1106
+ const userMessage = content.map((part) => {
1107
+ switch (part.type) {
1108
+ case "text": {
1109
+ return part.text;
1110
+ }
1111
+ case "image": {
1112
+ throw new UnsupportedFunctionalityError({
1113
+ functionality: "images"
1114
+ });
1115
+ }
1116
+ }
1117
+ }).join("");
1118
+ text += `${user}:
1119
+ ${userMessage}
1120
+
1121
+ `;
1122
+ break;
1123
+ }
1124
+ case "assistant": {
1125
+ const assistantMessage = content.map((part) => {
1126
+ switch (part.type) {
1127
+ case "text": {
1128
+ return part.text;
1129
+ }
1130
+ case "tool-call": {
1131
+ throw new UnsupportedFunctionalityError({
1132
+ functionality: "tool-call messages"
1133
+ });
1134
+ }
1135
+ }
1136
+ }).join("");
1137
+ text += `${assistant}:
1138
+ ${assistantMessage}
1139
+
1140
+ `;
1141
+ break;
1142
+ }
1143
+ case "tool": {
1144
+ throw new UnsupportedFunctionalityError({
1145
+ functionality: "tool messages"
1146
+ });
1147
+ }
1148
+ default: {
1149
+ const _exhaustiveCheck = role;
1150
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1151
+ }
1152
+ }
1153
+ }
1154
+ text += `${assistant}:
1155
+ `;
1156
+ return {
1157
+ prompt: text,
1158
+ stopSequences: [`
1159
+ ${user}:`]
1160
+ };
1161
+ }
1162
+ function mapOpenAICompletionLogProbs(logprobs) {
1163
+ return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => ({
1164
+ token,
1165
+ logprob: logprobs.token_logprobs[index],
1166
+ topLogprobs: logprobs.top_logprobs ? Object.entries(logprobs.top_logprobs[index]).map(
1167
+ ([token2, logprob]) => ({
1168
+ token: token2,
1169
+ logprob
1170
+ })
1171
+ ) : []
1172
+ }));
1173
+ }
1174
+ var OpenAICompletionLanguageModel = class {
1175
+ constructor(modelId, settings, config) {
1176
+ this.specificationVersion = "v1";
1177
+ this.defaultObjectGenerationMode = void 0;
1178
+ this.modelId = modelId;
1179
+ this.settings = settings;
1180
+ this.config = config;
1181
+ }
1182
+ get provider() {
1183
+ return this.config.provider;
1184
+ }
1185
+ getArgs({
1186
+ mode,
1187
+ inputFormat,
1188
+ prompt,
1189
+ maxTokens,
1190
+ temperature,
1191
+ topP,
1192
+ topK,
1193
+ frequencyPenalty,
1194
+ presencePenalty,
1195
+ stopSequences: userStopSequences,
1196
+ responseFormat,
1197
+ seed
1198
+ }) {
1199
+ var _a;
1200
+ const type = mode.type;
1201
+ const warnings = [];
1202
+ if (topK != null) {
1203
+ warnings.push({
1204
+ type: "unsupported-setting",
1205
+ setting: "topK"
1206
+ });
1207
+ }
1208
+ if (responseFormat != null && responseFormat.type !== "text") {
1209
+ warnings.push({
1210
+ type: "unsupported-setting",
1211
+ setting: "responseFormat",
1212
+ details: "JSON response format is not supported."
1213
+ });
1214
+ }
1215
+ const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt, inputFormat });
1216
+ const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
1217
+ const baseArgs = {
1218
+ // model id:
1219
+ model: this.modelId,
1220
+ // model specific settings:
1221
+ echo: this.settings.echo,
1222
+ logit_bias: this.settings.logitBias,
1223
+ logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
1224
+ suffix: this.settings.suffix,
1225
+ user: this.settings.user,
1226
+ // standardized settings:
1227
+ max_tokens: maxTokens,
1228
+ temperature,
1229
+ top_p: topP,
1230
+ frequency_penalty: frequencyPenalty,
1231
+ presence_penalty: presencePenalty,
1232
+ seed,
1233
+ // prompt:
1234
+ prompt: completionPrompt,
1235
+ // stop sequences:
1236
+ stop: stop.length > 0 ? stop : void 0
1237
+ };
1238
+ switch (type) {
1239
+ case "regular": {
1240
+ if ((_a = mode.tools) == null ? void 0 : _a.length) {
1241
+ throw new UnsupportedFunctionalityError({
1242
+ functionality: "tools"
1243
+ });
1244
+ }
1245
+ if (mode.toolChoice) {
1246
+ throw new UnsupportedFunctionalityError({
1247
+ functionality: "toolChoice"
1248
+ });
1249
+ }
1250
+ return { args: baseArgs, warnings };
1251
+ }
1252
+ case "object-json": {
1253
+ throw new UnsupportedFunctionalityError({
1254
+ functionality: "object-json mode"
1255
+ });
1256
+ }
1257
+ case "object-tool": {
1258
+ throw new UnsupportedFunctionalityError({
1259
+ functionality: "object-tool mode"
1260
+ });
1261
+ }
1262
+ default: {
1263
+ const _exhaustiveCheck = type;
1264
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
1265
+ }
1266
+ }
1267
+ }
1268
+ async doGenerate(options) {
1269
+ const { args, warnings } = this.getArgs(options);
1270
+ const {
1271
+ responseHeaders,
1272
+ value: response,
1273
+ rawValue: rawResponse
1274
+ } = await postJsonToApi({
1275
+ url: this.config.url({
1276
+ path: "/completions",
1277
+ modelId: this.modelId
1278
+ }),
1279
+ headers: combineHeaders(this.config.headers(), options.headers),
1280
+ body: args,
1281
+ failedResponseHandler: openaiFailedResponseHandler,
1282
+ successfulResponseHandler: createJsonResponseHandler(
1283
+ openaiCompletionResponseSchema
1284
+ ),
1285
+ abortSignal: options.abortSignal,
1286
+ fetch: this.config.fetch
1287
+ });
1288
+ const { prompt: rawPrompt, ...rawSettings } = args;
1289
+ const choice = response.choices[0];
1290
+ return {
1291
+ text: choice.text,
1292
+ usage: {
1293
+ promptTokens: response.usage.prompt_tokens,
1294
+ completionTokens: response.usage.completion_tokens
1295
+ },
1296
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
1297
+ logprobs: mapOpenAICompletionLogProbs(choice.logprobs),
1298
+ rawCall: { rawPrompt, rawSettings },
1299
+ rawResponse: { headers: responseHeaders, body: rawResponse },
1300
+ response: getResponseMetadata(response),
1301
+ warnings,
1302
+ request: { body: JSON.stringify(args) }
1303
+ };
1304
+ }
1305
+ async doStream(options) {
1306
+ const { args, warnings } = this.getArgs(options);
1307
+ const body = {
1308
+ ...args,
1309
+ stream: true,
1310
+ // only include stream_options when in strict compatibility mode:
1311
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
1312
+ };
1313
+ const { responseHeaders, value: response } = await postJsonToApi({
1314
+ url: this.config.url({
1315
+ path: "/completions",
1316
+ modelId: this.modelId
1317
+ }),
1318
+ headers: combineHeaders(this.config.headers(), options.headers),
1319
+ body,
1320
+ failedResponseHandler: openaiFailedResponseHandler,
1321
+ successfulResponseHandler: createEventSourceResponseHandler(
1322
+ openaiCompletionChunkSchema
1323
+ ),
1324
+ abortSignal: options.abortSignal,
1325
+ fetch: this.config.fetch
1326
+ });
1327
+ const { prompt: rawPrompt, ...rawSettings } = args;
1328
+ let finishReason = "unknown";
1329
+ let usage = {
1330
+ promptTokens: Number.NaN,
1331
+ completionTokens: Number.NaN
1332
+ };
1333
+ let logprobs;
1334
+ let isFirstChunk = true;
1335
+ return {
1336
+ stream: response.pipeThrough(
1337
+ new TransformStream({
1338
+ transform(chunk, controller) {
1339
+ if (!chunk.success) {
1340
+ finishReason = "error";
1341
+ controller.enqueue({ type: "error", error: chunk.error });
1342
+ return;
1343
+ }
1344
+ const value = chunk.value;
1345
+ if ("error" in value) {
1346
+ finishReason = "error";
1347
+ controller.enqueue({ type: "error", error: value.error });
1348
+ return;
1349
+ }
1350
+ if (isFirstChunk) {
1351
+ isFirstChunk = false;
1352
+ controller.enqueue({
1353
+ type: "response-metadata",
1354
+ ...getResponseMetadata(value)
1355
+ });
1356
+ }
1357
+ if (value.usage != null) {
1358
+ usage = {
1359
+ promptTokens: value.usage.prompt_tokens,
1360
+ completionTokens: value.usage.completion_tokens
1361
+ };
1362
+ }
1363
+ const choice = value.choices[0];
1364
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
1365
+ finishReason = mapOpenAIFinishReason(choice.finish_reason);
1366
+ }
1367
+ if ((choice == null ? void 0 : choice.text) != null) {
1368
+ controller.enqueue({
1369
+ type: "text-delta",
1370
+ textDelta: choice.text
1371
+ });
1372
+ }
1373
+ const mappedLogprobs = mapOpenAICompletionLogProbs(
1374
+ choice == null ? void 0 : choice.logprobs
1375
+ );
1376
+ if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
1377
+ if (logprobs === void 0) logprobs = [];
1378
+ logprobs.push(...mappedLogprobs);
1379
+ }
1380
+ },
1381
+ flush(controller) {
1382
+ controller.enqueue({
1383
+ type: "finish",
1384
+ finishReason,
1385
+ logprobs,
1386
+ usage
1387
+ });
1388
+ }
1389
+ })
1390
+ ),
1391
+ rawCall: { rawPrompt, rawSettings },
1392
+ rawResponse: { headers: responseHeaders },
1393
+ warnings,
1394
+ request: { body: JSON.stringify(body) }
1395
+ };
1396
+ }
1397
+ };
1398
+ var openaiCompletionResponseSchema = z3.object({
1399
+ id: z3.string().nullish(),
1400
+ created: z3.number().nullish(),
1401
+ model: z3.string().nullish(),
1402
+ choices: z3.array(
1403
+ z3.object({
1404
+ text: z3.string(),
1405
+ finish_reason: z3.string(),
1406
+ logprobs: z3.object({
1407
+ tokens: z3.array(z3.string()),
1408
+ token_logprobs: z3.array(z3.number()),
1409
+ top_logprobs: z3.array(z3.record(z3.string(), z3.number())).nullable()
1410
+ }).nullish()
1411
+ })
1412
+ ),
1413
+ usage: z3.object({
1414
+ prompt_tokens: z3.number(),
1415
+ completion_tokens: z3.number()
1416
+ })
1417
+ });
1418
+ var openaiCompletionChunkSchema = z3.union([
1419
+ z3.object({
1420
+ id: z3.string().nullish(),
1421
+ created: z3.number().nullish(),
1422
+ model: z3.string().nullish(),
1423
+ choices: z3.array(
1424
+ z3.object({
1425
+ text: z3.string(),
1426
+ finish_reason: z3.string().nullish(),
1427
+ index: z3.number(),
1428
+ logprobs: z3.object({
1429
+ tokens: z3.array(z3.string()),
1430
+ token_logprobs: z3.array(z3.number()),
1431
+ top_logprobs: z3.array(z3.record(z3.string(), z3.number())).nullable()
1432
+ }).nullish()
1433
+ })
1434
+ ),
1435
+ usage: z3.object({
1436
+ prompt_tokens: z3.number(),
1437
+ completion_tokens: z3.number()
1438
+ }).nullish()
1439
+ }),
1440
+ openaiErrorDataSchema
1441
+ ]);
1442
+ var OpenAIEmbeddingModel = class {
1443
+ constructor(modelId, settings, config) {
1444
+ this.specificationVersion = "v1";
1445
+ this.modelId = modelId;
1446
+ this.settings = settings;
1447
+ this.config = config;
1448
+ }
1449
+ get provider() {
1450
+ return this.config.provider;
1451
+ }
1452
+ get maxEmbeddingsPerCall() {
1453
+ var _a;
1454
+ return (_a = this.settings.maxEmbeddingsPerCall) != null ? _a : 2048;
1455
+ }
1456
+ get supportsParallelCalls() {
1457
+ var _a;
1458
+ return (_a = this.settings.supportsParallelCalls) != null ? _a : true;
1459
+ }
1460
+ async doEmbed({
1461
+ values,
1462
+ headers,
1463
+ abortSignal
1464
+ }) {
1465
+ if (values.length > this.maxEmbeddingsPerCall) {
1466
+ throw new TooManyEmbeddingValuesForCallError({
1467
+ provider: this.provider,
1468
+ modelId: this.modelId,
1469
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
1470
+ values
1471
+ });
1472
+ }
1473
+ const { responseHeaders, value: response } = await postJsonToApi({
1474
+ url: this.config.url({
1475
+ path: "/embeddings",
1476
+ modelId: this.modelId
1477
+ }),
1478
+ headers: combineHeaders(this.config.headers(), headers),
1479
+ body: {
1480
+ model: this.modelId,
1481
+ input: values,
1482
+ encoding_format: "float",
1483
+ dimensions: this.settings.dimensions,
1484
+ user: this.settings.user
1485
+ },
1486
+ failedResponseHandler: openaiFailedResponseHandler,
1487
+ successfulResponseHandler: createJsonResponseHandler(
1488
+ openaiTextEmbeddingResponseSchema
1489
+ ),
1490
+ abortSignal,
1491
+ fetch: this.config.fetch
1492
+ });
1493
+ return {
1494
+ embeddings: response.data.map((item) => item.embedding),
1495
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
1496
+ rawResponse: { headers: responseHeaders }
1497
+ };
1498
+ }
1499
+ };
1500
+ var openaiTextEmbeddingResponseSchema = z4.object({
1501
+ data: z4.array(z4.object({ embedding: z4.array(z4.number()) })),
1502
+ usage: z4.object({ prompt_tokens: z4.number() }).nullish()
1503
+ });
1504
+ var modelMaxImagesPerCall = {
1505
+ "dall-e-3": 1,
1506
+ "dall-e-2": 10,
1507
+ "gpt-image-1": 10
1508
+ };
1509
+ var hasDefaultResponseFormat = /* @__PURE__ */ new Set(["gpt-image-1"]);
1510
+ var OpenAIImageModel = class {
1511
+ constructor(modelId, settings, config) {
1512
+ this.modelId = modelId;
1513
+ this.settings = settings;
1514
+ this.config = config;
1515
+ this.specificationVersion = "v1";
1516
+ }
1517
+ get maxImagesPerCall() {
1518
+ var _a, _b;
1519
+ return (_b = (_a = this.settings.maxImagesPerCall) != null ? _a : modelMaxImagesPerCall[this.modelId]) != null ? _b : 1;
1520
+ }
1521
+ get provider() {
1522
+ return this.config.provider;
1523
+ }
1524
+ async doGenerate({
1525
+ prompt,
1526
+ n,
1527
+ size,
1528
+ aspectRatio,
1529
+ seed,
1530
+ providerOptions,
1531
+ headers,
1532
+ abortSignal
1533
+ }) {
1534
+ var _a, _b, _c, _d;
1535
+ const warnings = [];
1536
+ if (aspectRatio != null) {
1537
+ warnings.push({
1538
+ type: "unsupported-setting",
1539
+ setting: "aspectRatio",
1540
+ details: "This model does not support aspect ratio. Use `size` instead."
1541
+ });
1542
+ }
1543
+ if (seed != null) {
1544
+ warnings.push({ type: "unsupported-setting", setting: "seed" });
1545
+ }
1546
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1547
+ const { value: response, responseHeaders } = await postJsonToApi({
1548
+ url: this.config.url({
1549
+ path: "/images/generations",
1550
+ modelId: this.modelId
1551
+ }),
1552
+ headers: combineHeaders(this.config.headers(), headers),
1553
+ body: {
1554
+ model: this.modelId,
1555
+ prompt,
1556
+ n,
1557
+ size,
1558
+ ...(_d = providerOptions.openai) != null ? _d : {},
1559
+ ...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}
1560
+ },
1561
+ failedResponseHandler: openaiFailedResponseHandler,
1562
+ successfulResponseHandler: createJsonResponseHandler(
1563
+ openaiImageResponseSchema
1564
+ ),
1565
+ abortSignal,
1566
+ fetch: this.config.fetch
1567
+ });
1568
+ return {
1569
+ images: response.data.map((item) => item.b64_json),
1570
+ warnings,
1571
+ response: {
1572
+ timestamp: currentDate,
1573
+ modelId: this.modelId,
1574
+ headers: responseHeaders
1575
+ }
1576
+ };
1577
+ }
1578
+ };
1579
+ var openaiImageResponseSchema = z5.object({
1580
+ data: z5.array(z5.object({ b64_json: z5.string() }))
1581
+ });
1582
+ var openAIProviderOptionsSchema = z6.object({
1583
+ include: z6.array(z6.string()).nullish(),
1584
+ language: z6.string().nullish(),
1585
+ prompt: z6.string().nullish(),
1586
+ temperature: z6.number().min(0).max(1).nullish().default(0),
1587
+ timestampGranularities: z6.array(z6.enum(["word", "segment"])).nullish().default(["segment"])
1588
+ });
1589
+ var languageMap = {
1590
+ afrikaans: "af",
1591
+ arabic: "ar",
1592
+ armenian: "hy",
1593
+ azerbaijani: "az",
1594
+ belarusian: "be",
1595
+ bosnian: "bs",
1596
+ bulgarian: "bg",
1597
+ catalan: "ca",
1598
+ chinese: "zh",
1599
+ croatian: "hr",
1600
+ czech: "cs",
1601
+ danish: "da",
1602
+ dutch: "nl",
1603
+ english: "en",
1604
+ estonian: "et",
1605
+ finnish: "fi",
1606
+ french: "fr",
1607
+ galician: "gl",
1608
+ german: "de",
1609
+ greek: "el",
1610
+ hebrew: "he",
1611
+ hindi: "hi",
1612
+ hungarian: "hu",
1613
+ icelandic: "is",
1614
+ indonesian: "id",
1615
+ italian: "it",
1616
+ japanese: "ja",
1617
+ kannada: "kn",
1618
+ kazakh: "kk",
1619
+ korean: "ko",
1620
+ latvian: "lv",
1621
+ lithuanian: "lt",
1622
+ macedonian: "mk",
1623
+ malay: "ms",
1624
+ marathi: "mr",
1625
+ maori: "mi",
1626
+ nepali: "ne",
1627
+ norwegian: "no",
1628
+ persian: "fa",
1629
+ polish: "pl",
1630
+ portuguese: "pt",
1631
+ romanian: "ro",
1632
+ russian: "ru",
1633
+ serbian: "sr",
1634
+ slovak: "sk",
1635
+ slovenian: "sl",
1636
+ spanish: "es",
1637
+ swahili: "sw",
1638
+ swedish: "sv",
1639
+ tagalog: "tl",
1640
+ tamil: "ta",
1641
+ thai: "th",
1642
+ turkish: "tr",
1643
+ ukrainian: "uk",
1644
+ urdu: "ur",
1645
+ vietnamese: "vi",
1646
+ welsh: "cy"
1647
+ };
1648
+ var OpenAITranscriptionModel = class {
1649
+ constructor(modelId, config) {
1650
+ this.modelId = modelId;
1651
+ this.config = config;
1652
+ this.specificationVersion = "v1";
1653
+ }
1654
+ get provider() {
1655
+ return this.config.provider;
1656
+ }
1657
+ getArgs({
1658
+ audio,
1659
+ mediaType,
1660
+ providerOptions
1661
+ }) {
1662
+ var _a, _b, _c, _d, _e;
1663
+ const warnings = [];
1664
+ const openAIOptions = parseProviderOptions({
1665
+ provider: "openai",
1666
+ providerOptions,
1667
+ schema: openAIProviderOptionsSchema
1668
+ });
1669
+ const formData = new FormData();
1670
+ const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
1671
+ formData.append("model", this.modelId);
1672
+ formData.append("file", new File([blob], "audio", { type: mediaType }));
1673
+ if (openAIOptions) {
1674
+ const transcriptionModelOptions = {
1675
+ include: (_a = openAIOptions.include) != null ? _a : void 0,
1676
+ language: (_b = openAIOptions.language) != null ? _b : void 0,
1677
+ prompt: (_c = openAIOptions.prompt) != null ? _c : void 0,
1678
+ temperature: (_d = openAIOptions.temperature) != null ? _d : void 0,
1679
+ timestamp_granularities: (_e = openAIOptions.timestampGranularities) != null ? _e : void 0
1680
+ };
1681
+ for (const key in transcriptionModelOptions) {
1682
+ const value = transcriptionModelOptions[key];
1683
+ if (value !== void 0) {
1684
+ formData.append(key, String(value));
1685
+ }
1686
+ }
1687
+ }
1688
+ return {
1689
+ formData,
1690
+ warnings
1691
+ };
1692
+ }
1693
+ async doGenerate(options) {
1694
+ var _a, _b, _c, _d, _e, _f;
1695
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1696
+ const { formData, warnings } = this.getArgs(options);
1697
+ const {
1698
+ value: response,
1699
+ responseHeaders,
1700
+ rawValue: rawResponse
1701
+ } = await postFormDataToApi({
1702
+ url: this.config.url({
1703
+ path: "/audio/transcriptions",
1704
+ modelId: this.modelId
1705
+ }),
1706
+ headers: combineHeaders(this.config.headers(), options.headers),
1707
+ formData,
1708
+ failedResponseHandler: openaiFailedResponseHandler,
1709
+ successfulResponseHandler: createJsonResponseHandler(
1710
+ openaiTranscriptionResponseSchema
1711
+ ),
1712
+ abortSignal: options.abortSignal,
1713
+ fetch: this.config.fetch
1714
+ });
1715
+ const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0;
1716
+ return {
1717
+ text: response.text,
1718
+ segments: (_e = (_d = response.words) == null ? void 0 : _d.map((word) => ({
1719
+ text: word.word,
1720
+ startSecond: word.start,
1721
+ endSecond: word.end
1722
+ }))) != null ? _e : [],
1723
+ language,
1724
+ durationInSeconds: (_f = response.duration) != null ? _f : void 0,
1725
+ warnings,
1726
+ response: {
1727
+ timestamp: currentDate,
1728
+ modelId: this.modelId,
1729
+ headers: responseHeaders,
1730
+ body: rawResponse
1731
+ }
1732
+ };
1733
+ }
1734
+ };
1735
+ var openaiTranscriptionResponseSchema = z6.object({
1736
+ text: z6.string(),
1737
+ language: z6.string().nullish(),
1738
+ duration: z6.number().nullish(),
1739
+ words: z6.array(
1740
+ z6.object({
1741
+ word: z6.string(),
1742
+ start: z6.number(),
1743
+ end: z6.number()
1744
+ })
1745
+ ).nullish()
1746
+ });
1747
+ function convertToOpenAIResponsesMessages({
1748
+ prompt,
1749
+ systemMessageMode
1750
+ }) {
1751
+ const messages = [];
1752
+ const warnings = [];
1753
+ for (const { role, content } of prompt) {
1754
+ switch (role) {
1755
+ case "system": {
1756
+ switch (systemMessageMode) {
1757
+ case "system": {
1758
+ messages.push({ role: "system", content });
1759
+ break;
1760
+ }
1761
+ case "developer": {
1762
+ messages.push({ role: "developer", content });
1763
+ break;
1764
+ }
1765
+ case "remove": {
1766
+ warnings.push({
1767
+ type: "other",
1768
+ message: "system messages are removed for this model"
1769
+ });
1770
+ break;
1771
+ }
1772
+ default: {
1773
+ const _exhaustiveCheck = systemMessageMode;
1774
+ throw new Error(
1775
+ `Unsupported system message mode: ${_exhaustiveCheck}`
1776
+ );
1777
+ }
1778
+ }
1779
+ break;
1780
+ }
1781
+ case "user": {
1782
+ messages.push({
1783
+ role: "user",
1784
+ content: content.map((part, index) => {
1785
+ var _a, _b, _c, _d;
1786
+ switch (part.type) {
1787
+ case "text": {
1788
+ return { type: "input_text", text: part.text };
1789
+ }
1790
+ case "image": {
1791
+ return {
1792
+ type: "input_image",
1793
+ image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
1794
+ // OpenAI specific extension: image detail
1795
+ detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
1796
+ };
1797
+ }
1798
+ case "file": {
1799
+ if (part.data instanceof URL) {
1800
+ throw new UnsupportedFunctionalityError({
1801
+ functionality: "File URLs in user messages"
1802
+ });
1803
+ }
1804
+ switch (part.mimeType) {
1805
+ case "application/pdf": {
1806
+ return {
1807
+ type: "input_file",
1808
+ filename: (_d = part.filename) != null ? _d : `part-${index}.pdf`,
1809
+ file_data: `data:application/pdf;base64,${part.data}`
1810
+ };
1811
+ }
1812
+ default: {
1813
+ throw new UnsupportedFunctionalityError({
1814
+ functionality: "Only PDF files are supported in user messages"
1815
+ });
1816
+ }
1817
+ }
1818
+ }
1819
+ }
1820
+ })
1821
+ });
1822
+ break;
1823
+ }
1824
+ case "assistant": {
1825
+ for (const part of content) {
1826
+ switch (part.type) {
1827
+ case "text": {
1828
+ messages.push({
1829
+ role: "assistant",
1830
+ content: [{ type: "output_text", text: part.text }]
1831
+ });
1832
+ break;
1833
+ }
1834
+ case "tool-call": {
1835
+ messages.push({
1836
+ type: "function_call",
1837
+ call_id: part.toolCallId,
1838
+ name: part.toolName,
1839
+ arguments: JSON.stringify(part.args)
1840
+ });
1841
+ break;
1842
+ }
1843
+ }
1844
+ }
1845
+ break;
1846
+ }
1847
+ case "tool": {
1848
+ for (const part of content) {
1849
+ messages.push({
1850
+ type: "function_call_output",
1851
+ call_id: part.toolCallId,
1852
+ output: JSON.stringify(part.result)
1853
+ });
1854
+ }
1855
+ break;
1856
+ }
1857
+ default: {
1858
+ const _exhaustiveCheck = role;
1859
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1860
+ }
1861
+ }
1862
+ }
1863
+ return { messages, warnings };
1864
+ }
1865
+ function mapOpenAIResponseFinishReason({
1866
+ finishReason,
1867
+ hasToolCalls
1868
+ }) {
1869
+ switch (finishReason) {
1870
+ case void 0:
1871
+ case null:
1872
+ return hasToolCalls ? "tool-calls" : "stop";
1873
+ case "max_output_tokens":
1874
+ return "length";
1875
+ case "content_filter":
1876
+ return "content-filter";
1877
+ default:
1878
+ return hasToolCalls ? "tool-calls" : "unknown";
1879
+ }
1880
+ }
1881
+ function prepareResponsesTools({
1882
+ mode,
1883
+ strict
1884
+ }) {
1885
+ var _a;
1886
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
1887
+ const toolWarnings = [];
1888
+ if (tools == null) {
1889
+ return { tools: void 0, tool_choice: void 0, toolWarnings };
1890
+ }
1891
+ const toolChoice = mode.toolChoice;
1892
+ const openaiTools2 = [];
1893
+ for (const tool of tools) {
1894
+ switch (tool.type) {
1895
+ case "function":
1896
+ openaiTools2.push({
1897
+ type: "function",
1898
+ name: tool.name,
1899
+ description: tool.description,
1900
+ parameters: tool.parameters,
1901
+ strict: strict ? true : void 0
1902
+ });
1903
+ break;
1904
+ case "provider-defined":
1905
+ switch (tool.id) {
1906
+ case "openai.web_search_preview":
1907
+ openaiTools2.push({
1908
+ type: "web_search_preview",
1909
+ search_context_size: tool.args.searchContextSize,
1910
+ user_location: tool.args.userLocation
1911
+ });
1912
+ break;
1913
+ default:
1914
+ toolWarnings.push({ type: "unsupported-tool", tool });
1915
+ break;
1916
+ }
1917
+ break;
1918
+ default:
1919
+ toolWarnings.push({ type: "unsupported-tool", tool });
1920
+ break;
1921
+ }
1922
+ }
1923
+ if (toolChoice == null) {
1924
+ return { tools: openaiTools2, tool_choice: void 0, toolWarnings };
1925
+ }
1926
+ const type = toolChoice.type;
1927
+ switch (type) {
1928
+ case "auto":
1929
+ case "none":
1930
+ case "required":
1931
+ return { tools: openaiTools2, tool_choice: type, toolWarnings };
1932
+ case "tool": {
1933
+ if (toolChoice.toolName === "web_search_preview") {
1934
+ return {
1935
+ tools: openaiTools2,
1936
+ tool_choice: {
1937
+ type: "web_search_preview"
1938
+ },
1939
+ toolWarnings
1940
+ };
1941
+ }
1942
+ return {
1943
+ tools: openaiTools2,
1944
+ tool_choice: {
1945
+ type: "function",
1946
+ name: toolChoice.toolName
1947
+ },
1948
+ toolWarnings
1949
+ };
1950
+ }
1951
+ default: {
1952
+ const _exhaustiveCheck = type;
1953
+ throw new UnsupportedFunctionalityError({
1954
+ functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
1955
+ });
1956
+ }
1957
+ }
1958
+ }
1959
+ var OpenAIResponsesLanguageModel = class {
1960
+ constructor(modelId, config) {
1961
+ this.specificationVersion = "v1";
1962
+ this.defaultObjectGenerationMode = "json";
1963
+ this.supportsStructuredOutputs = true;
1964
+ this.modelId = modelId;
1965
+ this.config = config;
1966
+ }
1967
+ get provider() {
1968
+ return this.config.provider;
1969
+ }
1970
+ getArgs({
1971
+ mode,
1972
+ maxTokens,
1973
+ temperature,
1974
+ stopSequences,
1975
+ topP,
1976
+ topK,
1977
+ presencePenalty,
1978
+ frequencyPenalty,
1979
+ seed,
1980
+ prompt,
1981
+ providerMetadata,
1982
+ responseFormat
1983
+ }) {
1984
+ var _a, _b, _c;
1985
+ const warnings = [];
1986
+ const modelConfig = getResponsesModelConfig(this.modelId);
1987
+ const type = mode.type;
1988
+ if (topK != null) {
1989
+ warnings.push({
1990
+ type: "unsupported-setting",
1991
+ setting: "topK"
1992
+ });
1993
+ }
1994
+ if (seed != null) {
1995
+ warnings.push({
1996
+ type: "unsupported-setting",
1997
+ setting: "seed"
1998
+ });
1999
+ }
2000
+ if (presencePenalty != null) {
2001
+ warnings.push({
2002
+ type: "unsupported-setting",
2003
+ setting: "presencePenalty"
2004
+ });
2005
+ }
2006
+ if (frequencyPenalty != null) {
2007
+ warnings.push({
2008
+ type: "unsupported-setting",
2009
+ setting: "frequencyPenalty"
2010
+ });
2011
+ }
2012
+ if (stopSequences != null) {
2013
+ warnings.push({
2014
+ type: "unsupported-setting",
2015
+ setting: "stopSequences"
2016
+ });
2017
+ }
2018
+ const { messages, warnings: messageWarnings } = convertToOpenAIResponsesMessages({
2019
+ prompt,
2020
+ systemMessageMode: modelConfig.systemMessageMode
2021
+ });
2022
+ warnings.push(...messageWarnings);
2023
+ const openaiOptions = parseProviderOptions({
2024
+ provider: "openai",
2025
+ providerOptions: providerMetadata,
2026
+ schema: openaiResponsesProviderOptionsSchema
2027
+ });
2028
+ const isStrict = (_a = openaiOptions == null ? void 0 : openaiOptions.strictSchemas) != null ? _a : true;
2029
+ const baseArgs = {
2030
+ model: this.modelId,
2031
+ input: messages,
2032
+ temperature,
2033
+ top_p: topP,
2034
+ max_output_tokens: maxTokens,
2035
+ ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && {
2036
+ text: {
2037
+ format: responseFormat.schema != null ? {
2038
+ type: "json_schema",
2039
+ strict: isStrict,
2040
+ name: (_b = responseFormat.name) != null ? _b : "response",
2041
+ description: responseFormat.description,
2042
+ schema: responseFormat.schema
2043
+ } : { type: "json_object" }
2044
+ }
2045
+ },
2046
+ // provider options:
2047
+ metadata: openaiOptions == null ? void 0 : openaiOptions.metadata,
2048
+ parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls,
2049
+ previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId,
2050
+ store: openaiOptions == null ? void 0 : openaiOptions.store,
2051
+ user: openaiOptions == null ? void 0 : openaiOptions.user,
2052
+ instructions: openaiOptions == null ? void 0 : openaiOptions.instructions,
2053
+ // model-specific settings:
2054
+ ...modelConfig.isReasoningModel && ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) && {
2055
+ reasoning: {
2056
+ ...(openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null && {
2057
+ effort: openaiOptions.reasoningEffort
2058
+ },
2059
+ ...(openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && {
2060
+ summary: openaiOptions.reasoningSummary
2061
+ }
2062
+ }
2063
+ },
2064
+ ...modelConfig.requiredAutoTruncation && {
2065
+ truncation: "auto"
2066
+ }
2067
+ };
2068
+ if (modelConfig.isReasoningModel) {
2069
+ if (baseArgs.temperature != null) {
2070
+ baseArgs.temperature = void 0;
2071
+ warnings.push({
2072
+ type: "unsupported-setting",
2073
+ setting: "temperature",
2074
+ details: "temperature is not supported for reasoning models"
2075
+ });
2076
+ }
2077
+ if (baseArgs.top_p != null) {
2078
+ baseArgs.top_p = void 0;
2079
+ warnings.push({
2080
+ type: "unsupported-setting",
2081
+ setting: "topP",
2082
+ details: "topP is not supported for reasoning models"
2083
+ });
2084
+ }
2085
+ }
2086
+ switch (type) {
2087
+ case "regular": {
2088
+ const { tools, tool_choice, toolWarnings } = prepareResponsesTools({
2089
+ mode,
2090
+ strict: isStrict
2091
+ // TODO support provider options on tools
2092
+ });
2093
+ return {
2094
+ args: {
2095
+ ...baseArgs,
2096
+ tools,
2097
+ tool_choice
2098
+ },
2099
+ warnings: [...warnings, ...toolWarnings]
2100
+ };
2101
+ }
2102
+ case "object-json": {
2103
+ return {
2104
+ args: {
2105
+ ...baseArgs,
2106
+ text: {
2107
+ format: mode.schema != null ? {
2108
+ type: "json_schema",
2109
+ strict: isStrict,
2110
+ name: (_c = mode.name) != null ? _c : "response",
2111
+ description: mode.description,
2112
+ schema: mode.schema
2113
+ } : { type: "json_object" }
2114
+ }
2115
+ },
2116
+ warnings
2117
+ };
2118
+ }
2119
+ case "object-tool": {
2120
+ return {
2121
+ args: {
2122
+ ...baseArgs,
2123
+ tool_choice: { type: "function", name: mode.tool.name },
2124
+ tools: [
2125
+ {
2126
+ type: "function",
2127
+ name: mode.tool.name,
2128
+ description: mode.tool.description,
2129
+ parameters: mode.tool.parameters,
2130
+ strict: isStrict
2131
+ }
2132
+ ]
2133
+ },
2134
+ warnings
2135
+ };
2136
+ }
2137
+ default: {
2138
+ const _exhaustiveCheck = type;
2139
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
2140
+ }
2141
+ }
2142
+ }
2143
+ async doGenerate(options) {
2144
+ var _a, _b, _c, _d, _e, _f, _g;
2145
+ const { args: body, warnings } = this.getArgs(options);
2146
+ const url = this.config.url({
2147
+ path: "/responses",
2148
+ modelId: this.modelId
2149
+ });
2150
+ const {
2151
+ responseHeaders,
2152
+ value: response,
2153
+ rawValue: rawResponse
2154
+ } = await postJsonToApi({
2155
+ url,
2156
+ headers: combineHeaders(this.config.headers(), options.headers),
2157
+ body,
2158
+ failedResponseHandler: openaiFailedResponseHandler,
2159
+ successfulResponseHandler: createJsonResponseHandler(
2160
+ z7.object({
2161
+ id: z7.string(),
2162
+ created_at: z7.number(),
2163
+ error: z7.object({
2164
+ message: z7.string(),
2165
+ code: z7.string()
2166
+ }).nullish(),
2167
+ model: z7.string(),
2168
+ output: z7.array(
2169
+ z7.discriminatedUnion("type", [
2170
+ z7.object({
2171
+ type: z7.literal("message"),
2172
+ role: z7.literal("assistant"),
2173
+ content: z7.array(
2174
+ z7.object({
2175
+ type: z7.literal("output_text"),
2176
+ text: z7.string(),
2177
+ annotations: z7.array(
2178
+ z7.object({
2179
+ type: z7.literal("url_citation"),
2180
+ start_index: z7.number(),
2181
+ end_index: z7.number(),
2182
+ url: z7.string(),
2183
+ title: z7.string()
2184
+ })
2185
+ )
2186
+ })
2187
+ )
2188
+ }),
2189
+ z7.object({
2190
+ type: z7.literal("function_call"),
2191
+ call_id: z7.string(),
2192
+ name: z7.string(),
2193
+ arguments: z7.string()
2194
+ }),
2195
+ z7.object({
2196
+ type: z7.literal("web_search_call")
2197
+ }),
2198
+ z7.object({
2199
+ type: z7.literal("computer_call")
2200
+ }),
2201
+ z7.object({
2202
+ type: z7.literal("reasoning"),
2203
+ summary: z7.array(
2204
+ z7.object({
2205
+ type: z7.literal("summary_text"),
2206
+ text: z7.string()
2207
+ })
2208
+ )
2209
+ })
2210
+ ])
2211
+ ),
2212
+ incomplete_details: z7.object({ reason: z7.string() }).nullable(),
2213
+ usage: usageSchema
2214
+ })
2215
+ ),
2216
+ abortSignal: options.abortSignal,
2217
+ fetch: this.config.fetch
2218
+ });
2219
+ if (response.error) {
2220
+ throw new APICallError({
2221
+ message: response.error.message,
2222
+ url,
2223
+ requestBodyValues: body,
2224
+ statusCode: 400,
2225
+ responseHeaders,
2226
+ responseBody: rawResponse,
2227
+ isRetryable: false
2228
+ });
2229
+ }
2230
+ const outputTextElements = response.output.filter((output) => output.type === "message").flatMap((output) => output.content).filter((content) => content.type === "output_text");
2231
+ const toolCalls = response.output.filter((output) => output.type === "function_call").map((output) => ({
2232
+ toolCallType: "function",
2233
+ toolCallId: output.call_id,
2234
+ toolName: output.name,
2235
+ args: output.arguments
2236
+ }));
2237
+ const reasoningSummary = (_b = (_a = response.output.find((item) => item.type === "reasoning")) == null ? void 0 : _a.summary) != null ? _b : null;
2238
+ return {
2239
+ text: outputTextElements.map((content) => content.text).join("\n"),
2240
+ sources: outputTextElements.flatMap(
2241
+ (content) => content.annotations.map((annotation) => {
2242
+ var _a2, _b2, _c2;
2243
+ return {
2244
+ sourceType: "url",
2245
+ id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId(),
2246
+ url: annotation.url,
2247
+ title: annotation.title
2248
+ };
2249
+ })
2250
+ ),
2251
+ finishReason: mapOpenAIResponseFinishReason({
2252
+ finishReason: (_c = response.incomplete_details) == null ? void 0 : _c.reason,
2253
+ hasToolCalls: toolCalls.length > 0
2254
+ }),
2255
+ toolCalls: toolCalls.length > 0 ? toolCalls : void 0,
2256
+ reasoning: reasoningSummary ? reasoningSummary.map((summary) => ({
2257
+ type: "text",
2258
+ text: summary.text
2259
+ })) : void 0,
2260
+ usage: {
2261
+ promptTokens: response.usage.input_tokens,
2262
+ completionTokens: response.usage.output_tokens
2263
+ },
2264
+ rawCall: {
2265
+ rawPrompt: void 0,
2266
+ rawSettings: {}
2267
+ },
2268
+ rawResponse: {
2269
+ headers: responseHeaders,
2270
+ body: rawResponse
2271
+ },
2272
+ request: {
2273
+ body: JSON.stringify(body)
2274
+ },
2275
+ response: {
2276
+ id: response.id,
2277
+ timestamp: new Date(response.created_at * 1e3),
2278
+ modelId: response.model
2279
+ },
2280
+ providerMetadata: {
2281
+ openai: {
2282
+ responseId: response.id,
2283
+ cachedPromptTokens: (_e = (_d = response.usage.input_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _e : null,
2284
+ reasoningTokens: (_g = (_f = response.usage.output_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : null
2285
+ }
2286
+ },
2287
+ warnings
2288
+ };
2289
+ }
2290
+ async doStream(options) {
2291
+ const { args: body, warnings } = this.getArgs(options);
2292
+ const { responseHeaders, value: response } = await postJsonToApi({
2293
+ url: this.config.url({
2294
+ path: "/responses",
2295
+ modelId: this.modelId
2296
+ }),
2297
+ headers: combineHeaders(this.config.headers(), options.headers),
2298
+ body: {
2299
+ ...body,
2300
+ stream: true
2301
+ },
2302
+ failedResponseHandler: openaiFailedResponseHandler,
2303
+ successfulResponseHandler: createEventSourceResponseHandler(
2304
+ openaiResponsesChunkSchema
2305
+ ),
2306
+ abortSignal: options.abortSignal,
2307
+ fetch: this.config.fetch
2308
+ });
2309
+ const self = this;
2310
+ let finishReason = "unknown";
2311
+ let promptTokens = NaN;
2312
+ let completionTokens = NaN;
2313
+ let cachedPromptTokens = null;
2314
+ let reasoningTokens = null;
2315
+ let responseId = null;
2316
+ const ongoingToolCalls = {};
2317
+ let hasToolCalls = false;
2318
+ return {
2319
+ stream: response.pipeThrough(
2320
+ new TransformStream({
2321
+ transform(chunk, controller) {
2322
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2323
+ if (!chunk.success) {
2324
+ finishReason = "error";
2325
+ controller.enqueue({ type: "error", error: chunk.error });
2326
+ return;
2327
+ }
2328
+ const value = chunk.value;
2329
+ if (isResponseOutputItemAddedChunk(value)) {
2330
+ if (value.item.type === "function_call") {
2331
+ ongoingToolCalls[value.output_index] = {
2332
+ toolName: value.item.name,
2333
+ toolCallId: value.item.call_id
2334
+ };
2335
+ controller.enqueue({
2336
+ type: "tool-call-delta",
2337
+ toolCallType: "function",
2338
+ toolCallId: value.item.call_id,
2339
+ toolName: value.item.name,
2340
+ argsTextDelta: value.item.arguments
2341
+ });
2342
+ }
2343
+ } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) {
2344
+ const toolCall = ongoingToolCalls[value.output_index];
2345
+ if (toolCall != null) {
2346
+ controller.enqueue({
2347
+ type: "tool-call-delta",
2348
+ toolCallType: "function",
2349
+ toolCallId: toolCall.toolCallId,
2350
+ toolName: toolCall.toolName,
2351
+ argsTextDelta: value.delta
2352
+ });
2353
+ }
2354
+ } else if (isResponseCreatedChunk(value)) {
2355
+ responseId = value.response.id;
2356
+ controller.enqueue({
2357
+ type: "response-metadata",
2358
+ id: value.response.id,
2359
+ timestamp: new Date(value.response.created_at * 1e3),
2360
+ modelId: value.response.model
2361
+ });
2362
+ } else if (isTextDeltaChunk(value)) {
2363
+ controller.enqueue({
2364
+ type: "text-delta",
2365
+ textDelta: value.delta
2366
+ });
2367
+ } else if (isResponseReasoningSummaryTextDeltaChunk(value)) {
2368
+ controller.enqueue({
2369
+ type: "reasoning",
2370
+ textDelta: value.delta
2371
+ });
2372
+ } else if (isResponseOutputItemDoneChunk(value) && value.item.type === "function_call") {
2373
+ ongoingToolCalls[value.output_index] = void 0;
2374
+ hasToolCalls = true;
2375
+ controller.enqueue({
2376
+ type: "tool-call",
2377
+ toolCallType: "function",
2378
+ toolCallId: value.item.call_id,
2379
+ toolName: value.item.name,
2380
+ args: value.item.arguments
2381
+ });
2382
+ } else if (isResponseFinishedChunk(value)) {
2383
+ finishReason = mapOpenAIResponseFinishReason({
2384
+ finishReason: (_a = value.response.incomplete_details) == null ? void 0 : _a.reason,
2385
+ hasToolCalls
2386
+ });
2387
+ promptTokens = value.response.usage.input_tokens;
2388
+ completionTokens = value.response.usage.output_tokens;
2389
+ cachedPromptTokens = (_c = (_b = value.response.usage.input_tokens_details) == null ? void 0 : _b.cached_tokens) != null ? _c : cachedPromptTokens;
2390
+ reasoningTokens = (_e = (_d = value.response.usage.output_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : reasoningTokens;
2391
+ } else if (isResponseAnnotationAddedChunk(value)) {
2392
+ controller.enqueue({
2393
+ type: "source",
2394
+ source: {
2395
+ sourceType: "url",
2396
+ id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(),
2397
+ url: value.annotation.url,
2398
+ title: value.annotation.title
2399
+ }
2400
+ });
2401
+ } else if (isErrorChunk(value)) {
2402
+ controller.enqueue({ type: "error", error: value });
2403
+ }
2404
+ },
2405
+ flush(controller) {
2406
+ controller.enqueue({
2407
+ type: "finish",
2408
+ finishReason,
2409
+ usage: { promptTokens, completionTokens },
2410
+ ...(cachedPromptTokens != null || reasoningTokens != null) && {
2411
+ providerMetadata: {
2412
+ openai: {
2413
+ responseId,
2414
+ cachedPromptTokens,
2415
+ reasoningTokens
2416
+ }
2417
+ }
2418
+ }
2419
+ });
2420
+ }
2421
+ })
2422
+ ),
2423
+ rawCall: {
2424
+ rawPrompt: void 0,
2425
+ rawSettings: {}
2426
+ },
2427
+ rawResponse: { headers: responseHeaders },
2428
+ request: { body: JSON.stringify(body) },
2429
+ warnings
2430
+ };
2431
+ }
2432
+ };
2433
+ var usageSchema = z7.object({
2434
+ input_tokens: z7.number(),
2435
+ input_tokens_details: z7.object({ cached_tokens: z7.number().nullish() }).nullish(),
2436
+ output_tokens: z7.number(),
2437
+ output_tokens_details: z7.object({ reasoning_tokens: z7.number().nullish() }).nullish()
2438
+ });
2439
+ var textDeltaChunkSchema = z7.object({
2440
+ type: z7.literal("response.output_text.delta"),
2441
+ delta: z7.string()
2442
+ });
2443
+ var responseFinishedChunkSchema = z7.object({
2444
+ type: z7.enum(["response.completed", "response.incomplete"]),
2445
+ response: z7.object({
2446
+ incomplete_details: z7.object({ reason: z7.string() }).nullish(),
2447
+ usage: usageSchema
2448
+ })
2449
+ });
2450
+ var responseCreatedChunkSchema = z7.object({
2451
+ type: z7.literal("response.created"),
2452
+ response: z7.object({
2453
+ id: z7.string(),
2454
+ created_at: z7.number(),
2455
+ model: z7.string()
2456
+ })
2457
+ });
2458
+ var responseOutputItemDoneSchema = z7.object({
2459
+ type: z7.literal("response.output_item.done"),
2460
+ output_index: z7.number(),
2461
+ item: z7.discriminatedUnion("type", [
2462
+ z7.object({
2463
+ type: z7.literal("message")
2464
+ }),
2465
+ z7.object({
2466
+ type: z7.literal("function_call"),
2467
+ id: z7.string(),
2468
+ call_id: z7.string(),
2469
+ name: z7.string(),
2470
+ arguments: z7.string(),
2471
+ status: z7.literal("completed")
2472
+ })
2473
+ ])
2474
+ });
2475
+ var responseFunctionCallArgumentsDeltaSchema = z7.object({
2476
+ type: z7.literal("response.function_call_arguments.delta"),
2477
+ item_id: z7.string(),
2478
+ output_index: z7.number(),
2479
+ delta: z7.string()
2480
+ });
2481
+ var responseOutputItemAddedSchema = z7.object({
2482
+ type: z7.literal("response.output_item.added"),
2483
+ output_index: z7.number(),
2484
+ item: z7.discriminatedUnion("type", [
2485
+ z7.object({
2486
+ type: z7.literal("message")
2487
+ }),
2488
+ z7.object({
2489
+ type: z7.literal("function_call"),
2490
+ id: z7.string(),
2491
+ call_id: z7.string(),
2492
+ name: z7.string(),
2493
+ arguments: z7.string()
2494
+ })
2495
+ ])
2496
+ });
2497
+ var responseAnnotationAddedSchema = z7.object({
2498
+ type: z7.literal("response.output_text.annotation.added"),
2499
+ annotation: z7.object({
2500
+ type: z7.literal("url_citation"),
2501
+ url: z7.string(),
2502
+ title: z7.string()
2503
+ })
2504
+ });
2505
+ var responseReasoningSummaryTextDeltaSchema = z7.object({
2506
+ type: z7.literal("response.reasoning_summary_text.delta"),
2507
+ item_id: z7.string(),
2508
+ output_index: z7.number(),
2509
+ summary_index: z7.number(),
2510
+ delta: z7.string()
2511
+ });
2512
+ var errorChunkSchema = z7.object({
2513
+ type: z7.literal("error"),
2514
+ code: z7.string(),
2515
+ message: z7.string(),
2516
+ param: z7.string().nullish(),
2517
+ sequence_number: z7.number()
2518
+ });
2519
+ var openaiResponsesChunkSchema = z7.union([
2520
+ textDeltaChunkSchema,
2521
+ responseFinishedChunkSchema,
2522
+ responseCreatedChunkSchema,
2523
+ responseOutputItemDoneSchema,
2524
+ responseFunctionCallArgumentsDeltaSchema,
2525
+ responseOutputItemAddedSchema,
2526
+ responseAnnotationAddedSchema,
2527
+ responseReasoningSummaryTextDeltaSchema,
2528
+ errorChunkSchema,
2529
+ z7.object({ type: z7.string() }).passthrough()
2530
+ // fallback for unknown chunks
2531
+ ]);
2532
+ function isTextDeltaChunk(chunk) {
2533
+ return chunk.type === "response.output_text.delta";
2534
+ }
2535
+ function isResponseOutputItemDoneChunk(chunk) {
2536
+ return chunk.type === "response.output_item.done";
2537
+ }
2538
+ function isResponseFinishedChunk(chunk) {
2539
+ return chunk.type === "response.completed" || chunk.type === "response.incomplete";
2540
+ }
2541
+ function isResponseCreatedChunk(chunk) {
2542
+ return chunk.type === "response.created";
2543
+ }
2544
+ function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
2545
+ return chunk.type === "response.function_call_arguments.delta";
2546
+ }
2547
+ function isResponseOutputItemAddedChunk(chunk) {
2548
+ return chunk.type === "response.output_item.added";
2549
+ }
2550
+ function isResponseAnnotationAddedChunk(chunk) {
2551
+ return chunk.type === "response.output_text.annotation.added";
2552
+ }
2553
+ function isResponseReasoningSummaryTextDeltaChunk(chunk) {
2554
+ return chunk.type === "response.reasoning_summary_text.delta";
2555
+ }
2556
+ function isErrorChunk(chunk) {
2557
+ return chunk.type === "error";
2558
+ }
2559
+ function getResponsesModelConfig(modelId) {
2560
+ if (modelId.startsWith("o") || modelId.startsWith("gpt-5")) {
2561
+ if (modelId.startsWith("o1-mini") || modelId.startsWith("o1-preview")) {
2562
+ return {
2563
+ isReasoningModel: true,
2564
+ systemMessageMode: "remove",
2565
+ requiredAutoTruncation: false
2566
+ };
2567
+ }
2568
+ return {
2569
+ isReasoningModel: true,
2570
+ systemMessageMode: "developer",
2571
+ requiredAutoTruncation: false
2572
+ };
2573
+ }
2574
+ return {
2575
+ isReasoningModel: false,
2576
+ systemMessageMode: "system",
2577
+ requiredAutoTruncation: false
2578
+ };
2579
+ }
2580
+ var openaiResponsesProviderOptionsSchema = z7.object({
2581
+ metadata: z7.any().nullish(),
2582
+ parallelToolCalls: z7.boolean().nullish(),
2583
+ previousResponseId: z7.string().nullish(),
2584
+ store: z7.boolean().nullish(),
2585
+ user: z7.string().nullish(),
2586
+ reasoningEffort: z7.string().nullish(),
2587
+ strictSchemas: z7.boolean().nullish(),
2588
+ instructions: z7.string().nullish(),
2589
+ reasoningSummary: z7.string().nullish()
2590
+ });
2591
+ var WebSearchPreviewParameters = z8.object({});
2592
+ function webSearchPreviewTool({
2593
+ searchContextSize,
2594
+ userLocation
2595
+ } = {}) {
2596
+ return {
2597
+ type: "provider-defined",
2598
+ id: "openai.web_search_preview",
2599
+ args: {
2600
+ searchContextSize,
2601
+ userLocation
2602
+ },
2603
+ parameters: WebSearchPreviewParameters
2604
+ };
2605
+ }
2606
+ var openaiTools = {
2607
+ webSearchPreview: webSearchPreviewTool
2608
+ };
2609
+ var OpenAIProviderOptionsSchema = z9.object({
2610
+ instructions: z9.string().nullish(),
2611
+ speed: z9.number().min(0.25).max(4).default(1).nullish()
2612
+ });
2613
+ var OpenAISpeechModel = class {
2614
+ constructor(modelId, config) {
2615
+ this.modelId = modelId;
2616
+ this.config = config;
2617
+ this.specificationVersion = "v1";
2618
+ }
2619
+ get provider() {
2620
+ return this.config.provider;
2621
+ }
2622
+ getArgs({
2623
+ text,
2624
+ voice = "alloy",
2625
+ outputFormat = "mp3",
2626
+ speed,
2627
+ instructions,
2628
+ providerOptions
2629
+ }) {
2630
+ const warnings = [];
2631
+ const openAIOptions = parseProviderOptions({
2632
+ provider: "openai",
2633
+ providerOptions,
2634
+ schema: OpenAIProviderOptionsSchema
2635
+ });
2636
+ const requestBody = {
2637
+ model: this.modelId,
2638
+ input: text,
2639
+ voice,
2640
+ response_format: "mp3",
2641
+ speed,
2642
+ instructions
2643
+ };
2644
+ if (outputFormat) {
2645
+ if (["mp3", "opus", "aac", "flac", "wav", "pcm"].includes(outputFormat)) {
2646
+ requestBody.response_format = outputFormat;
2647
+ } else {
2648
+ warnings.push({
2649
+ type: "unsupported-setting",
2650
+ setting: "outputFormat",
2651
+ details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`
2652
+ });
2653
+ }
2654
+ }
2655
+ if (openAIOptions) {
2656
+ const speechModelOptions = {};
2657
+ for (const key in speechModelOptions) {
2658
+ const value = speechModelOptions[key];
2659
+ if (value !== void 0) {
2660
+ requestBody[key] = value;
2661
+ }
2662
+ }
2663
+ }
2664
+ return {
2665
+ requestBody,
2666
+ warnings
2667
+ };
2668
+ }
2669
+ async doGenerate(options) {
2670
+ var _a, _b, _c;
2671
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
2672
+ const { requestBody, warnings } = this.getArgs(options);
2673
+ const {
2674
+ value: audio,
2675
+ responseHeaders,
2676
+ rawValue: rawResponse
2677
+ } = await postJsonToApi({
2678
+ url: this.config.url({
2679
+ path: "/audio/speech",
2680
+ modelId: this.modelId
2681
+ }),
2682
+ headers: combineHeaders(this.config.headers(), options.headers),
2683
+ body: requestBody,
2684
+ failedResponseHandler: openaiFailedResponseHandler,
2685
+ successfulResponseHandler: createBinaryResponseHandler(),
2686
+ abortSignal: options.abortSignal,
2687
+ fetch: this.config.fetch
2688
+ });
2689
+ return {
2690
+ audio,
2691
+ warnings,
2692
+ request: {
2693
+ body: JSON.stringify(requestBody)
2694
+ },
2695
+ response: {
2696
+ timestamp: currentDate,
2697
+ modelId: this.modelId,
2698
+ headers: responseHeaders,
2699
+ body: rawResponse
2700
+ }
2701
+ };
2702
+ }
2703
+ };
2704
+ function createOpenAI(options = {}) {
2705
+ var _a, _b, _c;
2706
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
2707
+ const compatibility = (_b = options.compatibility) != null ? _b : "compatible";
2708
+ const providerName = (_c = options.name) != null ? _c : "openai";
2709
+ const getHeaders = () => ({
2710
+ Authorization: `Bearer ${loadApiKey({
2711
+ apiKey: options.apiKey,
2712
+ environmentVariableName: "OPENAI_API_KEY",
2713
+ description: "OpenAI"
2714
+ })}`,
2715
+ "OpenAI-Organization": options.organization,
2716
+ "OpenAI-Project": options.project,
2717
+ ...options.headers
2718
+ });
2719
+ const createChatModel = (modelId, settings = {}) => new OpenAIChatLanguageModel(modelId, settings, {
2720
+ provider: `${providerName}.chat`,
2721
+ url: ({ path }) => `${baseURL}${path}`,
2722
+ headers: getHeaders,
2723
+ compatibility,
2724
+ fetch: options.fetch
2725
+ });
2726
+ const createCompletionModel = (modelId, settings = {}) => new OpenAICompletionLanguageModel(modelId, settings, {
2727
+ provider: `${providerName}.completion`,
2728
+ url: ({ path }) => `${baseURL}${path}`,
2729
+ headers: getHeaders,
2730
+ compatibility,
2731
+ fetch: options.fetch
2732
+ });
2733
+ const createEmbeddingModel = (modelId, settings = {}) => new OpenAIEmbeddingModel(modelId, settings, {
2734
+ provider: `${providerName}.embedding`,
2735
+ url: ({ path }) => `${baseURL}${path}`,
2736
+ headers: getHeaders,
2737
+ fetch: options.fetch
2738
+ });
2739
+ const createImageModel = (modelId, settings = {}) => new OpenAIImageModel(modelId, settings, {
2740
+ provider: `${providerName}.image`,
2741
+ url: ({ path }) => `${baseURL}${path}`,
2742
+ headers: getHeaders,
2743
+ fetch: options.fetch
2744
+ });
2745
+ const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
2746
+ provider: `${providerName}.transcription`,
2747
+ url: ({ path }) => `${baseURL}${path}`,
2748
+ headers: getHeaders,
2749
+ fetch: options.fetch
2750
+ });
2751
+ const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
2752
+ provider: `${providerName}.speech`,
2753
+ url: ({ path }) => `${baseURL}${path}`,
2754
+ headers: getHeaders,
2755
+ fetch: options.fetch
2756
+ });
2757
+ const createLanguageModel = (modelId, settings) => {
2758
+ if (new.target) {
2759
+ throw new Error(
2760
+ "The OpenAI model function cannot be called with the new keyword."
2761
+ );
2762
+ }
2763
+ if (modelId === "gpt-3.5-turbo-instruct") {
2764
+ return createCompletionModel(
2765
+ modelId,
2766
+ settings
2767
+ );
2768
+ }
2769
+ return createChatModel(modelId, settings);
2770
+ };
2771
+ const createResponsesModel = (modelId) => {
2772
+ return new OpenAIResponsesLanguageModel(modelId, {
2773
+ provider: `${providerName}.responses`,
2774
+ url: ({ path }) => `${baseURL}${path}`,
2775
+ headers: getHeaders,
2776
+ fetch: options.fetch
2777
+ });
2778
+ };
2779
+ const provider = function(modelId, settings) {
2780
+ return createLanguageModel(modelId, settings);
2781
+ };
2782
+ provider.languageModel = createLanguageModel;
2783
+ provider.chat = createChatModel;
2784
+ provider.completion = createCompletionModel;
2785
+ provider.responses = createResponsesModel;
2786
+ provider.embedding = createEmbeddingModel;
2787
+ provider.textEmbedding = createEmbeddingModel;
2788
+ provider.textEmbeddingModel = createEmbeddingModel;
2789
+ provider.image = createImageModel;
2790
+ provider.imageModel = createImageModel;
2791
+ provider.transcription = createTranscriptionModel;
2792
+ provider.transcriptionModel = createTranscriptionModel;
2793
+ provider.speech = createSpeechModel;
2794
+ provider.speechModel = createSpeechModel;
2795
+ provider.tools = openaiTools;
2796
+ return provider;
2797
+ }
2798
+ var openai = createOpenAI({
2799
+ compatibility: "strict"
2800
+ // strict for OpenAI API
2801
+ });
2802
+ export {
2803
+ createOpenAI,
2804
+ openai
2805
+ };