ai 5.0.0-canary.19 → 5.0.0-canary.20

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.
@@ -4,8 +4,8 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
6
  var __export = (target, all) => {
7
- for (var name6 in all)
8
- __defProp(target, name6, { get: all[name6], enumerable: true });
7
+ for (var name5 in all)
8
+ __defProp(target, name5, { get: all[name5], enumerable: true });
9
9
  };
10
10
  var __copyProps = (to, from, except, desc) => {
11
11
  if (from && typeof from === "object" || typeof from === "function") {
@@ -20,71 +20,20 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // internal/index.ts
21
21
  var internal_exports = {};
22
22
  __export(internal_exports, {
23
- HANGING_STREAM_WARNING_TIME_MS: () => HANGING_STREAM_WARNING_TIME_MS,
23
+ convertAsyncIteratorToReadableStream: () => import_provider_utils7.convertAsyncIteratorToReadableStream,
24
24
  convertToLanguageModelPrompt: () => convertToLanguageModelPrompt,
25
- createCallbacksTransformer: () => createCallbacksTransformer,
26
25
  prepareCallSettings: () => prepareCallSettings,
27
26
  prepareRetries: () => prepareRetries,
28
27
  prepareToolsAndToolChoice: () => prepareToolsAndToolChoice,
29
28
  standardizePrompt: () => standardizePrompt
30
29
  });
31
30
  module.exports = __toCommonJS(internal_exports);
31
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
32
32
 
33
33
  // core/prompt/convert-to-language-model-prompt.ts
34
34
  var import_provider_utils3 = require("@ai-sdk/provider-utils");
35
35
 
36
- // util/download-error.ts
37
- var import_provider = require("@ai-sdk/provider");
38
- var name = "AI_DownloadError";
39
- var marker = `vercel.ai.error.${name}`;
40
- var symbol = Symbol.for(marker);
41
- var _a;
42
- var DownloadError = class extends import_provider.AISDKError {
43
- constructor({
44
- url,
45
- statusCode,
46
- statusText,
47
- cause,
48
- message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
49
- }) {
50
- super({ name, message, cause });
51
- this[_a] = true;
52
- this.url = url;
53
- this.statusCode = statusCode;
54
- this.statusText = statusText;
55
- }
56
- static isInstance(error) {
57
- return import_provider.AISDKError.hasMarker(error, marker);
58
- }
59
- };
60
- _a = symbol;
61
-
62
- // util/download.ts
63
- async function download({ url }) {
64
- var _a6;
65
- const urlText = url.toString();
66
- try {
67
- const response = await fetch(urlText);
68
- if (!response.ok) {
69
- throw new DownloadError({
70
- url: urlText,
71
- statusCode: response.status,
72
- statusText: response.statusText
73
- });
74
- }
75
- return {
76
- data: new Uint8Array(await response.arrayBuffer()),
77
- mediaType: (_a6 = response.headers.get("content-type")) != null ? _a6 : void 0
78
- };
79
- } catch (error) {
80
- if (DownloadError.isInstance(error)) {
81
- throw error;
82
- }
83
- throw new DownloadError({ url: urlText, cause: error });
84
- }
85
- }
86
-
87
- // core/util/detect-media-type.ts
36
+ // src/util/detect-media-type.ts
88
37
  var import_provider_utils = require("@ai-sdk/provider-utils");
89
38
  var imageMediaTypeSignatures = [
90
39
  {
@@ -185,6 +134,57 @@ function detectMediaType({
185
134
  return void 0;
186
135
  }
187
136
 
137
+ // src/util/download-error.ts
138
+ var import_provider = require("@ai-sdk/provider");
139
+ var name = "AI_DownloadError";
140
+ var marker = `vercel.ai.error.${name}`;
141
+ var symbol = Symbol.for(marker);
142
+ var _a;
143
+ var DownloadError = class extends import_provider.AISDKError {
144
+ constructor({
145
+ url,
146
+ statusCode,
147
+ statusText,
148
+ cause,
149
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
150
+ }) {
151
+ super({ name, message, cause });
152
+ this[_a] = true;
153
+ this.url = url;
154
+ this.statusCode = statusCode;
155
+ this.statusText = statusText;
156
+ }
157
+ static isInstance(error) {
158
+ return import_provider.AISDKError.hasMarker(error, marker);
159
+ }
160
+ };
161
+ _a = symbol;
162
+
163
+ // src/util/download.ts
164
+ async function download({ url }) {
165
+ var _a5;
166
+ const urlText = url.toString();
167
+ try {
168
+ const response = await fetch(urlText);
169
+ if (!response.ok) {
170
+ throw new DownloadError({
171
+ url: urlText,
172
+ statusCode: response.status,
173
+ statusText: response.statusText
174
+ });
175
+ }
176
+ return {
177
+ data: new Uint8Array(await response.arrayBuffer()),
178
+ mediaType: (_a5 = response.headers.get("content-type")) != null ? _a5 : void 0
179
+ };
180
+ } catch (error) {
181
+ if (DownloadError.isInstance(error)) {
182
+ throw error;
183
+ }
184
+ throw new DownloadError({ url: urlText, cause: error });
185
+ }
186
+ }
187
+
188
188
  // core/prompt/data-content.ts
189
189
  var import_provider2 = require("@ai-sdk/provider");
190
190
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
@@ -214,8 +214,8 @@ var dataContentSchema = import_zod.z.union([
214
214
  import_zod.z.custom(
215
215
  // Buffer might not be available in some environments such as CloudFlare:
216
216
  (value) => {
217
- var _a6, _b;
218
- return (_b = (_a6 = globalThis.Buffer) == null ? void 0 : _a6.isBuffer(value)) != null ? _b : false;
217
+ var _a5, _b;
218
+ return (_b = (_a5 = globalThis.Buffer) == null ? void 0 : _a5.isBuffer(value)) != null ? _b : false;
219
219
  },
220
220
  { message: "Must be a Buffer" }
221
221
  )
@@ -394,8 +394,8 @@ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
394
394
  ).flat().filter(
395
395
  (part) => part.type === "image" || part.type === "file"
396
396
  ).map((part) => {
397
- var _a6;
398
- const mediaType = (_a6 = part.mediaType) != null ? _a6 : part.type === "image" ? "image/*" : void 0;
397
+ var _a5;
398
+ const mediaType = (_a5 = part.mediaType) != null ? _a5 : part.type === "image" ? "image/*" : void 0;
399
399
  let data = part.type === "image" ? part.image : part.data;
400
400
  if (typeof data === "string") {
401
401
  try {
@@ -422,7 +422,7 @@ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
422
422
  );
423
423
  }
424
424
  function convertPartToLanguageModelPart(part, downloadedAssets) {
425
- var _a6, _b;
425
+ var _a5, _b;
426
426
  if (part.type === "text") {
427
427
  return {
428
428
  type: "text",
@@ -449,7 +449,7 @@ function convertPartToLanguageModelPart(part, downloadedAssets) {
449
449
  const downloadedFile = downloadedAssets[data.toString()];
450
450
  if (downloadedFile) {
451
451
  data = downloadedFile.data;
452
- mediaType = (_a6 = downloadedFile.mediaType) != null ? _a6 : mediaType;
452
+ mediaType = (_a5 = downloadedFile.mediaType) != null ? _a5 : mediaType;
453
453
  }
454
454
  }
455
455
  switch (type) {
@@ -481,7 +481,7 @@ function convertPartToLanguageModelPart(part, downloadedAssets) {
481
481
  }
482
482
  }
483
483
 
484
- // errors/invalid-argument-error.ts
484
+ // src/error/invalid-argument-error.ts
485
485
  var import_provider4 = require("@ai-sdk/provider");
486
486
  var name3 = "AI_InvalidArgumentError";
487
487
  var marker3 = `vercel.ai.error.${name3}`;
@@ -600,118 +600,10 @@ function prepareCallSettings({
600
600
  };
601
601
  }
602
602
 
603
- // util/retry-with-exponential-backoff.ts
604
- var import_provider6 = require("@ai-sdk/provider");
603
+ // core/prompt/prepare-tools-and-tool-choice.ts
605
604
  var import_provider_utils4 = require("@ai-sdk/provider-utils");
606
605
 
607
- // util/retry-error.ts
608
- var import_provider5 = require("@ai-sdk/provider");
609
- var name4 = "AI_RetryError";
610
- var marker4 = `vercel.ai.error.${name4}`;
611
- var symbol4 = Symbol.for(marker4);
612
- var _a4;
613
- var RetryError = class extends import_provider5.AISDKError {
614
- constructor({
615
- message,
616
- reason,
617
- errors
618
- }) {
619
- super({ name: name4, message });
620
- this[_a4] = true;
621
- this.reason = reason;
622
- this.errors = errors;
623
- this.lastError = errors[errors.length - 1];
624
- }
625
- static isInstance(error) {
626
- return import_provider5.AISDKError.hasMarker(error, marker4);
627
- }
628
- };
629
- _a4 = symbol4;
630
-
631
- // util/retry-with-exponential-backoff.ts
632
- var retryWithExponentialBackoff = ({
633
- maxRetries = 2,
634
- initialDelayInMs = 2e3,
635
- backoffFactor = 2
636
- } = {}) => async (f) => _retryWithExponentialBackoff(f, {
637
- maxRetries,
638
- delayInMs: initialDelayInMs,
639
- backoffFactor
640
- });
641
- async function _retryWithExponentialBackoff(f, {
642
- maxRetries,
643
- delayInMs,
644
- backoffFactor
645
- }, errors = []) {
646
- try {
647
- return await f();
648
- } catch (error) {
649
- if ((0, import_provider_utils4.isAbortError)(error)) {
650
- throw error;
651
- }
652
- if (maxRetries === 0) {
653
- throw error;
654
- }
655
- const errorMessage = (0, import_provider_utils4.getErrorMessage)(error);
656
- const newErrors = [...errors, error];
657
- const tryNumber = newErrors.length;
658
- if (tryNumber > maxRetries) {
659
- throw new RetryError({
660
- message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
661
- reason: "maxRetriesExceeded",
662
- errors: newErrors
663
- });
664
- }
665
- if (error instanceof Error && import_provider6.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
666
- await (0, import_provider_utils4.delay)(delayInMs);
667
- return _retryWithExponentialBackoff(
668
- f,
669
- { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
670
- newErrors
671
- );
672
- }
673
- if (tryNumber === 1) {
674
- throw error;
675
- }
676
- throw new RetryError({
677
- message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
678
- reason: "errorNotRetryable",
679
- errors: newErrors
680
- });
681
- }
682
- }
683
-
684
- // core/prompt/prepare-retries.ts
685
- function prepareRetries({
686
- maxRetries
687
- }) {
688
- if (maxRetries != null) {
689
- if (!Number.isInteger(maxRetries)) {
690
- throw new InvalidArgumentError({
691
- parameter: "maxRetries",
692
- value: maxRetries,
693
- message: "maxRetries must be an integer"
694
- });
695
- }
696
- if (maxRetries < 0) {
697
- throw new InvalidArgumentError({
698
- parameter: "maxRetries",
699
- value: maxRetries,
700
- message: "maxRetries must be >= 0"
701
- });
702
- }
703
- }
704
- const maxRetriesResult = maxRetries != null ? maxRetries : 2;
705
- return {
706
- maxRetries: maxRetriesResult,
707
- retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
708
- };
709
- }
710
-
711
- // core/util/index.ts
712
- var import_provider_utils5 = require("@ai-sdk/provider-utils");
713
-
714
- // core/util/is-non-empty-object.ts
606
+ // src/util/is-non-empty-object.ts
715
607
  function isNonEmptyObject(object) {
716
608
  return object != null && Object.keys(object).length > 0;
717
609
  }
@@ -729,24 +621,24 @@ function prepareToolsAndToolChoice({
729
621
  };
730
622
  }
731
623
  const filteredTools = activeTools != null ? Object.entries(tools).filter(
732
- ([name6]) => activeTools.includes(name6)
624
+ ([name5]) => activeTools.includes(name5)
733
625
  ) : Object.entries(tools);
734
626
  return {
735
- tools: filteredTools.map(([name6, tool]) => {
627
+ tools: filteredTools.map(([name5, tool]) => {
736
628
  const toolType = tool.type;
737
629
  switch (toolType) {
738
630
  case void 0:
739
631
  case "function":
740
632
  return {
741
633
  type: "function",
742
- name: name6,
634
+ name: name5,
743
635
  description: tool.description,
744
- parameters: (0, import_provider_utils5.asSchema)(tool.parameters).jsonSchema
636
+ parameters: (0, import_provider_utils4.asSchema)(tool.parameters).jsonSchema
745
637
  };
746
638
  case "provider-defined":
747
639
  return {
748
640
  type: "provider-defined",
749
- name: name6,
641
+ name: name5,
750
642
  id: tool.id,
751
643
  args: tool.args
752
644
  };
@@ -761,227 +653,10 @@ function prepareToolsAndToolChoice({
761
653
  }
762
654
 
763
655
  // core/prompt/standardize-prompt.ts
764
- var import_provider8 = require("@ai-sdk/provider");
765
- var import_provider_utils6 = require("@ai-sdk/provider-utils");
656
+ var import_provider5 = require("@ai-sdk/provider");
657
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
766
658
  var import_zod7 = require("zod");
767
659
 
768
- // core/ui/get-ui-text.ts
769
- function getUIText(parts) {
770
- return parts.map((part) => part.type === "text" ? part.text : "").join("");
771
- }
772
-
773
- // core/prompt/message-conversion-error.ts
774
- var import_provider7 = require("@ai-sdk/provider");
775
- var name5 = "AI_MessageConversionError";
776
- var marker5 = `vercel.ai.error.${name5}`;
777
- var symbol5 = Symbol.for(marker5);
778
- var _a5;
779
- var MessageConversionError = class extends import_provider7.AISDKError {
780
- constructor({
781
- originalMessage,
782
- message
783
- }) {
784
- super({ name: name5, message });
785
- this[_a5] = true;
786
- this.originalMessage = originalMessage;
787
- }
788
- static isInstance(error) {
789
- return import_provider7.AISDKError.hasMarker(error, marker5);
790
- }
791
- };
792
- _a5 = symbol5;
793
-
794
- // core/prompt/convert-to-model-messages.ts
795
- function convertToModelMessages(messages, options) {
796
- var _a6, _b;
797
- const tools = (_a6 = options == null ? void 0 : options.tools) != null ? _a6 : {};
798
- const modelMessages = [];
799
- for (const message of messages) {
800
- switch (message.role) {
801
- case "system": {
802
- modelMessages.push({
803
- role: "system",
804
- content: getUIText(message.parts)
805
- });
806
- break;
807
- }
808
- case "user": {
809
- modelMessages.push({
810
- role: "user",
811
- content: message.parts.filter(
812
- (part) => part.type === "text" || part.type === "file"
813
- ).map(
814
- (part) => part.type === "file" ? {
815
- type: "file",
816
- mediaType: part.mediaType,
817
- filename: part.filename,
818
- data: part.url
819
- } : part
820
- )
821
- });
822
- break;
823
- }
824
- case "assistant": {
825
- if (message.parts != null) {
826
- let processBlock2 = function() {
827
- const content = [];
828
- for (const part of block) {
829
- switch (part.type) {
830
- case "text": {
831
- content.push(part);
832
- break;
833
- }
834
- case "file": {
835
- content.push({
836
- type: "file",
837
- mediaType: part.mediaType,
838
- data: part.url
839
- });
840
- break;
841
- }
842
- case "reasoning": {
843
- content.push({
844
- type: "reasoning",
845
- text: part.text,
846
- providerOptions: part.providerMetadata
847
- });
848
- break;
849
- }
850
- case "tool-invocation":
851
- content.push({
852
- type: "tool-call",
853
- toolCallId: part.toolInvocation.toolCallId,
854
- toolName: part.toolInvocation.toolName,
855
- args: part.toolInvocation.args
856
- });
857
- break;
858
- default: {
859
- const _exhaustiveCheck = part;
860
- throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
861
- }
862
- }
863
- }
864
- modelMessages.push({
865
- role: "assistant",
866
- content
867
- });
868
- const stepInvocations = block.filter(
869
- (part) => part.type === "tool-invocation"
870
- ).map((part) => part.toolInvocation);
871
- if (stepInvocations.length > 0) {
872
- modelMessages.push({
873
- role: "tool",
874
- content: stepInvocations.map(
875
- (toolInvocation) => {
876
- if (!("result" in toolInvocation)) {
877
- throw new MessageConversionError({
878
- originalMessage: message,
879
- message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
880
- });
881
- }
882
- const { toolCallId, toolName, result } = toolInvocation;
883
- const tool = tools[toolName];
884
- return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
885
- type: "tool-result",
886
- toolCallId,
887
- toolName,
888
- result: tool.experimental_toToolResultContent(result),
889
- experimental_content: tool.experimental_toToolResultContent(result)
890
- } : {
891
- type: "tool-result",
892
- toolCallId,
893
- toolName,
894
- result
895
- };
896
- }
897
- )
898
- });
899
- }
900
- block = [];
901
- blockHasToolInvocations = false;
902
- currentStep++;
903
- };
904
- var processBlock = processBlock2;
905
- let currentStep = 0;
906
- let blockHasToolInvocations = false;
907
- let block = [];
908
- for (const part of message.parts) {
909
- switch (part.type) {
910
- case "text": {
911
- if (blockHasToolInvocations) {
912
- processBlock2();
913
- }
914
- block.push(part);
915
- break;
916
- }
917
- case "file":
918
- case "reasoning": {
919
- block.push(part);
920
- break;
921
- }
922
- case "tool-invocation": {
923
- if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
924
- processBlock2();
925
- }
926
- block.push(part);
927
- blockHasToolInvocations = true;
928
- break;
929
- }
930
- }
931
- }
932
- processBlock2();
933
- break;
934
- }
935
- break;
936
- }
937
- default: {
938
- const _exhaustiveCheck = message.role;
939
- throw new MessageConversionError({
940
- originalMessage: message,
941
- message: `Unsupported role: ${_exhaustiveCheck}`
942
- });
943
- }
944
- }
945
- }
946
- return modelMessages;
947
- }
948
-
949
- // core/prompt/detect-prompt-type.ts
950
- function detectPromptType(prompt) {
951
- if (!Array.isArray(prompt)) {
952
- return "other";
953
- }
954
- if (prompt.length === 0) {
955
- return "model-messages";
956
- }
957
- const characteristics = prompt.map(detectSingleMessageCharacteristics);
958
- if (characteristics.some((c) => c === "has-ui-specific-parts")) {
959
- return "ui-messages";
960
- } else if (characteristics.every(
961
- (c) => c === "has-core-specific-parts" || c === "message"
962
- )) {
963
- return "model-messages";
964
- } else {
965
- return "other";
966
- }
967
- }
968
- function detectSingleMessageCharacteristics(message) {
969
- if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
970
- message.role === "data" || // UI-only role
971
- "toolInvocations" in message || // UI-specific field
972
- "parts" in message || // UI-specific field
973
- "experimental_attachments" in message)) {
974
- return "has-ui-specific-parts";
975
- } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
976
- "providerOptions" in message)) {
977
- return "has-core-specific-parts";
978
- } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
979
- return "message";
980
- } else {
981
- return "other";
982
- }
983
- }
984
-
985
660
  // core/prompt/message.ts
986
661
  var import_zod6 = require("zod");
987
662
 
@@ -1108,113 +783,172 @@ var modelMessageSchema = import_zod6.z.union([
1108
783
  ]);
1109
784
 
1110
785
  // core/prompt/standardize-prompt.ts
1111
- async function standardizePrompt({
1112
- prompt,
1113
- tools
1114
- }) {
786
+ async function standardizePrompt(prompt) {
1115
787
  if (prompt.prompt == null && prompt.messages == null) {
1116
- throw new import_provider8.InvalidPromptError({
788
+ throw new import_provider5.InvalidPromptError({
1117
789
  prompt,
1118
790
  message: "prompt or messages must be defined"
1119
791
  });
1120
792
  }
1121
793
  if (prompt.prompt != null && prompt.messages != null) {
1122
- throw new import_provider8.InvalidPromptError({
794
+ throw new import_provider5.InvalidPromptError({
1123
795
  prompt,
1124
796
  message: "prompt and messages cannot be defined at the same time"
1125
797
  });
1126
798
  }
1127
799
  if (prompt.system != null && typeof prompt.system !== "string") {
1128
- throw new import_provider8.InvalidPromptError({
800
+ throw new import_provider5.InvalidPromptError({
1129
801
  prompt,
1130
802
  message: "system must be a string"
1131
803
  });
1132
804
  }
1133
- if (prompt.prompt != null) {
1134
- if (typeof prompt.prompt !== "string") {
1135
- throw new import_provider8.InvalidPromptError({
1136
- prompt,
1137
- message: "prompt must be a string"
1138
- });
1139
- }
1140
- return {
1141
- system: prompt.system,
1142
- messages: [
1143
- {
1144
- role: "user",
1145
- content: prompt.prompt
1146
- }
1147
- ]
1148
- };
805
+ let messages;
806
+ if (prompt.prompt != null && typeof prompt.prompt === "string") {
807
+ messages = [{ role: "user", content: prompt.prompt }];
808
+ } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {
809
+ messages = prompt.prompt;
810
+ } else if (prompt.messages != null) {
811
+ messages = prompt.messages;
812
+ } else {
813
+ throw new import_provider5.InvalidPromptError({
814
+ prompt,
815
+ message: "prompt or messages must be defined"
816
+ });
1149
817
  }
1150
- if (prompt.messages != null) {
1151
- const promptType = detectPromptType(prompt.messages);
1152
- if (promptType === "other") {
1153
- throw new import_provider8.InvalidPromptError({
1154
- prompt,
1155
- message: "messages must be an array of ModelMessage or UIMessage"
1156
- });
818
+ if (messages.length === 0) {
819
+ throw new import_provider5.InvalidPromptError({
820
+ prompt,
821
+ message: "messages must not be empty"
822
+ });
823
+ }
824
+ const validationResult = await (0, import_provider_utils5.safeValidateTypes)({
825
+ value: messages,
826
+ schema: import_zod7.z.array(modelMessageSchema)
827
+ });
828
+ if (!validationResult.success) {
829
+ throw new import_provider5.InvalidPromptError({
830
+ prompt,
831
+ message: "messages must be an array of ModelMessage",
832
+ cause: validationResult.error
833
+ });
834
+ }
835
+ return {
836
+ messages,
837
+ system: prompt.system
838
+ };
839
+ }
840
+
841
+ // src/util/retry-with-exponential-backoff.ts
842
+ var import_provider7 = require("@ai-sdk/provider");
843
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
844
+
845
+ // src/util/retry-error.ts
846
+ var import_provider6 = require("@ai-sdk/provider");
847
+ var name4 = "AI_RetryError";
848
+ var marker4 = `vercel.ai.error.${name4}`;
849
+ var symbol4 = Symbol.for(marker4);
850
+ var _a4;
851
+ var RetryError = class extends import_provider6.AISDKError {
852
+ constructor({
853
+ message,
854
+ reason,
855
+ errors
856
+ }) {
857
+ super({ name: name4, message });
858
+ this[_a4] = true;
859
+ this.reason = reason;
860
+ this.errors = errors;
861
+ this.lastError = errors[errors.length - 1];
862
+ }
863
+ static isInstance(error) {
864
+ return import_provider6.AISDKError.hasMarker(error, marker4);
865
+ }
866
+ };
867
+ _a4 = symbol4;
868
+
869
+ // src/util/retry-with-exponential-backoff.ts
870
+ var retryWithExponentialBackoff = ({
871
+ maxRetries = 2,
872
+ initialDelayInMs = 2e3,
873
+ backoffFactor = 2
874
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
875
+ maxRetries,
876
+ delayInMs: initialDelayInMs,
877
+ backoffFactor
878
+ });
879
+ async function _retryWithExponentialBackoff(f, {
880
+ maxRetries,
881
+ delayInMs,
882
+ backoffFactor
883
+ }, errors = []) {
884
+ try {
885
+ return await f();
886
+ } catch (error) {
887
+ if ((0, import_provider_utils6.isAbortError)(error)) {
888
+ throw error;
1157
889
  }
1158
- const messages = promptType === "ui-messages" ? convertToModelMessages(prompt.messages, {
1159
- tools
1160
- }) : prompt.messages;
1161
- if (messages.length === 0) {
1162
- throw new import_provider8.InvalidPromptError({
1163
- prompt,
1164
- message: "messages must not be empty"
1165
- });
890
+ if (maxRetries === 0) {
891
+ throw error;
1166
892
  }
1167
- const validationResult = await (0, import_provider_utils6.safeValidateTypes)({
1168
- value: messages,
1169
- schema: import_zod7.z.array(modelMessageSchema)
1170
- });
1171
- if (!validationResult.success) {
1172
- throw new import_provider8.InvalidPromptError({
1173
- prompt,
1174
- message: "messages must be an array of ModelMessage or UIMessage",
1175
- cause: validationResult.error
893
+ const errorMessage = (0, import_provider_utils6.getErrorMessage)(error);
894
+ const newErrors = [...errors, error];
895
+ const tryNumber = newErrors.length;
896
+ if (tryNumber > maxRetries) {
897
+ throw new RetryError({
898
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
899
+ reason: "maxRetriesExceeded",
900
+ errors: newErrors
1176
901
  });
1177
902
  }
1178
- return {
1179
- messages,
1180
- system: prompt.system
1181
- };
903
+ if (error instanceof Error && import_provider7.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
904
+ await (0, import_provider_utils6.delay)(delayInMs);
905
+ return _retryWithExponentialBackoff(
906
+ f,
907
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
908
+ newErrors
909
+ );
910
+ }
911
+ if (tryNumber === 1) {
912
+ throw error;
913
+ }
914
+ throw new RetryError({
915
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
916
+ reason: "errorNotRetryable",
917
+ errors: newErrors
918
+ });
1182
919
  }
1183
- throw new Error("unreachable");
1184
920
  }
1185
921
 
1186
- // streams/stream-callbacks.ts
1187
- function createCallbacksTransformer(callbacks = {}) {
1188
- let aggregatedResponse = "";
1189
- return new TransformStream({
1190
- async start() {
1191
- if (callbacks.onStart)
1192
- await callbacks.onStart();
1193
- },
1194
- async transform(message, controller) {
1195
- controller.enqueue(message);
1196
- aggregatedResponse += message;
1197
- if (callbacks.onToken)
1198
- await callbacks.onToken(message);
1199
- if (callbacks.onText && typeof message === "string") {
1200
- await callbacks.onText(message);
1201
- }
1202
- },
1203
- async flush() {
1204
- if (callbacks.onFinal) {
1205
- await callbacks.onFinal(aggregatedResponse);
1206
- }
922
+ // src/util/prepare-retries.ts
923
+ function prepareRetries({
924
+ maxRetries
925
+ }) {
926
+ if (maxRetries != null) {
927
+ if (!Number.isInteger(maxRetries)) {
928
+ throw new InvalidArgumentError({
929
+ parameter: "maxRetries",
930
+ value: maxRetries,
931
+ message: "maxRetries must be an integer"
932
+ });
1207
933
  }
1208
- });
934
+ if (maxRetries < 0) {
935
+ throw new InvalidArgumentError({
936
+ parameter: "maxRetries",
937
+ value: maxRetries,
938
+ message: "maxRetries must be >= 0"
939
+ });
940
+ }
941
+ }
942
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
943
+ return {
944
+ maxRetries: maxRetriesResult,
945
+ retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
946
+ };
1209
947
  }
1210
-
1211
- // util/constants.ts
1212
- var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
1213
948
  // Annotate the CommonJS export names for ESM import in node:
1214
949
  0 && (module.exports = {
1215
- HANGING_STREAM_WARNING_TIME_MS,
950
+ convertAsyncIteratorToReadableStream,
1216
951
  convertToLanguageModelPrompt,
1217
- createCallbacksTransformer,
1218
952
  prepareCallSettings,
1219
953
  prepareRetries,
1220
954
  prepareToolsAndToolChoice,