ai 3.0.20 → 3.0.22

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.
Files changed (63) hide show
  1. package/dist/index.d.mts +45 -354
  2. package/dist/index.d.ts +45 -354
  3. package/dist/index.js +161 -460
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +136 -430
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +6 -41
  8. package/react/dist/index.d.mts +1 -1
  9. package/react/dist/index.d.ts +1 -1
  10. package/react/dist/index.js +3 -3
  11. package/react/dist/index.js.map +1 -1
  12. package/react/dist/index.mjs +3 -3
  13. package/react/dist/index.mjs.map +1 -1
  14. package/rsc/dist/rsc-server.mjs +3 -3
  15. package/rsc/dist/rsc-server.mjs.map +1 -1
  16. package/solid/dist/index.d.mts +1 -1
  17. package/solid/dist/index.d.ts +1 -1
  18. package/solid/dist/index.js +3 -3
  19. package/solid/dist/index.js.map +1 -1
  20. package/solid/dist/index.mjs +3 -3
  21. package/solid/dist/index.mjs.map +1 -1
  22. package/svelte/dist/index.d.mts +1 -1
  23. package/svelte/dist/index.d.ts +1 -1
  24. package/svelte/dist/index.js +3 -3
  25. package/svelte/dist/index.js.map +1 -1
  26. package/svelte/dist/index.mjs +3 -3
  27. package/svelte/dist/index.mjs.map +1 -1
  28. package/vue/dist/index.d.mts +1 -1
  29. package/vue/dist/index.d.ts +1 -1
  30. package/vue/dist/index.js +3 -3
  31. package/vue/dist/index.js.map +1 -1
  32. package/vue/dist/index.mjs +3 -3
  33. package/vue/dist/index.mjs.map +1 -1
  34. package/anthropic/dist/index.d.mts +0 -403
  35. package/anthropic/dist/index.d.ts +0 -403
  36. package/anthropic/dist/index.js +0 -950
  37. package/anthropic/dist/index.js.map +0 -1
  38. package/anthropic/dist/index.mjs +0 -914
  39. package/anthropic/dist/index.mjs.map +0 -1
  40. package/google/dist/index.d.mts +0 -399
  41. package/google/dist/index.d.ts +0 -399
  42. package/google/dist/index.js +0 -954
  43. package/google/dist/index.js.map +0 -1
  44. package/google/dist/index.mjs +0 -918
  45. package/google/dist/index.mjs.map +0 -1
  46. package/mistral/dist/index.d.mts +0 -404
  47. package/mistral/dist/index.d.ts +0 -404
  48. package/mistral/dist/index.js +0 -921
  49. package/mistral/dist/index.js.map +0 -1
  50. package/mistral/dist/index.mjs +0 -885
  51. package/mistral/dist/index.mjs.map +0 -1
  52. package/openai/dist/index.d.mts +0 -468
  53. package/openai/dist/index.d.ts +0 -468
  54. package/openai/dist/index.js +0 -1334
  55. package/openai/dist/index.js.map +0 -1
  56. package/openai/dist/index.mjs +0 -1298
  57. package/openai/dist/index.mjs.map +0 -1
  58. package/spec/dist/index.d.mts +0 -780
  59. package/spec/dist/index.d.ts +0 -780
  60. package/spec/dist/index.js +0 -863
  61. package/spec/dist/index.js.map +0 -1
  62. package/spec/dist/index.mjs +0 -797
  63. package/spec/dist/index.mjs.map +0 -1
