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.
@@ -1,58 +1,10 @@
1
+ // internal/index.ts
2
+ import { convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
+
1
4
  // core/prompt/convert-to-language-model-prompt.ts
2
5
  import { isUrlSupported } from "@ai-sdk/provider-utils";
3
6
 
4
- // util/download-error.ts
5
- import { AISDKError } from "@ai-sdk/provider";
6
- var name = "AI_DownloadError";
7
- var marker = `vercel.ai.error.${name}`;
8
- var symbol = Symbol.for(marker);
9
- var _a;
10
- var DownloadError = class extends AISDKError {
11
- constructor({
12
- url,
13
- statusCode,
14
- statusText,
15
- cause,
16
- message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
17
- }) {
18
- super({ name, message, cause });
19
- this[_a] = true;
20
- this.url = url;
21
- this.statusCode = statusCode;
22
- this.statusText = statusText;
23
- }
24
- static isInstance(error) {
25
- return AISDKError.hasMarker(error, marker);
26
- }
27
- };
28
- _a = symbol;
29
-
30
- // util/download.ts
31
- async function download({ url }) {
32
- var _a6;
33
- const urlText = url.toString();
34
- try {
35
- const response = await fetch(urlText);
36
- if (!response.ok) {
37
- throw new DownloadError({
38
- url: urlText,
39
- statusCode: response.status,
40
- statusText: response.statusText
41
- });
42
- }
43
- return {
44
- data: new Uint8Array(await response.arrayBuffer()),
45
- mediaType: (_a6 = response.headers.get("content-type")) != null ? _a6 : void 0
46
- };
47
- } catch (error) {
48
- if (DownloadError.isInstance(error)) {
49
- throw error;
50
- }
51
- throw new DownloadError({ url: urlText, cause: error });
52
- }
53
- }
54
-
55
- // core/util/detect-media-type.ts
7
+ // src/util/detect-media-type.ts
56
8
  import { convertBase64ToUint8Array } from "@ai-sdk/provider-utils";
57
9
  var imageMediaTypeSignatures = [
58
10
  {
@@ -153,6 +105,57 @@ function detectMediaType({
153
105
  return void 0;
154
106
  }
155
107
 
108
+ // src/util/download-error.ts
109
+ import { AISDKError } from "@ai-sdk/provider";
110
+ var name = "AI_DownloadError";
111
+ var marker = `vercel.ai.error.${name}`;
112
+ var symbol = Symbol.for(marker);
113
+ var _a;
114
+ var DownloadError = class extends AISDKError {
115
+ constructor({
116
+ url,
117
+ statusCode,
118
+ statusText,
119
+ cause,
120
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
121
+ }) {
122
+ super({ name, message, cause });
123
+ this[_a] = true;
124
+ this.url = url;
125
+ this.statusCode = statusCode;
126
+ this.statusText = statusText;
127
+ }
128
+ static isInstance(error) {
129
+ return AISDKError.hasMarker(error, marker);
130
+ }
131
+ };
132
+ _a = symbol;
133
+
134
+ // src/util/download.ts
135
+ async function download({ url }) {
136
+ var _a5;
137
+ const urlText = url.toString();
138
+ try {
139
+ const response = await fetch(urlText);
140
+ if (!response.ok) {
141
+ throw new DownloadError({
142
+ url: urlText,
143
+ statusCode: response.status,
144
+ statusText: response.statusText
145
+ });
146
+ }
147
+ return {
148
+ data: new Uint8Array(await response.arrayBuffer()),
149
+ mediaType: (_a5 = response.headers.get("content-type")) != null ? _a5 : void 0
150
+ };
151
+ } catch (error) {
152
+ if (DownloadError.isInstance(error)) {
153
+ throw error;
154
+ }
155
+ throw new DownloadError({ url: urlText, cause: error });
156
+ }
157
+ }
158
+
156
159
  // core/prompt/data-content.ts
157
160
  import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
158
161
  import {
@@ -185,8 +188,8 @@ var dataContentSchema = z.union([
185
188
  z.custom(
186
189
  // Buffer might not be available in some environments such as CloudFlare:
187
190
  (value) => {
188
- var _a6, _b;
189
- return (_b = (_a6 = globalThis.Buffer) == null ? void 0 : _a6.isBuffer(value)) != null ? _b : false;
191
+ var _a5, _b;
192
+ return (_b = (_a5 = globalThis.Buffer) == null ? void 0 : _a5.isBuffer(value)) != null ? _b : false;
190
193
  },
191
194
  { message: "Must be a Buffer" }
192
195
  )
@@ -365,8 +368,8 @@ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
365
368
  ).flat().filter(
366
369
  (part) => part.type === "image" || part.type === "file"
367
370
  ).map((part) => {
368
- var _a6;
369
- const mediaType = (_a6 = part.mediaType) != null ? _a6 : part.type === "image" ? "image/*" : void 0;
371
+ var _a5;
372
+ const mediaType = (_a5 = part.mediaType) != null ? _a5 : part.type === "image" ? "image/*" : void 0;
370
373
  let data = part.type === "image" ? part.image : part.data;
371
374
  if (typeof data === "string") {
372
375
  try {
@@ -393,7 +396,7 @@ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
393
396
  );
394
397
  }
395
398
  function convertPartToLanguageModelPart(part, downloadedAssets) {
396
- var _a6, _b;
399
+ var _a5, _b;
397
400
  if (part.type === "text") {
398
401
  return {
399
402
  type: "text",
@@ -420,7 +423,7 @@ function convertPartToLanguageModelPart(part, downloadedAssets) {
420
423
  const downloadedFile = downloadedAssets[data.toString()];
421
424
  if (downloadedFile) {
422
425
  data = downloadedFile.data;
423
- mediaType = (_a6 = downloadedFile.mediaType) != null ? _a6 : mediaType;
426
+ mediaType = (_a5 = downloadedFile.mediaType) != null ? _a5 : mediaType;
424
427
  }
425
428
  }
426
429
  switch (type) {
@@ -452,7 +455,7 @@ function convertPartToLanguageModelPart(part, downloadedAssets) {
452
455
  }
453
456
  }
454
457
 
455
- // errors/invalid-argument-error.ts
458
+ // src/error/invalid-argument-error.ts
456
459
  import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
457
460
  var name3 = "AI_InvalidArgumentError";
458
461
  var marker3 = `vercel.ai.error.${name3}`;
@@ -571,122 +574,10 @@ function prepareCallSettings({
571
574
  };
572
575
  }
573
576
 
574
- // util/retry-with-exponential-backoff.ts
575
- import { APICallError } from "@ai-sdk/provider";
576
- import { delay, getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
577
-
578
- // util/retry-error.ts
579
- import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
580
- var name4 = "AI_RetryError";
581
- var marker4 = `vercel.ai.error.${name4}`;
582
- var symbol4 = Symbol.for(marker4);
583
- var _a4;
584
- var RetryError = class extends AISDKError5 {
585
- constructor({
586
- message,
587
- reason,
588
- errors
589
- }) {
590
- super({ name: name4, message });
591
- this[_a4] = true;
592
- this.reason = reason;
593
- this.errors = errors;
594
- this.lastError = errors[errors.length - 1];
595
- }
596
- static isInstance(error) {
597
- return AISDKError5.hasMarker(error, marker4);
598
- }
599
- };
600
- _a4 = symbol4;
601
-
602
- // util/retry-with-exponential-backoff.ts
603
- var retryWithExponentialBackoff = ({
604
- maxRetries = 2,
605
- initialDelayInMs = 2e3,
606
- backoffFactor = 2
607
- } = {}) => async (f) => _retryWithExponentialBackoff(f, {
608
- maxRetries,
609
- delayInMs: initialDelayInMs,
610
- backoffFactor
611
- });
612
- async function _retryWithExponentialBackoff(f, {
613
- maxRetries,
614
- delayInMs,
615
- backoffFactor
616
- }, errors = []) {
617
- try {
618
- return await f();
619
- } catch (error) {
620
- if (isAbortError(error)) {
621
- throw error;
622
- }
623
- if (maxRetries === 0) {
624
- throw error;
625
- }
626
- const errorMessage = getErrorMessage(error);
627
- const newErrors = [...errors, error];
628
- const tryNumber = newErrors.length;
629
- if (tryNumber > maxRetries) {
630
- throw new RetryError({
631
- message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
632
- reason: "maxRetriesExceeded",
633
- errors: newErrors
634
- });
635
- }
636
- if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
637
- await delay(delayInMs);
638
- return _retryWithExponentialBackoff(
639
- f,
640
- { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
641
- newErrors
642
- );
643
- }
644
- if (tryNumber === 1) {
645
- throw error;
646
- }
647
- throw new RetryError({
648
- message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
649
- reason: "errorNotRetryable",
650
- errors: newErrors
651
- });
652
- }
653
- }
654
-
655
- // core/prompt/prepare-retries.ts
656
- function prepareRetries({
657
- maxRetries
658
- }) {
659
- if (maxRetries != null) {
660
- if (!Number.isInteger(maxRetries)) {
661
- throw new InvalidArgumentError({
662
- parameter: "maxRetries",
663
- value: maxRetries,
664
- message: "maxRetries must be an integer"
665
- });
666
- }
667
- if (maxRetries < 0) {
668
- throw new InvalidArgumentError({
669
- parameter: "maxRetries",
670
- value: maxRetries,
671
- message: "maxRetries must be >= 0"
672
- });
673
- }
674
- }
675
- const maxRetriesResult = maxRetries != null ? maxRetries : 2;
676
- return {
677
- maxRetries: maxRetriesResult,
678
- retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
679
- };
680
- }
681
-
682
- // core/util/index.ts
683
- import {
684
- asSchema,
685
- generateId,
686
- jsonSchema
687
- } from "@ai-sdk/provider-utils";
577
+ // core/prompt/prepare-tools-and-tool-choice.ts
578
+ import { asSchema } from "@ai-sdk/provider-utils";
688
579
 
689
- // core/util/is-non-empty-object.ts
580
+ // src/util/is-non-empty-object.ts
690
581
  function isNonEmptyObject(object) {
691
582
  return object != null && Object.keys(object).length > 0;
692
583
  }
@@ -704,24 +595,24 @@ function prepareToolsAndToolChoice({
704
595
  };
705
596
  }
706
597
  const filteredTools = activeTools != null ? Object.entries(tools).filter(
707
- ([name6]) => activeTools.includes(name6)
598
+ ([name5]) => activeTools.includes(name5)
708
599
  ) : Object.entries(tools);
709
600
  return {
710
- tools: filteredTools.map(([name6, tool]) => {
601
+ tools: filteredTools.map(([name5, tool]) => {
711
602
  const toolType = tool.type;
712
603
  switch (toolType) {
713
604
  case void 0:
714
605
  case "function":
715
606
  return {
716
607
  type: "function",
717
- name: name6,
608
+ name: name5,
718
609
  description: tool.description,
719
610
  parameters: asSchema(tool.parameters).jsonSchema
720
611
  };
721
612
  case "provider-defined":
722
613
  return {
723
614
  type: "provider-defined",
724
- name: name6,
615
+ name: name5,
725
616
  id: tool.id,
726
617
  args: tool.args
727
618
  };
@@ -740,223 +631,6 @@ import { InvalidPromptError } from "@ai-sdk/provider";
740
631
  import { safeValidateTypes } from "@ai-sdk/provider-utils";
741
632
  import { z as z7 } from "zod";
742
633
 
743
- // core/ui/get-ui-text.ts
744
- function getUIText(parts) {
745
- return parts.map((part) => part.type === "text" ? part.text : "").join("");
746
- }
747
-
748
- // core/prompt/message-conversion-error.ts
749
- import { AISDKError as AISDKError6 } from "@ai-sdk/provider";
750
- var name5 = "AI_MessageConversionError";
751
- var marker5 = `vercel.ai.error.${name5}`;
752
- var symbol5 = Symbol.for(marker5);
753
- var _a5;
754
- var MessageConversionError = class extends AISDKError6 {
755
- constructor({
756
- originalMessage,
757
- message
758
- }) {
759
- super({ name: name5, message });
760
- this[_a5] = true;
761
- this.originalMessage = originalMessage;
762
- }
763
- static isInstance(error) {
764
- return AISDKError6.hasMarker(error, marker5);
765
- }
766
- };
767
- _a5 = symbol5;
768
-
769
- // core/prompt/convert-to-model-messages.ts
770
- function convertToModelMessages(messages, options) {
771
- var _a6, _b;
772
- const tools = (_a6 = options == null ? void 0 : options.tools) != null ? _a6 : {};
773
- const modelMessages = [];
774
- for (const message of messages) {
775
- switch (message.role) {
776
- case "system": {
777
- modelMessages.push({
778
- role: "system",
779
- content: getUIText(message.parts)
780
- });
781
- break;
782
- }
783
- case "user": {
784
- modelMessages.push({
785
- role: "user",
786
- content: message.parts.filter(
787
- (part) => part.type === "text" || part.type === "file"
788
- ).map(
789
- (part) => part.type === "file" ? {
790
- type: "file",
791
- mediaType: part.mediaType,
792
- filename: part.filename,
793
- data: part.url
794
- } : part
795
- )
796
- });
797
- break;
798
- }
799
- case "assistant": {
800
- if (message.parts != null) {
801
- let processBlock2 = function() {
802
- const content = [];
803
- for (const part of block) {
804
- switch (part.type) {
805
- case "text": {
806
- content.push(part);
807
- break;
808
- }
809
- case "file": {
810
- content.push({
811
- type: "file",
812
- mediaType: part.mediaType,
813
- data: part.url
814
- });
815
- break;
816
- }
817
- case "reasoning": {
818
- content.push({
819
- type: "reasoning",
820
- text: part.text,
821
- providerOptions: part.providerMetadata
822
- });
823
- break;
824
- }
825
- case "tool-invocation":
826
- content.push({
827
- type: "tool-call",
828
- toolCallId: part.toolInvocation.toolCallId,
829
- toolName: part.toolInvocation.toolName,
830
- args: part.toolInvocation.args
831
- });
832
- break;
833
- default: {
834
- const _exhaustiveCheck = part;
835
- throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
836
- }
837
- }
838
- }
839
- modelMessages.push({
840
- role: "assistant",
841
- content
842
- });
843
- const stepInvocations = block.filter(
844
- (part) => part.type === "tool-invocation"
845
- ).map((part) => part.toolInvocation);
846
- if (stepInvocations.length > 0) {
847
- modelMessages.push({
848
- role: "tool",
849
- content: stepInvocations.map(
850
- (toolInvocation) => {
851
- if (!("result" in toolInvocation)) {
852
- throw new MessageConversionError({
853
- originalMessage: message,
854
- message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
855
- });
856
- }
857
- const { toolCallId, toolName, result } = toolInvocation;
858
- const tool = tools[toolName];
859
- return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
860
- type: "tool-result",
861
- toolCallId,
862
- toolName,
863
- result: tool.experimental_toToolResultContent(result),
864
- experimental_content: tool.experimental_toToolResultContent(result)
865
- } : {
866
- type: "tool-result",
867
- toolCallId,
868
- toolName,
869
- result
870
- };
871
- }
872
- )
873
- });
874
- }
875
- block = [];
876
- blockHasToolInvocations = false;
877
- currentStep++;
878
- };
879
- var processBlock = processBlock2;
880
- let currentStep = 0;
881
- let blockHasToolInvocations = false;
882
- let block = [];
883
- for (const part of message.parts) {
884
- switch (part.type) {
885
- case "text": {
886
- if (blockHasToolInvocations) {
887
- processBlock2();
888
- }
889
- block.push(part);
890
- break;
891
- }
892
- case "file":
893
- case "reasoning": {
894
- block.push(part);
895
- break;
896
- }
897
- case "tool-invocation": {
898
- if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
899
- processBlock2();
900
- }
901
- block.push(part);
902
- blockHasToolInvocations = true;
903
- break;
904
- }
905
- }
906
- }
907
- processBlock2();
908
- break;
909
- }
910
- break;
911
- }
912
- default: {
913
- const _exhaustiveCheck = message.role;
914
- throw new MessageConversionError({
915
- originalMessage: message,
916
- message: `Unsupported role: ${_exhaustiveCheck}`
917
- });
918
- }
919
- }
920
- }
921
- return modelMessages;
922
- }
923
-
924
- // core/prompt/detect-prompt-type.ts
925
- function detectPromptType(prompt) {
926
- if (!Array.isArray(prompt)) {
927
- return "other";
928
- }
929
- if (prompt.length === 0) {
930
- return "model-messages";
931
- }
932
- const characteristics = prompt.map(detectSingleMessageCharacteristics);
933
- if (characteristics.some((c) => c === "has-ui-specific-parts")) {
934
- return "ui-messages";
935
- } else if (characteristics.every(
936
- (c) => c === "has-core-specific-parts" || c === "message"
937
- )) {
938
- return "model-messages";
939
- } else {
940
- return "other";
941
- }
942
- }
943
- function detectSingleMessageCharacteristics(message) {
944
- if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
945
- message.role === "data" || // UI-only role
946
- "toolInvocations" in message || // UI-specific field
947
- "parts" in message || // UI-specific field
948
- "experimental_attachments" in message)) {
949
- return "has-ui-specific-parts";
950
- } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
951
- "providerOptions" in message)) {
952
- return "has-core-specific-parts";
953
- } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
954
- return "message";
955
- } else {
956
- return "other";
957
- }
958
- }
959
-
960
634
  // core/prompt/message.ts
961
635
  import { z as z6 } from "zod";
962
636
 
@@ -1083,10 +757,7 @@ var modelMessageSchema = z6.union([
1083
757
  ]);
1084
758
 
1085
759
  // core/prompt/standardize-prompt.ts
1086
- async function standardizePrompt({
1087
- prompt,
1088
- tools
1089
- }) {
760
+ async function standardizePrompt(prompt) {
1090
761
  if (prompt.prompt == null && prompt.messages == null) {
1091
762
  throw new InvalidPromptError({
1092
763
  prompt,
@@ -1105,90 +776,152 @@ async function standardizePrompt({
1105
776
  message: "system must be a string"
1106
777
  });
1107
778
  }
1108
- if (prompt.prompt != null) {
1109
- if (typeof prompt.prompt !== "string") {
1110
- throw new InvalidPromptError({
1111
- prompt,
1112
- message: "prompt must be a string"
1113
- });
1114
- }
1115
- return {
1116
- system: prompt.system,
1117
- messages: [
1118
- {
1119
- role: "user",
1120
- content: prompt.prompt
1121
- }
1122
- ]
1123
- };
779
+ let messages;
780
+ if (prompt.prompt != null && typeof prompt.prompt === "string") {
781
+ messages = [{ role: "user", content: prompt.prompt }];
782
+ } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {
783
+ messages = prompt.prompt;
784
+ } else if (prompt.messages != null) {
785
+ messages = prompt.messages;
786
+ } else {
787
+ throw new InvalidPromptError({
788
+ prompt,
789
+ message: "prompt or messages must be defined"
790
+ });
1124
791
  }
1125
- if (prompt.messages != null) {
1126
- const promptType = detectPromptType(prompt.messages);
1127
- if (promptType === "other") {
1128
- throw new InvalidPromptError({
1129
- prompt,
1130
- message: "messages must be an array of ModelMessage or UIMessage"
1131
- });
792
+ if (messages.length === 0) {
793
+ throw new InvalidPromptError({
794
+ prompt,
795
+ message: "messages must not be empty"
796
+ });
797
+ }
798
+ const validationResult = await safeValidateTypes({
799
+ value: messages,
800
+ schema: z7.array(modelMessageSchema)
801
+ });
802
+ if (!validationResult.success) {
803
+ throw new InvalidPromptError({
804
+ prompt,
805
+ message: "messages must be an array of ModelMessage",
806
+ cause: validationResult.error
807
+ });
808
+ }
809
+ return {
810
+ messages,
811
+ system: prompt.system
812
+ };
813
+ }
814
+
815
+ // src/util/retry-with-exponential-backoff.ts
816
+ import { APICallError } from "@ai-sdk/provider";
817
+ import { delay, getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
818
+
819
+ // src/util/retry-error.ts
820
+ import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
821
+ var name4 = "AI_RetryError";
822
+ var marker4 = `vercel.ai.error.${name4}`;
823
+ var symbol4 = Symbol.for(marker4);
824
+ var _a4;
825
+ var RetryError = class extends AISDKError5 {
826
+ constructor({
827
+ message,
828
+ reason,
829
+ errors
830
+ }) {
831
+ super({ name: name4, message });
832
+ this[_a4] = true;
833
+ this.reason = reason;
834
+ this.errors = errors;
835
+ this.lastError = errors[errors.length - 1];
836
+ }
837
+ static isInstance(error) {
838
+ return AISDKError5.hasMarker(error, marker4);
839
+ }
840
+ };
841
+ _a4 = symbol4;
842
+
843
+ // src/util/retry-with-exponential-backoff.ts
844
+ var retryWithExponentialBackoff = ({
845
+ maxRetries = 2,
846
+ initialDelayInMs = 2e3,
847
+ backoffFactor = 2
848
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
849
+ maxRetries,
850
+ delayInMs: initialDelayInMs,
851
+ backoffFactor
852
+ });
853
+ async function _retryWithExponentialBackoff(f, {
854
+ maxRetries,
855
+ delayInMs,
856
+ backoffFactor
857
+ }, errors = []) {
858
+ try {
859
+ return await f();
860
+ } catch (error) {
861
+ if (isAbortError(error)) {
862
+ throw error;
1132
863
  }
1133
- const messages = promptType === "ui-messages" ? convertToModelMessages(prompt.messages, {
1134
- tools
1135
- }) : prompt.messages;
1136
- if (messages.length === 0) {
1137
- throw new InvalidPromptError({
1138
- prompt,
1139
- message: "messages must not be empty"
1140
- });
864
+ if (maxRetries === 0) {
865
+ throw error;
1141
866
  }
1142
- const validationResult = await safeValidateTypes({
1143
- value: messages,
1144
- schema: z7.array(modelMessageSchema)
1145
- });
1146
- if (!validationResult.success) {
1147
- throw new InvalidPromptError({
1148
- prompt,
1149
- message: "messages must be an array of ModelMessage or UIMessage",
1150
- cause: validationResult.error
867
+ const errorMessage = getErrorMessage(error);
868
+ const newErrors = [...errors, error];
869
+ const tryNumber = newErrors.length;
870
+ if (tryNumber > maxRetries) {
871
+ throw new RetryError({
872
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
873
+ reason: "maxRetriesExceeded",
874
+ errors: newErrors
1151
875
  });
1152
876
  }
1153
- return {
1154
- messages,
1155
- system: prompt.system
1156
- };
877
+ if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
878
+ await delay(delayInMs);
879
+ return _retryWithExponentialBackoff(
880
+ f,
881
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
882
+ newErrors
883
+ );
884
+ }
885
+ if (tryNumber === 1) {
886
+ throw error;
887
+ }
888
+ throw new RetryError({
889
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
890
+ reason: "errorNotRetryable",
891
+ errors: newErrors
892
+ });
1157
893
  }
1158
- throw new Error("unreachable");
1159
894
  }
1160
895
 
1161
- // streams/stream-callbacks.ts
1162
- function createCallbacksTransformer(callbacks = {}) {
1163
- let aggregatedResponse = "";
1164
- return new TransformStream({
1165
- async start() {
1166
- if (callbacks.onStart)
1167
- await callbacks.onStart();
1168
- },
1169
- async transform(message, controller) {
1170
- controller.enqueue(message);
1171
- aggregatedResponse += message;
1172
- if (callbacks.onToken)
1173
- await callbacks.onToken(message);
1174
- if (callbacks.onText && typeof message === "string") {
1175
- await callbacks.onText(message);
1176
- }
1177
- },
1178
- async flush() {
1179
- if (callbacks.onFinal) {
1180
- await callbacks.onFinal(aggregatedResponse);
1181
- }
896
+ // src/util/prepare-retries.ts
897
+ function prepareRetries({
898
+ maxRetries
899
+ }) {
900
+ if (maxRetries != null) {
901
+ if (!Number.isInteger(maxRetries)) {
902
+ throw new InvalidArgumentError({
903
+ parameter: "maxRetries",
904
+ value: maxRetries,
905
+ message: "maxRetries must be an integer"
906
+ });
1182
907
  }
1183
- });
908
+ if (maxRetries < 0) {
909
+ throw new InvalidArgumentError({
910
+ parameter: "maxRetries",
911
+ value: maxRetries,
912
+ message: "maxRetries must be >= 0"
913
+ });
914
+ }
915
+ }
916
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
917
+ return {
918
+ maxRetries: maxRetriesResult,
919
+ retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
920
+ };
1184
921
  }
1185
-
1186
- // util/constants.ts
1187
- var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
1188
922
  export {
1189
- HANGING_STREAM_WARNING_TIME_MS,
923
+ convertAsyncIteratorToReadableStream,
1190
924
  convertToLanguageModelPrompt,
1191
- createCallbacksTransformer,
1192
925
  prepareCallSettings,
1193
926
  prepareRetries,
1194
927
  prepareToolsAndToolChoice,