@ai-sdk/openai 0.0.37 → 0.0.39

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.
@@ -27,13 +27,17 @@ __export(internal_exports, {
27
27
  module.exports = __toCommonJS(internal_exports);
28
28
 
29
29
  // src/openai-chat-language-model.ts
30
- var import_provider = require("@ai-sdk/provider");
30
+ var import_provider2 = require("@ai-sdk/provider");
31
31
  var import_provider_utils3 = require("@ai-sdk/provider-utils");
32
32
  var import_zod2 = require("zod");
33
33
 
34
34
  // src/convert-to-openai-chat-messages.ts
35
+ var import_provider = require("@ai-sdk/provider");
35
36
  var import_provider_utils = require("@ai-sdk/provider-utils");
36
- function convertToOpenAIChatMessages(prompt) {
37
+ function convertToOpenAIChatMessages({
38
+ prompt,
39
+ useLegacyFunctionCalling = false
40
+ }) {
37
41
  const messages = [];
38
42
  for (const { role, content } of prompt) {
39
43
  switch (role) {
@@ -93,20 +97,41 @@ function convertToOpenAIChatMessages(prompt) {
93
97
  }
94
98
  }
95
99
  }
96
- messages.push({
97
- role: "assistant",
98
- content: text,
99
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
100
- });
100
+ if (useLegacyFunctionCalling) {
101
+ if (toolCalls.length > 1) {
102
+ throw new import_provider.UnsupportedFunctionalityError({
103
+ functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
104
+ });
105
+ }
106
+ messages.push({
107
+ role: "assistant",
108
+ content: text,
109
+ function_call: toolCalls.length > 0 ? toolCalls[0].function : void 0
110
+ });
111
+ } else {
112
+ messages.push({
113
+ role: "assistant",
114
+ content: text,
115
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
116
+ });
117
+ }
101
118
  break;
102
119
  }
103
120
  case "tool": {
104
121
  for (const toolResponse of content) {
105
- messages.push({
106
- role: "tool",
107
- tool_call_id: toolResponse.toolCallId,
108
- content: JSON.stringify(toolResponse.result)
109
- });
122
+ if (useLegacyFunctionCalling) {
123
+ messages.push({
124
+ role: "function",
125
+ name: toolResponse.toolName,
126
+ content: JSON.stringify(toolResponse.result)
127
+ });
128
+ } else {
129
+ messages.push({
130
+ role: "tool",
131
+ tool_call_id: toolResponse.toolCallId,
132
+ content: JSON.stringify(toolResponse.result)
133
+ });
134
+ }
110
135
  }
111
136
  break;
112
137
  }
@@ -183,11 +208,34 @@ var OpenAIChatLanguageModel = class {
183
208
  maxTokens,
184
209
  temperature,
185
210
  topP,
211
+ topK,
186
212
  frequencyPenalty,
187
213
  presencePenalty,
214
+ stopSequences,
215
+ responseFormat,
188
216
  seed
189
217
  }) {
190
218
  const type = mode.type;
219
+ const warnings = [];
220
+ if (topK != null) {
221
+ warnings.push({
222
+ type: "unsupported-setting",
223
+ setting: "topK"
224
+ });
225
+ }
226
+ if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) {
227
+ warnings.push({
228
+ type: "unsupported-setting",
229
+ setting: "responseFormat",
230
+ details: "JSON response format schema is not supported"
231
+ });
232
+ }
233
+ const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
234
+ if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
235
+ throw new import_provider2.UnsupportedFunctionalityError({
236
+ functionality: "useLegacyFunctionCalling with parallelToolCalls"
237
+ });
238
+ }
191
239
  const baseArgs = {
192
240
  // model id:
193
241
  model: this.modelId,
@@ -203,41 +251,69 @@ var OpenAIChatLanguageModel = class {
203
251
  top_p: topP,
204
252
  frequency_penalty: frequencyPenalty,
205
253
  presence_penalty: presencePenalty,
254
+ stop: stopSequences,
206
255
  seed,
256
+ // response format:
257
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { type: "json_object" } : void 0,
207
258
  // messages:
208
- messages: convertToOpenAIChatMessages(prompt)
259
+ messages: convertToOpenAIChatMessages({
260
+ prompt,
261
+ useLegacyFunctionCalling
262
+ })
209
263
  };
210
264
  switch (type) {
211
265
  case "regular": {
212
- return { ...baseArgs, ...prepareToolsAndToolChoice(mode) };
266
+ return {
267
+ args: {
268
+ ...baseArgs,
269
+ ...prepareToolsAndToolChoice({ mode, useLegacyFunctionCalling })
270
+ },
271
+ warnings
272
+ };
213
273
  }
214
274
  case "object-json": {
215
275
  return {
216
- ...baseArgs,
217
- response_format: { type: "json_object" }
276
+ args: {
277
+ ...baseArgs,
278
+ response_format: { type: "json_object" }
279
+ },
280
+ warnings
218
281
  };
219
282
  }
220
283
  case "object-tool": {
221
284
  return {
222
- ...baseArgs,
223
- tool_choice: { type: "function", function: { name: mode.tool.name } },
224
- tools: [
225
- {
226
- type: "function",
227
- function: {
285
+ args: useLegacyFunctionCalling ? {
286
+ ...baseArgs,
287
+ function_call: {
288
+ name: mode.tool.name
289
+ },
290
+ functions: [
291
+ {
228
292
  name: mode.tool.name,
229
293
  description: mode.tool.description,
230
294
  parameters: mode.tool.parameters
231
295
  }
232
- }
233
- ]
296
+ ]
297
+ } : {
298
+ ...baseArgs,
299
+ tool_choice: {
300
+ type: "function",
301
+ function: { name: mode.tool.name }
302
+ },
303
+ tools: [
304
+ {
305
+ type: "function",
306
+ function: {
307
+ name: mode.tool.name,
308
+ description: mode.tool.description,
309
+ parameters: mode.tool.parameters
310
+ }
311
+ }
312
+ ]
313
+ },
314
+ warnings
234
315
  };
235
316
  }
236
- case "object-grammar": {
237
- throw new import_provider.UnsupportedFunctionalityError({
238
- functionality: "object-grammar mode"
239
- });
240
- }
241
317
  default: {
242
318
  const _exhaustiveCheck = type;
243
319
  throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
@@ -246,7 +322,7 @@ var OpenAIChatLanguageModel = class {
246
322
  }
247
323
  async doGenerate(options) {
248
324
  var _a, _b;
249
- const args = this.getArgs(options);
325
+ const { args, warnings } = this.getArgs(options);
250
326
  const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
251
327
  url: this.config.url({
252
328
  path: "/chat/completions",
@@ -265,7 +341,14 @@ var OpenAIChatLanguageModel = class {
265
341
  const choice = response.choices[0];
266
342
  return {
267
343
  text: (_a = choice.message.content) != null ? _a : void 0,
268
- toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => {
344
+ toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
345
+ {
346
+ toolCallType: "function",
347
+ toolCallId: (0, import_provider_utils3.generateId)(),
348
+ toolName: choice.message.function_call.name,
349
+ args: choice.message.function_call.arguments
350
+ }
351
+ ] : (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => {
269
352
  var _a2;
270
353
  return {
271
354
  toolCallType: "function",
@@ -281,12 +364,12 @@ var OpenAIChatLanguageModel = class {
281
364
  },
282
365
  rawCall: { rawPrompt, rawSettings },
283
366
  rawResponse: { headers: responseHeaders },
284
- warnings: [],
367
+ warnings,
285
368
  logprobs: mapOpenAIChatLogProbsOutput(choice.logprobs)
286
369
  };
287
370
  }
288
371
  async doStream(options) {
289
- const args = this.getArgs(options);
372
+ const { args, warnings } = this.getArgs(options);
290
373
  const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
291
374
  url: this.config.url({
292
375
  path: "/chat/completions",
@@ -314,6 +397,7 @@ var OpenAIChatLanguageModel = class {
314
397
  completionTokens: Number.NaN
315
398
  };
316
399
  let logprobs;
400
+ const { useLegacyFunctionCalling } = this.settings;
317
401
  return {
318
402
  stream: response.pipeThrough(
319
403
  new TransformStream({
@@ -358,24 +442,32 @@ var OpenAIChatLanguageModel = class {
358
442
  logprobs = [];
359
443
  logprobs.push(...mappedLogprobs);
360
444
  }
361
- if (delta.tool_calls != null) {
362
- for (const toolCallDelta of delta.tool_calls) {
445
+ const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
446
+ {
447
+ type: "function",
448
+ id: (0, import_provider_utils3.generateId)(),
449
+ function: delta.function_call,
450
+ index: 0
451
+ }
452
+ ] : delta.tool_calls;
453
+ if (mappedToolCalls != null) {
454
+ for (const toolCallDelta of mappedToolCalls) {
363
455
  const index = toolCallDelta.index;
364
456
  if (toolCalls[index] == null) {
365
457
  if (toolCallDelta.type !== "function") {
366
- throw new import_provider.InvalidResponseDataError({
458
+ throw new import_provider2.InvalidResponseDataError({
367
459
  data: toolCallDelta,
368
460
  message: `Expected 'function' type.`
369
461
  });
370
462
  }
371
463
  if (toolCallDelta.id == null) {
372
- throw new import_provider.InvalidResponseDataError({
464
+ throw new import_provider2.InvalidResponseDataError({
373
465
  data: toolCallDelta,
374
466
  message: `Expected 'id' to be a string.`
375
467
  });
376
468
  }
377
469
  if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
378
- throw new import_provider.InvalidResponseDataError({
470
+ throw new import_provider2.InvalidResponseDataError({
379
471
  data: toolCallDelta,
380
472
  message: `Expected 'function.name' to be a string.`
381
473
  });
@@ -442,7 +534,7 @@ var OpenAIChatLanguageModel = class {
442
534
  ),
443
535
  rawCall: { rawPrompt, rawSettings },
444
536
  rawResponse: { headers: responseHeaders },
445
- warnings: []
537
+ warnings
446
538
  };
447
539
  }
448
540
  };
@@ -451,17 +543,21 @@ var openAIChatResponseSchema = import_zod2.z.object({
451
543
  import_zod2.z.object({
452
544
  message: import_zod2.z.object({
453
545
  role: import_zod2.z.literal("assistant"),
454
- content: import_zod2.z.string().nullable().optional(),
546
+ content: import_zod2.z.string().nullish(),
547
+ function_call: import_zod2.z.object({
548
+ arguments: import_zod2.z.string(),
549
+ name: import_zod2.z.string()
550
+ }).nullish(),
455
551
  tool_calls: import_zod2.z.array(
456
552
  import_zod2.z.object({
457
- id: import_zod2.z.string().optional().nullable(),
553
+ id: import_zod2.z.string().nullish(),
458
554
  type: import_zod2.z.literal("function"),
459
555
  function: import_zod2.z.object({
460
556
  name: import_zod2.z.string(),
461
557
  arguments: import_zod2.z.string()
462
558
  })
463
559
  })
464
- ).optional()
560
+ ).nullish()
465
561
  }),
466
562
  index: import_zod2.z.number(),
467
563
  logprobs: import_zod2.z.object({
@@ -477,8 +573,8 @@ var openAIChatResponseSchema = import_zod2.z.object({
477
573
  )
478
574
  })
479
575
  ).nullable()
480
- }).nullable().optional(),
481
- finish_reason: import_zod2.z.string().optional().nullable()
576
+ }).nullish(),
577
+ finish_reason: import_zod2.z.string().nullish()
482
578
  })
483
579
  ),
484
580
  usage: import_zod2.z.object({
@@ -493,6 +589,10 @@ var openaiChatChunkSchema = import_zod2.z.union([
493
589
  delta: import_zod2.z.object({
494
590
  role: import_zod2.z.enum(["assistant"]).optional(),
495
591
  content: import_zod2.z.string().nullish(),
592
+ function_call: import_zod2.z.object({
593
+ name: import_zod2.z.string().optional(),
594
+ arguments: import_zod2.z.string().optional()
595
+ }).nullish(),
496
596
  tool_calls: import_zod2.z.array(
497
597
  import_zod2.z.object({
498
598
  index: import_zod2.z.number(),
@@ -530,12 +630,45 @@ var openaiChatChunkSchema = import_zod2.z.union([
530
630
  }),
531
631
  openAIErrorDataSchema
532
632
  ]);
533
- function prepareToolsAndToolChoice(mode) {
633
+ function prepareToolsAndToolChoice({
634
+ mode,
635
+ useLegacyFunctionCalling = false
636
+ }) {
534
637
  var _a;
535
638
  const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
536
639
  if (tools == null) {
537
640
  return { tools: void 0, tool_choice: void 0 };
538
641
  }
642
+ const toolChoice = mode.toolChoice;
643
+ if (useLegacyFunctionCalling) {
644
+ const mappedFunctions = tools.map((tool) => ({
645
+ name: tool.name,
646
+ description: tool.description,
647
+ parameters: tool.parameters
648
+ }));
649
+ if (toolChoice == null) {
650
+ return { functions: mappedFunctions, function_call: void 0 };
651
+ }
652
+ const type2 = toolChoice.type;
653
+ switch (type2) {
654
+ case "auto":
655
+ case "none":
656
+ case void 0:
657
+ return {
658
+ functions: mappedFunctions,
659
+ function_call: void 0
660
+ };
661
+ case "required":
662
+ throw new import_provider2.UnsupportedFunctionalityError({
663
+ functionality: "useLegacyFunctionCalling and toolChoice: required"
664
+ });
665
+ default:
666
+ return {
667
+ functions: mappedFunctions,
668
+ function_call: { name: toolChoice.toolName }
669
+ };
670
+ }
671
+ }
539
672
  const mappedTools = tools.map((tool) => ({
540
673
  type: "function",
541
674
  function: {
@@ -544,7 +677,6 @@ function prepareToolsAndToolChoice(mode) {
544
677
  parameters: tool.parameters
545
678
  }
546
679
  }));
547
- const toolChoice = mode.toolChoice;
548
680
  if (toolChoice == null) {
549
681
  return { tools: mappedTools, tool_choice: void 0 };
550
682
  }
@@ -572,12 +704,12 @@ function prepareToolsAndToolChoice(mode) {
572
704
  }
573
705
 
574
706
  // src/openai-completion-language-model.ts
575
- var import_provider3 = require("@ai-sdk/provider");
707
+ var import_provider4 = require("@ai-sdk/provider");
576
708
  var import_provider_utils4 = require("@ai-sdk/provider-utils");
577
709
  var import_zod3 = require("zod");
578
710
 
579
711
  // src/convert-to-openai-completion-prompt.ts
580
- var import_provider2 = require("@ai-sdk/provider");
712
+ var import_provider3 = require("@ai-sdk/provider");
581
713
  function convertToOpenAICompletionPrompt({
582
714
  prompt,
583
715
  inputFormat,
@@ -597,7 +729,7 @@ function convertToOpenAICompletionPrompt({
597
729
  for (const { role, content } of prompt) {
598
730
  switch (role) {
599
731
  case "system": {
600
- throw new import_provider2.InvalidPromptError({
732
+ throw new import_provider3.InvalidPromptError({
601
733
  message: "Unexpected system message in prompt: ${content}",
602
734
  prompt
603
735
  });
@@ -609,7 +741,7 @@ function convertToOpenAICompletionPrompt({
609
741
  return part.text;
610
742
  }
611
743
  case "image": {
612
- throw new import_provider2.UnsupportedFunctionalityError({
744
+ throw new import_provider3.UnsupportedFunctionalityError({
613
745
  functionality: "images"
614
746
  });
615
747
  }
@@ -628,7 +760,7 @@ ${userMessage}
628
760
  return part.text;
629
761
  }
630
762
  case "tool-call": {
631
- throw new import_provider2.UnsupportedFunctionalityError({
763
+ throw new import_provider3.UnsupportedFunctionalityError({
632
764
  functionality: "tool-call messages"
633
765
  });
634
766
  }
@@ -641,7 +773,7 @@ ${assistantMessage}
641
773
  break;
642
774
  }
643
775
  case "tool": {
644
- throw new import_provider2.UnsupportedFunctionalityError({
776
+ throw new import_provider3.UnsupportedFunctionalityError({
645
777
  functionality: "tool messages"
646
778
  });
647
779
  }
@@ -693,13 +825,31 @@ var OpenAICompletionLanguageModel = class {
693
825
  maxTokens,
694
826
  temperature,
695
827
  topP,
828
+ topK,
696
829
  frequencyPenalty,
697
830
  presencePenalty,
831
+ stopSequences: userStopSequences,
832
+ responseFormat,
698
833
  seed
699
834
  }) {
700
835
  var _a;
701
836
  const type = mode.type;
837
+ const warnings = [];
838
+ if (topK != null) {
839
+ warnings.push({
840
+ type: "unsupported-setting",
841
+ setting: "topK"
842
+ });
843
+ }
844
+ if (responseFormat != null && responseFormat.type !== "text") {
845
+ warnings.push({
846
+ type: "unsupported-setting",
847
+ setting: "responseFormat",
848
+ details: "JSON response format is not supported."
849
+ });
850
+ }
702
851
  const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt, inputFormat });
852
+ const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
703
853
  const baseArgs = {
704
854
  // model id:
705
855
  model: this.modelId,
@@ -719,37 +869,32 @@ var OpenAICompletionLanguageModel = class {
719
869
  // prompt:
720
870
  prompt: completionPrompt,
721
871
  // stop sequences:
722
- stop: stopSequences
872
+ stop: stop.length > 0 ? stop : void 0
723
873
  };
724
874
  switch (type) {
725
875
  case "regular": {
726
876
  if ((_a = mode.tools) == null ? void 0 : _a.length) {
727
- throw new import_provider3.UnsupportedFunctionalityError({
877
+ throw new import_provider4.UnsupportedFunctionalityError({
728
878
  functionality: "tools"
729
879
  });
730
880
  }
731
881
  if (mode.toolChoice) {
732
- throw new import_provider3.UnsupportedFunctionalityError({
882
+ throw new import_provider4.UnsupportedFunctionalityError({
733
883
  functionality: "toolChoice"
734
884
  });
735
885
  }
736
- return baseArgs;
886
+ return { args: baseArgs, warnings };
737
887
  }
738
888
  case "object-json": {
739
- throw new import_provider3.UnsupportedFunctionalityError({
889
+ throw new import_provider4.UnsupportedFunctionalityError({
740
890
  functionality: "object-json mode"
741
891
  });
742
892
  }
743
893
  case "object-tool": {
744
- throw new import_provider3.UnsupportedFunctionalityError({
894
+ throw new import_provider4.UnsupportedFunctionalityError({
745
895
  functionality: "object-tool mode"
746
896
  });
747
897
  }
748
- case "object-grammar": {
749
- throw new import_provider3.UnsupportedFunctionalityError({
750
- functionality: "object-grammar mode"
751
- });
752
- }
753
898
  default: {
754
899
  const _exhaustiveCheck = type;
755
900
  throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
@@ -757,7 +902,7 @@ var OpenAICompletionLanguageModel = class {
757
902
  }
758
903
  }
759
904
  async doGenerate(options) {
760
- const args = this.getArgs(options);
905
+ const { args, warnings } = this.getArgs(options);
761
906
  const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
762
907
  url: this.config.url({
763
908
  path: "/completions",
@@ -784,11 +929,11 @@ var OpenAICompletionLanguageModel = class {
784
929
  logprobs: mapOpenAICompletionLogProbs(choice.logprobs),
785
930
  rawCall: { rawPrompt, rawSettings },
786
931
  rawResponse: { headers: responseHeaders },
787
- warnings: []
932
+ warnings
788
933
  };
789
934
  }
790
935
  async doStream(options) {
791
- const args = this.getArgs(options);
936
+ const { args, warnings } = this.getArgs(options);
792
937
  const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
793
938
  url: this.config.url({
794
939
  path: "/completions",
@@ -796,7 +941,7 @@ var OpenAICompletionLanguageModel = class {
796
941
  }),
797
942
  headers: (0, import_provider_utils4.combineHeaders)(this.config.headers(), options.headers),
798
943
  body: {
799
- ...this.getArgs(options),
944
+ ...args,
800
945
  stream: true,
801
946
  // only include stream_options when in strict compatibility mode:
802
947
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
@@ -867,7 +1012,7 @@ var OpenAICompletionLanguageModel = class {
867
1012
  ),
868
1013
  rawCall: { rawPrompt, rawSettings },
869
1014
  rawResponse: { headers: responseHeaders },
870
- warnings: []
1015
+ warnings
871
1016
  };
872
1017
  }
873
1018
  };
@@ -911,7 +1056,7 @@ var openaiCompletionChunkSchema = import_zod3.z.union([
911
1056
  ]);
912
1057
 
913
1058
  // src/openai-embedding-model.ts
914
- var import_provider4 = require("@ai-sdk/provider");
1059
+ var import_provider5 = require("@ai-sdk/provider");
915
1060
  var import_provider_utils5 = require("@ai-sdk/provider-utils");
916
1061
  var import_zod4 = require("zod");
917
1062
  var OpenAIEmbeddingModel = class {
@@ -938,7 +1083,7 @@ var OpenAIEmbeddingModel = class {
938
1083
  abortSignal
939
1084
  }) {
940
1085
  if (values.length > this.maxEmbeddingsPerCall) {
941
- throw new import_provider4.TooManyEmbeddingValuesForCallError({
1086
+ throw new import_provider5.TooManyEmbeddingValuesForCallError({
942
1087
  provider: this.provider,
943
1088
  modelId: this.modelId,
944
1089
  maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,