package/dist/index.js CHANGED
@@ -65,9 +65,12 @@ __export(streams_exports, {
65
65
  experimental_generateText: () => experimental_generateText,
66
66
  experimental_streamObject: () => experimental_streamObject,
67
67
  experimental_streamText: () => experimental_streamText,
68
+ formatStreamPart: () => formatStreamPart,
68
69
  generateId: () => generateId,
69
70
  isStreamStringEqualToType: () => isStreamStringEqualToType,
70
71
  nanoid: () => generateId,
72
+ parseStreamPart: () => parseStreamPart,
73
+ readDataStream: () => readDataStream,
71
74
  readableFromAsyncIterable: () => readableFromAsyncIterable,
72
75
  streamToResponse: () => streamToResponse,
73
76
  tool: () => tool,
@@ -75,352 +78,9 @@ __export(streams_exports, {
75
78
  });
76
79
  module.exports = __toCommonJS(streams_exports);
77
80
 
78
- // spec/errors/api-call-error.ts
79
- var APICallError = class extends Error {
80
- constructor({
81
- message,
82
- url,
83
- requestBodyValues,
84
- statusCode,
85
- responseBody,
86
- cause,
87
- isRetryable = statusCode != null && (statusCode === 408 || // request timeout
88
- statusCode === 409 || // conflict
89
- statusCode === 429 || // too many requests
90
- statusCode >= 500),
91
- // server error
92
- data
93
- }) {
94
- super(message);
95
- this.name = "AI_APICallError";
96
- this.url = url;
97
- this.requestBodyValues = requestBodyValues;
98
- this.statusCode = statusCode;
99
- this.responseBody = responseBody;
100
- this.cause = cause;
101
- this.isRetryable = isRetryable;
102
- this.data = data;
103
- }
104
- static isAPICallError(error) {
105
- return error instanceof Error && error.name === "AI_APICallError" && typeof error.url === "string" && typeof error.requestBodyValues === "object" && (error.statusCode == null || typeof error.statusCode === "number") && (error.responseBody == null || typeof error.responseBody === "string") && (error.cause == null || typeof error.cause === "object") && typeof error.isRetryable === "boolean" && (error.data == null || typeof error.data === "object");
106
- }
107
- toJSON() {
108
- return {
109
- name: this.name,
110
- message: this.message,
111
- url: this.url,
112
- requestBodyValues: this.requestBodyValues,
113
- statusCode: this.statusCode,
114
- responseBody: this.responseBody,
115
- cause: this.cause,
116
- isRetryable: this.isRetryable,
117
- data: this.data
118
- };
119
- }
120
- };
121
-
122
- // spec/errors/invalid-argument-error.ts
123
- var InvalidArgumentError = class extends Error {
124
- constructor({
125
- parameter,
126
- value,
127
- message
128
- }) {
129
- super(`Invalid argument for parameter ${parameter}: ${message}`);
130
- this.name = "AI_InvalidArgumentError";
131
- this.parameter = parameter;
132
- this.value = value;
133
- }
134
- static isInvalidArgumentError(error) {
135
- return error instanceof Error && error.name === "AI_InvalidArgumentError" && typeof error.parameter === "string" && typeof error.value === "string";
136
- }
137
- toJSON() {
138
- return {
139
- name: this.name,
140
- message: this.message,
141
- stack: this.stack,
142
- parameter: this.parameter,
143
- value: this.value
144
- };
145
- }
146
- };
147
-
148
- // spec/errors/invalid-data-content-error.ts
149
- var InvalidDataContentError = class extends Error {
150
- constructor({
151
- content,
152
- message = `Invalid data content. Expected a string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
153
- }) {
154
- super(message);
155
- this.name = "AI_InvalidDataContentError";
156
- this.content = content;
157
- }
158
- static isInvalidDataContentError(error) {
159
- return error instanceof Error && error.name === "AI_InvalidDataContentError" && error.content != null;
160
- }
161
- toJSON() {
162
- return {
163
- name: this.name,
164
- message: this.message,
165
- stack: this.stack,
166
- content: this.content
167
- };
168
- }
169
- };
170
-
171
- // spec/errors/invalid-prompt-error.ts
172
- var InvalidPromptError = class extends Error {
173
- constructor({ prompt: prompt2, message }) {
174
- super(`Invalid prompt: ${message}`);
175
- this.name = "AI_InvalidPromptError";
176
- this.prompt = prompt2;
177
- }
178
- static isInvalidPromptError(error) {
179
- return error instanceof Error && error.name === "AI_InvalidPromptError" && prompt != null;
180
- }
181
- toJSON() {
182
- return {
183
- name: this.name,
184
- message: this.message,
185
- stack: this.stack,
186
- prompt: this.prompt
187
- };
188
- }
189
- };
190
-
191
- // spec/util/get-error-message.ts
192
- function getErrorMessage(error) {
193
- if (error == null) {
194
- return "unknown error";
195
- }
196
- if (typeof error === "string") {
197
- return error;
198
- }
199
- if (error instanceof Error) {
200
- return error.message;
201
- }
202
- return JSON.stringify(error);
203
- }
204
-
205
- // spec/util/parse-json.ts
206
- var import_secure_json_parse = __toESM(require("secure-json-parse"));
207
-
208
- // spec/errors/json-parse-error.ts
209
- var JSONParseError = class extends Error {
210
- constructor({ text, cause }) {
211
- super(
212
- `JSON parsing failed: Text: ${text}.
213
- Error message: ${getErrorMessage(cause)}`
214
- );
215
- this.name = "AI_JSONParseError";
216
- this.cause = cause;
217
- this.text = text;
218
- }
219
- static isJSONParseError(error) {
220
- return error instanceof Error && error.name === "AI_JSONParseError" && typeof error.text === "string" && typeof error.cause === "string";
221
- }
222
- toJSON() {
223
- return {
224
- name: this.name,
225
- message: this.message,
226
- cause: this.cause,
227
- stack: this.stack,
228
- valueText: this.text
229
- };
230
- }
231
- };
232
-
233
- // spec/errors/type-validation-error.ts
234
- var TypeValidationError = class extends Error {
235
- constructor({ value, cause }) {
236
- super(
237
- `Type validation failed: Value: ${JSON.stringify(value)}.
238
- Error message: ${getErrorMessage(cause)}`
239
- );
240
- this.name = "AI_TypeValidationError";
241
- this.cause = cause;
242
- this.value = value;
243
- }
244
- static isTypeValidationError(error) {
245
- return error instanceof Error && error.name === "AI_TypeValidationError" && typeof error.value === "string" && typeof error.cause === "string";
246
- }
247
- toJSON() {
248
- return {
249
- name: this.name,
250
- message: this.message,
251
- cause: this.cause,
252
- stack: this.stack,
253
- value: this.value
254
- };
255
- }
256
- };
257
-
258
- // spec/util/validate-types.ts
259
- function safeValidateTypes({
260
- value,
261
- schema
262
- }) {
263
- try {
264
- const validationResult = schema.safeParse(value);
265
- if (validationResult.success) {
266
- return {
267
- success: true,
268
- value: validationResult.data
269
- };
270
- }
271
- return {
272
- success: false,
273
- error: new TypeValidationError({
274
- value,
275
- cause: validationResult.error
276
- })
277
- };
278
- } catch (error) {
279
- return {
280
- success: false,
281
- error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
282
- };
283
- }
284
- }
285
-
286
- // spec/util/parse-json.ts
287
- function safeParseJSON({
288
- text,
289
- schema
290
- }) {
291
- try {
292
- const value = import_secure_json_parse.default.parse(text);
293
- if (schema == null) {
294
- return {
295
- success: true,
296
- value
297
- };
298
- }
299
- return safeValidateTypes({ value, schema });
300
- } catch (error) {
301
- return {
302
- success: false,
303
- error: JSONParseError.isJSONParseError(error) ? error : new JSONParseError({ text, cause: error })
304
- };
305
- }
306
- }
307
-
308
- // spec/util/uint8-utils.ts
309
- function convertBase64ToUint8Array(base64String) {
310
- const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
311
- const latin1string = globalThis.atob(base64Url);
312
- return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
313
- }
314
- function convertUint8ArrayToBase64(array) {
315
- let latin1string = "";
316
- for (let i = 0; i < array.length; i++) {
317
- latin1string += String.fromCodePoint(array[i]);
318
- }
319
- return globalThis.btoa(latin1string);
320
- }
321
-
322
- // spec/errors/invalid-tool-arguments-error.ts
323
- var InvalidToolArgumentsError = class extends Error {
324
- constructor({
325
- toolArgs,
326
- toolName,
327
- cause,
328
- message = `Invalid arguments for tool ${toolName}: ${getErrorMessage(
329
- cause
330
- )}`
331
- }) {
332
- super(message);
333
- this.name = "AI_InvalidToolArgumentsError";
334
- this.toolArgs = toolArgs;
335
- this.toolName = toolName;
336
- this.cause = cause;
337
- }
338
- static isInvalidToolArgumentsError(error) {
339
- return error instanceof Error && error.name === "AI_InvalidToolArgumentsError" && typeof error.toolName === "string" && typeof error.toolArgs === "string";
340
- }
341
- toJSON() {
342
- return {
343
- name: this.name,
344
- message: this.message,
345
- cause: this.cause,
346
- stack: this.stack,
347
- toolName: this.toolName,
348
- toolArgs: this.toolArgs
349
- };
350
- }
351
- };
352
-
353
- // spec/errors/no-object-generated-error.ts
354
- var NoTextGeneratedError = class extends Error {
355
- constructor() {
356
- super(`No text generated.`);
357
- this.name = "AI_NoTextGeneratedError";
358
- }
359
- static isNoTextGeneratedError(error) {
360
- return error instanceof Error && error.name === "AI_NoTextGeneratedError";
361
- }
362
- toJSON() {
363
- return {
364
- name: this.name,
365
- cause: this.cause,
366
- message: this.message,
367
- stack: this.stack
368
- };
369
- }
370
- };
371
-
372
- // spec/errors/no-such-tool-error.ts
373
- var NoSuchToolError = class extends Error {
374
- constructor({
375
- toolName,
376
- availableTools = void 0,
377
- message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
378
- }) {
379
- super(message);
380
- this.name = "AI_NoSuchToolError";
381
- this.toolName = toolName;
382
- this.availableTools = availableTools;
383
- }
384
- static isNoSuchToolError(error) {
385
- return error instanceof Error && error.name === "AI_NoSuchToolError" && "toolName" in error && error.toolName != void 0 && typeof error.name === "string";
386
- }
387
- toJSON() {
388
- return {
389
- name: this.name,
390
- message: this.message,
391
- stack: this.stack,
392
- toolName: this.toolName,
393
- availableTools: this.availableTools
394
- };
395
- }
396
- };
397
-
398
- // spec/errors/retry-error.ts
399
- var RetryError = class extends Error {
400
- constructor({
401
- message,
402
- reason,
403
- errors
404
- }) {
405
- super(message);
406
- this.name = "AI_RetryError";
407
- this.reason = reason;
408
- this.errors = errors;
409
- this.lastError = errors[errors.length - 1];
410
- }
411
- static isRetryError(error) {
412
- return error instanceof Error && error.name === "AI_RetryError" && typeof error.reason === "string" && Array.isArray(error.errors);
413
- }
414
- toJSON() {
415
- return {
416
- name: this.name,
417
- message: this.message,
418
- reason: this.reason,
419
- lastError: this.lastError,
420
- errors: this.errors
421
- };
422
- }
423
- };
81
+ // core/generate-object/generate-object.ts
82
+ var import_provider5 = require("@ai-sdk/provider");
83
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
424
84
 
425
85
  // core/generate-text/token-usage.ts
426
86
  function calculateTokenUsage(usage) {
@@ -448,45 +108,47 @@ function detectImageMimeType(image) {
448
108
  }
449
109
 
450
110
  // core/prompt/data-content.ts
111
+ var import_provider = require("@ai-sdk/provider");
112
+ var import_provider_utils = require("@ai-sdk/provider-utils");
451
113
  function convertDataContentToBase64String(content) {
452
114
  if (typeof content === "string") {
453
115
  return content;
454
116
  }
455
117
  if (content instanceof ArrayBuffer) {
456
- return convertUint8ArrayToBase64(new Uint8Array(content));
118
+ return (0, import_provider_utils.convertUint8ArrayToBase64)(new Uint8Array(content));
457
119
  }
458
- return convertUint8ArrayToBase64(content);
120
+ return (0, import_provider_utils.convertUint8ArrayToBase64)(content);
459
121
  }
460
122
  function convertDataContentToUint8Array(content) {
461
123
  if (content instanceof Uint8Array) {
462
124
  return content;
463
125
  }
464
126
  if (typeof content === "string") {
465
- return convertBase64ToUint8Array(content);
127
+ return (0, import_provider_utils.convertBase64ToUint8Array)(content);
466
128
  }
467
129
  if (content instanceof ArrayBuffer) {
468
130
  return new Uint8Array(content);
469
131
  }
470
- throw new InvalidDataContentError({ content });
132
+ throw new import_provider.InvalidDataContentError({ content });
471
133
  }
472
134
 
473
135
  // core/prompt/convert-to-language-model-prompt.ts
474
- function convertToLanguageModelPrompt(prompt2) {
136
+ function convertToLanguageModelPrompt(prompt) {
475
137
  const languageModelMessages = [];
476
- if (prompt2.system != null) {
477
- languageModelMessages.push({ role: "system", content: prompt2.system });
138
+ if (prompt.system != null) {
139
+ languageModelMessages.push({ role: "system", content: prompt.system });
478
140
  }
479
- switch (prompt2.type) {
141
+ switch (prompt.type) {
480
142
  case "prompt": {
481
143
  languageModelMessages.push({
482
144
  role: "user",
483
- content: [{ type: "text", text: prompt2.prompt }]
145
+ content: [{ type: "text", text: prompt.prompt }]
484
146
  });
485
147
  break;
486
148
  }
487
149
  case "messages": {
488
150
  languageModelMessages.push(
489
- ...prompt2.messages.map((message) => {
151
+ ...prompt.messages.map((message) => {
490
152
  switch (message.role) {
491
153
  case "user": {
492
154
  if (typeof message.content === "string") {
@@ -544,7 +206,7 @@ function convertToLanguageModelPrompt(prompt2) {
544
206
  break;
545
207
  }
546
208
  default: {
547
- const _exhaustiveCheck = prompt2;
209
+ const _exhaustiveCheck = prompt;
548
210
  throw new Error(`Unsupported prompt type: ${_exhaustiveCheck}`);
549
211
  }
550
212
  }
@@ -552,34 +214,36 @@ function convertToLanguageModelPrompt(prompt2) {
552
214
  }
553
215
 
554
216
  // core/prompt/get-validated-prompt.ts
555
- function getValidatedPrompt(prompt2) {
556
- if (prompt2.prompt == null && prompt2.messages == null) {
557
- throw new InvalidPromptError({
558
- prompt: prompt2,
217
+ var import_provider2 = require("@ai-sdk/provider");
218
+ function getValidatedPrompt(prompt) {
219
+ if (prompt.prompt == null && prompt.messages == null) {
220
+ throw new import_provider2.InvalidPromptError({
221
+ prompt,
559
222
  message: "prompt or messages must be defined"
560
223
  });
561
224
  }
562
- if (prompt2.prompt != null && prompt2.messages != null) {
563
- throw new InvalidPromptError({
564
- prompt: prompt2,
225
+ if (prompt.prompt != null && prompt.messages != null) {
226
+ throw new import_provider2.InvalidPromptError({
227
+ prompt,
565
228
  message: "prompt and messages cannot be defined at the same time"
566
229
  });
567
230
  }
568
- return prompt2.prompt != null ? {
231
+ return prompt.prompt != null ? {
569
232
  type: "prompt",
570
- prompt: prompt2.prompt,
233
+ prompt: prompt.prompt,
571
234
  messages: void 0,
572
- system: prompt2.system
235
+ system: prompt.system
573
236
  } : {
574
237
  type: "messages",
575
238
  prompt: void 0,
576
- messages: prompt2.messages,
239
+ messages: prompt.messages,
577
240
  // only possible case bc of checks above
578
- system: prompt2.system
241
+ system: prompt.system
579
242
  };
580
243
  }
581
244
 
582
245
  // core/prompt/prepare-call-settings.ts
246
+ var import_provider3 = require("@ai-sdk/provider");
583
247
  function prepareCallSettings({
584
248
  maxTokens,
585
249
  temperature,
@@ -591,14 +255,14 @@ function prepareCallSettings({
591
255
  }) {
592
256
  if (maxTokens != null) {
593
257
  if (!Number.isInteger(maxTokens)) {
594
- throw new InvalidArgumentError({
258
+ throw new import_provider3.InvalidArgumentError({
595
259
  parameter: "maxTokens",
596
260
  value: maxTokens,
597
261
  message: "maxTokens must be an integer"
598
262
  });
599
263
  }
600
264
  if (maxTokens < 1) {
601
- throw new InvalidArgumentError({
265
+ throw new import_provider3.InvalidArgumentError({
602
266
  parameter: "maxTokens",
603
267
  value: maxTokens,
604
268
  message: "maxTokens must be >= 1"
@@ -607,14 +271,14 @@ function prepareCallSettings({
607
271
  }
608
272
  if (temperature != null) {
609
273
  if (typeof temperature !== "number") {
610
- throw new InvalidArgumentError({
274
+ throw new import_provider3.InvalidArgumentError({
611
275
  parameter: "temperature",
612
276
  value: temperature,
613
277
  message: "temperature must be a number"
614
278
  });
615
279
  }
616
280
  if (temperature < 0 || temperature > 1) {
617
- throw new InvalidArgumentError({
281
+ throw new import_provider3.InvalidArgumentError({
618
282
  parameter: "temperature",
619
283
  value: temperature,
620
284
  message: "temperature must be between 0 and 1 (inclusive)"
@@ -623,14 +287,14 @@ function prepareCallSettings({
623
287
  }
624
288
  if (topP != null) {
625
289
  if (typeof topP !== "number") {
626
- throw new InvalidArgumentError({
290
+ throw new import_provider3.InvalidArgumentError({
627
291
  parameter: "topP",
628
292
  value: topP,
629
293
  message: "topP must be a number"
630
294
  });
631
295
  }
632
296
  if (topP < 0 || topP > 1) {
633
- throw new InvalidArgumentError({
297
+ throw new import_provider3.InvalidArgumentError({
634
298
  parameter: "topP",
635
299
  value: topP,
636
300
  message: "topP must be between 0 and 1 (inclusive)"
@@ -639,14 +303,14 @@ function prepareCallSettings({
639
303
  }
640
304
  if (presencePenalty != null) {
641
305
  if (typeof presencePenalty !== "number") {
642
- throw new InvalidArgumentError({
306
+ throw new import_provider3.InvalidArgumentError({
643
307
  parameter: "presencePenalty",
644
308
  value: presencePenalty,
645
309
  message: "presencePenalty must be a number"
646
310
  });
647
311
  }
648
312
  if (presencePenalty < -1 || presencePenalty > 1) {
649
- throw new InvalidArgumentError({
313
+ throw new import_provider3.InvalidArgumentError({
650
314
  parameter: "presencePenalty",
651
315
  value: presencePenalty,
652
316
  message: "presencePenalty must be between -1 and 1 (inclusive)"
@@ -655,14 +319,14 @@ function prepareCallSettings({
655
319
  }
656
320
  if (frequencyPenalty != null) {
657
321
  if (typeof frequencyPenalty !== "number") {
658
- throw new InvalidArgumentError({
322
+ throw new import_provider3.InvalidArgumentError({
659
323
  parameter: "frequencyPenalty",
660
324
  value: frequencyPenalty,
661
325
  message: "frequencyPenalty must be a number"
662
326
  });
663
327
  }
664
328
  if (frequencyPenalty < -1 || frequencyPenalty > 1) {
665
- throw new InvalidArgumentError({
329
+ throw new import_provider3.InvalidArgumentError({
666
330
  parameter: "frequencyPenalty",
667
331
  value: frequencyPenalty,
668
332
  message: "frequencyPenalty must be between -1 and 1 (inclusive)"
@@ -671,7 +335,7 @@ function prepareCallSettings({
671
335
  }
672
336
  if (seed != null) {
673
337
  if (!Number.isInteger(seed)) {
674
- throw new InvalidArgumentError({
338
+ throw new import_provider3.InvalidArgumentError({
675
339
  parameter: "seed",
676
340
  value: seed,
677
341
  message: "seed must be an integer"
@@ -680,14 +344,14 @@ function prepareCallSettings({
680
344
  }
681
345
  if (maxRetries != null) {
682
346
  if (!Number.isInteger(maxRetries)) {
683
- throw new InvalidArgumentError({
347
+ throw new import_provider3.InvalidArgumentError({
684
348
  parameter: "maxRetries",
685
349
  value: maxRetries,
686
350
  message: "maxRetries must be an integer"
687
351
  });
688
352
  }
689
353
  if (maxRetries < 0) {
690
- throw new InvalidArgumentError({
354
+ throw new import_provider3.InvalidArgumentError({
691
355
  parameter: "maxRetries",
692
356
  value: maxRetries,
693
357
  message: "maxRetries must be >= 0"
@@ -711,6 +375,10 @@ function convertZodToJSONSchema(zodSchema) {
711
375
  return (0, import_zod_to_json_schema.default)(zodSchema);
712
376
  }
713
377
 
378
+ // core/util/retry-with-exponential-backoff.ts
379
+ var import_provider4 = require("@ai-sdk/provider");
380
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
381
+
714
382
  // core/util/delay.ts
715
383
  async function delay(delayInMs) {
716
384
  return new Promise((resolve) => setTimeout(resolve, delayInMs));
@@ -740,17 +408,17 @@ async function _retryWithExponentialBackoff(f, {
740
408
  if (maxRetries === 0) {
741
409
  throw error;
742
410
  }
743
- const errorMessage = getErrorMessage(error);
411
+ const errorMessage = (0, import_provider_utils2.getErrorMessage)(error);
744
412
  const newErrors = [...errors, error];
745
413
  const tryNumber = newErrors.length;
746
414
  if (tryNumber > maxRetries) {
747
- throw new RetryError({
748
- message: `Failed after ${tryNumber} attemps. Last error: ${errorMessage}`,
415
+ throw new import_provider4.RetryError({
416
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
749
417
  reason: "maxRetriesExceeded",
750
418
  errors: newErrors
751
419
  });
752
420
  }
753
- if (error instanceof Error && APICallError.isAPICallError(error) && error.isRetryable === true && tryNumber <= maxRetries) {
421
+ if (error instanceof Error && import_provider4.APICallError.isAPICallError(error) && error.isRetryable === true && tryNumber <= maxRetries) {
754
422
  await delay(delayInMs);
755
423
  return _retryWithExponentialBackoff(
756
424
  f,
@@ -761,8 +429,8 @@ async function _retryWithExponentialBackoff(f, {
761
429
  if (tryNumber === 1) {
762
430
  throw error;
763
431
  }
764
- throw new RetryError({
765
- message: `Failed after ${tryNumber} attemps with non-retryable error: '${errorMessage}'`,
432
+ throw new import_provider4.RetryError({
433
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
766
434
  reason: "errorNotRetryable",
767
435
  errors: newErrors
768
436
  });
@@ -794,7 +462,7 @@ async function experimental_generateObject({
794
462
  schema,
795
463
  mode,
796
464
  system,
797
- prompt: prompt2,
465
+ prompt,
798
466
  messages,
799
467
  maxRetries,
800
468
  abortSignal,
@@ -814,7 +482,7 @@ async function experimental_generateObject({
814
482
  case "json": {
815
483
  const validatedPrompt = getValidatedPrompt({
816
484
  system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
817
- prompt: prompt2,
485
+ prompt,
818
486
  messages
819
487
  });
820
488
  const generateResult = await retry(() => {
@@ -827,7 +495,7 @@ async function experimental_generateObject({
827
495
  });
828
496
  });
829
497
  if (generateResult.text === void 0) {
830
- throw new NoTextGeneratedError();
498
+ throw new import_provider5.NoTextGeneratedError();
831
499
  }
832
500
  result = generateResult.text;
833
501
  finishReason = generateResult.finishReason;
@@ -838,7 +506,7 @@ async function experimental_generateObject({
838
506
  case "grammar": {
839
507
  const validatedPrompt = getValidatedPrompt({
840
508
  system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
841
- prompt: prompt2,
509
+ prompt,
842
510
  messages
843
511
  });
844
512
  const generateResult = await retry(
@@ -851,7 +519,7 @@ async function experimental_generateObject({
851
519
  })
852
520
  );
853
521
  if (generateResult.text === void 0) {
854
- throw new NoTextGeneratedError();
522
+ throw new import_provider5.NoTextGeneratedError();
855
523
  }
856
524
  result = generateResult.text;
857
525
  finishReason = generateResult.finishReason;
@@ -862,7 +530,7 @@ async function experimental_generateObject({
862
530
  case "tool": {
863
531
  const validatedPrompt = getValidatedPrompt({
864
532
  system,
865
- prompt: prompt2,
533
+ prompt,
866
534
  messages
867
535
  });
868
536
  const generateResult = await retry(
@@ -884,7 +552,7 @@ async function experimental_generateObject({
884
552
  );
885
553
  const functionArgs = (_b = (_a = generateResult.toolCalls) == null ? void 0 : _a[0]) == null ? void 0 : _b.args;
886
554
  if (functionArgs === void 0) {
887
- throw new NoTextGeneratedError();
555
+ throw new import_provider5.NoTextGeneratedError();
888
556
  }
889
557
  result = functionArgs;
890
558
  finishReason = generateResult.finishReason;
@@ -900,7 +568,7 @@ async function experimental_generateObject({
900
568
  throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);
901
569
  }
902
570
  }
903
- const parseResult = safeParseJSON({ text: result, schema });
571
+ const parseResult = (0, import_provider_utils3.safeParseJSON)({ text: result, schema });
904
572
  if (!parseResult.success) {
905
573
  throw parseResult.error;
906
574
  }
@@ -973,7 +641,7 @@ function isDeepEqualData(obj1, obj2) {
973
641
  }
974
642
 
975
643
  // core/util/parse-partial-json.ts
976
- var import_secure_json_parse2 = __toESM(require("secure-json-parse"));
644
+ var import_secure_json_parse = __toESM(require("secure-json-parse"));
977
645
 
978
646
  // core/util/fix-json.ts
979
647
  function fixJson(input) {
@@ -1298,11 +966,11 @@ function parsePartialJson(jsonText) {
1298
966
  return void 0;
1299
967
  }
1300
968
  try {
1301
- return import_secure_json_parse2.default.parse(jsonText);
969
+ return import_secure_json_parse.default.parse(jsonText);
1302
970
  } catch (ignored) {
1303
971
  try {
1304
972
  const fixedJsonText = fixJson(jsonText);
1305
- return import_secure_json_parse2.default.parse(fixedJsonText);
973
+ return import_secure_json_parse.default.parse(fixedJsonText);
1306
974
  } catch (ignored2) {
1307
975
  }
1308
976
  }
@@ -1315,7 +983,7 @@ async function experimental_streamObject({
1315
983
  schema,
1316
984
  mode,
1317
985
  system,
1318
- prompt: prompt2,
986
+ prompt,
1319
987
  messages,
1320
988
  maxRetries,
1321
989
  abortSignal,
@@ -1332,7 +1000,7 @@ async function experimental_streamObject({
1332
1000
  case "json": {
1333
1001
  const validatedPrompt = getValidatedPrompt({
1334
1002
  system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
1335
- prompt: prompt2,
1003
+ prompt,
1336
1004
  messages
1337
1005
  });
1338
1006
  callOptions = {
@@ -1359,7 +1027,7 @@ async function experimental_streamObject({
1359
1027
  case "grammar": {
1360
1028
  const validatedPrompt = getValidatedPrompt({
1361
1029
  system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
1362
- prompt: prompt2,
1030
+ prompt,
1363
1031
  messages
1364
1032
  });
1365
1033
  callOptions = {
@@ -1386,7 +1054,7 @@ async function experimental_streamObject({
1386
1054
  case "tool": {
1387
1055
  const validatedPrompt = getValidatedPrompt({
1388
1056
  system,
1389
- prompt: prompt2,
1057
+ prompt,
1390
1058
  messages
1391
1059
  });
1392
1060
  callOptions = {
@@ -1464,27 +1132,29 @@ var StreamObjectResult = class {
1464
1132
  };
1465
1133
 
1466
1134
  // core/generate-text/tool-call.ts
1135
+ var import_provider6 = require("@ai-sdk/provider");
1136
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
1467
1137
  function parseToolCall({
1468
1138
  toolCall,
1469
1139
  tools
1470
1140
  }) {
1471
1141
  const toolName = toolCall.toolName;
1472
1142
  if (tools == null) {
1473
- throw new NoSuchToolError({ toolName: toolCall.toolName });
1143
+ throw new import_provider6.NoSuchToolError({ toolName: toolCall.toolName });
1474
1144
  }
1475
1145
  const tool2 = tools[toolName];
1476
1146
  if (tool2 == null) {
1477
- throw new NoSuchToolError({
1147
+ throw new import_provider6.NoSuchToolError({
1478
1148
  toolName: toolCall.toolName,
1479
1149
  availableTools: Object.keys(tools)
1480
1150
  });
1481
1151
  }
1482
- const parseResult = safeParseJSON({
1152
+ const parseResult = (0, import_provider_utils4.safeParseJSON)({
1483
1153
  text: toolCall.args,
1484
1154
  schema: tool2.parameters
1485
1155
  });
1486
1156
  if (parseResult.success === false) {
1487
- throw new InvalidToolArgumentsError({
1157
+ throw new import_provider6.InvalidToolArgumentsError({
1488
1158
  toolName,
1489
1159
  toolArgs: toolCall.args,
1490
1160
  cause: parseResult.error
@@ -1503,7 +1173,7 @@ async function experimental_generateText({
1503
1173
  model,
1504
1174
  tools,
1505
1175
  system,
1506
- prompt: prompt2,
1176
+ prompt,
1507
1177
  messages,
1508
1178
  maxRetries,
1509
1179
  abortSignal,
@@ -1511,7 +1181,7 @@ async function experimental_generateText({
1511
1181
  }) {
1512
1182
  var _a, _b;
1513
1183
  const retry = retryWithExponentialBackoff({ maxRetries });
1514
- const validatedPrompt = getValidatedPrompt({ system, prompt: prompt2, messages });
1184
+ const validatedPrompt = getValidatedPrompt({ system, prompt, messages });
1515
1185
  const modelResponse = await retry(() => {
1516
1186
  return model.doGenerate({
1517
1187
  mode: {
@@ -1580,6 +1250,9 @@ var GenerateTextResult = class {
1580
1250
  }
1581
1251
  };
1582
1252
 
1253
+ // core/generate-text/run-tools-transformation.ts
1254
+ var import_provider7 = require("@ai-sdk/provider");
1255
+
1583
1256
  // shared/generate-id.ts
1584
1257
  var import_non_secure = require("nanoid/non-secure");
1585
1258
  var generateId = (0, import_non_secure.customAlphabet)(
@@ -1614,7 +1287,7 @@ function runToolsTransformation({
1614
1287
  if (tools == null) {
1615
1288
  toolResultsStreamController.enqueue({
1616
1289
  type: "error",
1617
- error: new NoSuchToolError({ toolName: chunk.toolName })
1290
+ error: new import_provider7.NoSuchToolError({ toolName: chunk.toolName })
1618
1291
  });
1619
1292
  break;
1620
1293
  }
@@ -1622,7 +1295,7 @@ function runToolsTransformation({
1622
1295
  if (tool2 == null) {
1623
1296
  toolResultsStreamController.enqueue({
1624
1297
  type: "error",
1625
- error: new NoSuchToolError({
1298
+ error: new import_provider7.NoSuchToolError({
1626
1299
  toolName: chunk.toolName,
1627
1300
  availableTools: Object.keys(tools)
1628
1301
  })
@@ -1728,14 +1401,14 @@ async function experimental_streamText({
1728
1401
  model,
1729
1402
  tools,
1730
1403
  system,
1731
- prompt: prompt2,
1404
+ prompt,
1732
1405
  messages,
1733
1406
  maxRetries,
1734
1407
  abortSignal,
1735
1408
  ...settings
1736
1409
  }) {
1737
1410
  const retry = retryWithExponentialBackoff({ maxRetries });
1738
- const validatedPrompt = getValidatedPrompt({ system, prompt: prompt2, messages });
1411
+ const validatedPrompt = getValidatedPrompt({ system, prompt, messages });
1739
1412
  const { stream, warnings } = await retry(
1740
1413
  () => model.doStream({
1741
1414
  mode: {
@@ -1816,7 +1489,32 @@ var StreamTextResult = class {
1816
1489
  @returns an `AIStream` object.
1817
1490
  */
1818
1491
  toAIStream(callbacks) {
1819
- return readableFromAsyncIterable(this.textStream).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
1492
+ return this.textStream.pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
1493
+ }
1494
+ /**
1495
+ Creates a simple text stream response.
1496
+ Each text delta is encoded as UTF-8 and sent as a separate chunk.
1497
+ Non-text-delta events are ignored.
1498
+ */
1499
+ toTextStreamResponse(init) {
1500
+ const encoder = new TextEncoder();
1501
+ return new Response(
1502
+ this.textStream.pipeThrough(
1503
+ new TransformStream({
1504
+ transform(chunk, controller) {
1505
+ controller.enqueue(encoder.encode(chunk));
1506
+ }
1507
+ })
1508
+ ),
1509
+ {
1510
+ ...init,
1511
+ status: 200,
1512
+ headers: {
1513
+ "Content-Type": "text/plain; charset=utf-8",
1514
+ ...init == null ? void 0 : init.headers
1515
+ }
1516
+ }
1517
+ );
1820
1518
  }
1821
1519
  };
1822
1520
 
@@ -1925,9 +1623,9 @@ var toolCallStreamPart = {
1925
1623
  code: "7",
1926
1624
  name: "tool_calls",
1927
1625
  parse: (value) => {
1928
- if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some((tc) => {
1929
- tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string";
1930
- })) {
1626
+ if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some(
1627
+ (tc) => tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string"
1628
+ )) {
1931
1629
  throw new Error(
1932
1630
  '"tool_calls" parts expect an object with a ToolCallPayload.'
1933
1631
  );
@@ -2005,6 +1703,49 @@ function formatStreamPart(type, value) {
2005
1703
  `;
2006
1704
  }
2007
1705
 
1706
+ // shared/read-data-stream.ts
1707
+ var NEWLINE = "\n".charCodeAt(0);
1708
+ function concatChunks(chunks, totalLength) {
1709
+ const concatenatedChunks = new Uint8Array(totalLength);
1710
+ let offset = 0;
1711
+ for (const chunk of chunks) {
1712
+ concatenatedChunks.set(chunk, offset);
1713
+ offset += chunk.length;
1714
+ }
1715
+ chunks.length = 0;
1716
+ return concatenatedChunks;
1717
+ }
1718
+ async function* readDataStream(reader, {
1719
+ isAborted
1720
+ } = {}) {
1721
+ const decoder = new TextDecoder();
1722
+ const chunks = [];
1723
+ let totalLength = 0;
1724
+ while (true) {
1725
+ const { value } = await reader.read();
1726
+ if (value) {
1727
+ chunks.push(value);
1728
+ totalLength += value.length;
1729
+ if (value[value.length - 1] !== NEWLINE) {
1730
+ continue;
1731
+ }
1732
+ }
1733
+ if (chunks.length === 0) {
1734
+ break;
1735
+ }
1736
+ const concatenatedChunks = concatChunks(chunks, totalLength);
1737
+ totalLength = 0;
1738
+ const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
1739
+ for (const streamPart of streamParts2) {
1740
+ yield streamPart;
1741
+ }
1742
+ if (isAborted == null ? void 0 : isAborted()) {
1743
+ reader.cancel();
1744
+ break;
1745
+ }
1746
+ }
1747
+ }
1748
+
2008
1749
  // shared/utils.ts
2009
1750
  function createChunkDecoder(complex) {
2010
1751
  const decoder = new TextDecoder();
@@ -2978,49 +2719,6 @@ async function ReplicateStream(res, cb, options) {
2978
2719
  );
2979
2720
  }
2980
2721
 
2981
- // shared/read-data-stream.ts
2982
- var NEWLINE = "\n".charCodeAt(0);
2983
- function concatChunks(chunks, totalLength) {
2984
- const concatenatedChunks = new Uint8Array(totalLength);
2985
- let offset = 0;
2986
- for (const chunk of chunks) {
2987
- concatenatedChunks.set(chunk, offset);
2988
- offset += chunk.length;
2989
- }
2990
- chunks.length = 0;
2991
- return concatenatedChunks;
2992
- }
2993
- async function* readDataStream(reader, {
2994
- isAborted
2995
- } = {}) {
2996
- const decoder = new TextDecoder();
2997
- const chunks = [];
2998
- let totalLength = 0;
2999
- while (true) {
3000
- const { value } = await reader.read();
3001
- if (value) {
3002
- chunks.push(value);
3003
- totalLength += value.length;
3004
- if (value[value.length - 1] !== NEWLINE) {
3005
- continue;
3006
- }
3007
- }
3008
- if (chunks.length === 0) {
3009
- break;
3010
- }
3011
- const concatenatedChunks = concatChunks(chunks, totalLength);
3012
- totalLength = 0;
3013
- const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
3014
- for (const streamPart of streamParts2) {
3015
- yield streamPart;
3016
- }
3017
- if (isAborted == null ? void 0 : isAborted()) {
3018
- reader.cancel();
3019
- break;
3020
- }
3021
- }
3022
- }
3023
-
3024
2722
  // shared/parse-complex-response.ts
3025
2723
  function assignAnnotationsToMessage(message, annotations) {
3026
2724
  if (!message || !annotations || !annotations.length)
@@ -3246,9 +2944,12 @@ function streamToResponse(res, response, init) {
3246
2944
  experimental_generateText,
3247
2945
  experimental_streamObject,
3248
2946
  experimental_streamText,
2947
+ formatStreamPart,
3249
2948
  generateId,
3250
2949
  isStreamStringEqualToType,
3251
2950
  nanoid,
2951
+ parseStreamPart,
2952
+ readDataStream,
3252
2953
  readableFromAsyncIterable,
3253
2954
  streamToResponse,
3254
2955
  tool,