ai 5.0.0-canary.17 → 5.0.0-canary.19

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.
@@ -21,39 +21,37 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var internal_exports = {};
22
22
  __export(internal_exports, {
23
23
  HANGING_STREAM_WARNING_TIME_MS: () => HANGING_STREAM_WARNING_TIME_MS,
24
- StreamData: () => StreamData,
25
- calculateLanguageModelUsage: () => calculateLanguageModelUsage,
26
24
  convertToLanguageModelPrompt: () => convertToLanguageModelPrompt,
27
25
  createCallbacksTransformer: () => createCallbacksTransformer,
28
- formatDataStreamPart: () => formatDataStreamPart,
29
- mergeStreams: () => mergeStreams,
30
26
  prepareCallSettings: () => prepareCallSettings,
31
- prepareResponseHeaders: () => prepareResponseHeaders,
32
27
  prepareRetries: () => prepareRetries,
33
28
  prepareToolsAndToolChoice: () => prepareToolsAndToolChoice,
34
29
  standardizePrompt: () => standardizePrompt
35
30
  });
36
31
  module.exports = __toCommonJS(internal_exports);
37
32
 
38
- // core/prompt/standardize-prompt.ts
39
- var import_provider3 = require("@ai-sdk/provider");
40
- var import_provider_utils2 = require("@ai-sdk/provider-utils");
41
- var import_zod7 = require("zod");
33
+ // core/prompt/convert-to-language-model-prompt.ts
34
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
42
35
 
43
- // core/prompt/message-conversion-error.ts
36
+ // util/download-error.ts
44
37
  var import_provider = require("@ai-sdk/provider");
45
- var name = "AI_MessageConversionError";
38
+ var name = "AI_DownloadError";
46
39
  var marker = `vercel.ai.error.${name}`;
47
40
  var symbol = Symbol.for(marker);
48
41
  var _a;
49
- var MessageConversionError = class extends import_provider.AISDKError {
42
+ var DownloadError = class extends import_provider.AISDKError {
50
43
  constructor({
51
- originalMessage,
52
- message
44
+ url,
45
+ statusCode,
46
+ statusText,
47
+ cause,
48
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
53
49
  }) {
54
- super({ name, message });
50
+ super({ name, message, cause });
55
51
  this[_a] = true;
56
- this.originalMessage = originalMessage;
52
+ this.url = url;
53
+ this.statusCode = statusCode;
54
+ this.statusText = statusText;
57
55
  }
58
56
  static isInstance(error) {
59
57
  return import_provider.AISDKError.hasMarker(error, marker);
@@ -61,270 +59,171 @@ var MessageConversionError = class extends import_provider.AISDKError {
61
59
  };
62
60
  _a = symbol;
63
61
 
64
- // core/prompt/convert-to-model-messages.ts
65
- function convertToModelMessages(messages, options) {
66
- var _a6, _b;
67
- const tools = (_a6 = options == null ? void 0 : options.tools) != null ? _a6 : {};
68
- const coreMessages = [];
69
- for (let i = 0; i < messages.length; i++) {
70
- const message = messages[i];
71
- const isLastMessage = i === messages.length - 1;
72
- const { role, content } = message;
73
- switch (role) {
74
- case "system": {
75
- coreMessages.push({
76
- role: "system",
77
- content
78
- });
79
- break;
80
- }
81
- case "user": {
82
- coreMessages.push({
83
- role: "user",
84
- content: message.parts.filter(
85
- (part) => part.type === "text" || part.type === "file"
86
- ).map(
87
- (part) => part.type === "file" ? {
88
- type: "file",
89
- mediaType: part.mediaType,
90
- filename: part.filename,
91
- data: part.url
92
- } : part
93
- )
94
- });
95
- break;
96
- }
97
- case "assistant": {
98
- if (message.parts != null) {
99
- let processBlock2 = function() {
100
- const content2 = [];
101
- for (const part of block) {
102
- switch (part.type) {
103
- case "text": {
104
- content2.push(part);
105
- break;
106
- }
107
- case "file": {
108
- content2.push({
109
- type: "file",
110
- mediaType: part.mediaType,
111
- data: part.url
112
- });
113
- break;
114
- }
115
- case "reasoning": {
116
- content2.push({
117
- type: "reasoning",
118
- text: part.text,
119
- providerOptions: part.providerMetadata
120
- });
121
- break;
122
- }
123
- case "tool-invocation":
124
- content2.push({
125
- type: "tool-call",
126
- toolCallId: part.toolInvocation.toolCallId,
127
- toolName: part.toolInvocation.toolName,
128
- args: part.toolInvocation.args
129
- });
130
- break;
131
- default: {
132
- const _exhaustiveCheck = part;
133
- throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
134
- }
135
- }
136
- }
137
- coreMessages.push({
138
- role: "assistant",
139
- content: content2
140
- });
141
- const stepInvocations = block.filter(
142
- (part) => part.type === "tool-invocation"
143
- ).map((part) => part.toolInvocation);
144
- if (stepInvocations.length > 0) {
145
- coreMessages.push({
146
- role: "tool",
147
- content: stepInvocations.map(
148
- (toolInvocation) => {
149
- if (!("result" in toolInvocation)) {
150
- throw new MessageConversionError({
151
- originalMessage: message,
152
- message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
153
- });
154
- }
155
- const { toolCallId, toolName, result } = toolInvocation;
156
- const tool = tools[toolName];
157
- return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
158
- type: "tool-result",
159
- toolCallId,
160
- toolName,
161
- result: tool.experimental_toToolResultContent(result),
162
- experimental_content: tool.experimental_toToolResultContent(result)
163
- } : {
164
- type: "tool-result",
165
- toolCallId,
166
- toolName,
167
- result
168
- };
169
- }
170
- )
171
- });
172
- }
173
- block = [];
174
- blockHasToolInvocations = false;
175
- currentStep++;
176
- };
177
- var processBlock = processBlock2;
178
- let currentStep = 0;
179
- let blockHasToolInvocations = false;
180
- let block = [];
181
- for (const part of message.parts) {
182
- switch (part.type) {
183
- case "text": {
184
- if (blockHasToolInvocations) {
185
- processBlock2();
186
- }
187
- block.push(part);
188
- break;
189
- }
190
- case "file":
191
- case "reasoning": {
192
- block.push(part);
193
- break;
194
- }
195
- case "tool-invocation": {
196
- if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
197
- processBlock2();
198
- }
199
- block.push(part);
200
- blockHasToolInvocations = true;
201
- break;
202
- }
203
- }
204
- }
205
- processBlock2();
206
- break;
207
- }
208
- if (content && !isLastMessage) {
209
- coreMessages.push({ role: "assistant", content });
210
- }
211
- break;
212
- }
213
- default: {
214
- const _exhaustiveCheck = role;
215
- throw new MessageConversionError({
216
- originalMessage: message,
217
- message: `Unsupported role: ${_exhaustiveCheck}`
218
- });
219
- }
220
- }
221
- }
222
- return coreMessages;
223
- }
224
-
225
- // core/prompt/detect-prompt-type.ts
226
- function detectPromptType(prompt) {
227
- if (!Array.isArray(prompt)) {
228
- return "other";
229
- }
230
- if (prompt.length === 0) {
231
- return "messages";
232
- }
233
- const characteristics = prompt.map(detectSingleMessageCharacteristics);
234
- if (characteristics.some((c) => c === "has-ui-specific-parts")) {
235
- return "ui-messages";
236
- } else if (characteristics.every(
237
- (c) => c === "has-core-specific-parts" || c === "message"
238
- )) {
239
- return "messages";
240
- } else {
241
- return "other";
242
- }
243
- }
244
- function detectSingleMessageCharacteristics(message) {
245
- if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
246
- message.role === "data" || // UI-only role
247
- "toolInvocations" in message || // UI-specific field
248
- "parts" in message || // UI-specific field
249
- "experimental_attachments" in message)) {
250
- return "has-ui-specific-parts";
251
- } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
252
- "providerOptions" in message)) {
253
- return "has-core-specific-parts";
254
- } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
255
- return "message";
256
- } else {
257
- return "other";
258
- }
259
- }
260
-
261
- // core/prompt/message.ts
262
- var import_zod6 = require("zod");
263
-
264
- // core/types/provider-metadata.ts
265
- var import_zod2 = require("zod");
266
-
267
- // core/types/json-value.ts
268
- var import_zod = require("zod");
269
- var jsonValueSchema = import_zod.z.lazy(
270
- () => import_zod.z.union([
271
- import_zod.z.null(),
272
- import_zod.z.string(),
273
- import_zod.z.number(),
274
- import_zod.z.boolean(),
275
- import_zod.z.record(import_zod.z.string(), jsonValueSchema),
276
- import_zod.z.array(jsonValueSchema)
277
- ])
278
- );
279
-
280
- // core/types/provider-metadata.ts
281
- var providerMetadataSchema = import_zod2.z.record(
282
- import_zod2.z.string(),
283
- import_zod2.z.record(import_zod2.z.string(), jsonValueSchema)
284
- );
285
-
286
- // core/prompt/content-part.ts
287
- var import_zod5 = require("zod");
288
-
289
- // core/prompt/data-content.ts
290
- var import_provider2 = require("@ai-sdk/provider");
291
- var import_provider_utils = require("@ai-sdk/provider-utils");
292
- var import_zod3 = require("zod");
293
-
294
- // core/prompt/split-data-url.ts
295
- function splitDataUrl(dataUrl) {
62
+ // util/download.ts
63
+ async function download({ url }) {
64
+ var _a6;
65
+ const urlText = url.toString();
296
66
  try {
297
- const [header, base64Content] = dataUrl.split(",");
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
+ }
298
75
  return {
299
- mediaType: header.split(";")[0].split(":")[1],
300
- base64Content
76
+ data: new Uint8Array(await response.arrayBuffer()),
77
+ mediaType: (_a6 = response.headers.get("content-type")) != null ? _a6 : void 0
301
78
  };
302
79
  } catch (error) {
303
- return {
304
- mediaType: void 0,
305
- base64Content: void 0
306
- };
80
+ if (DownloadError.isInstance(error)) {
81
+ throw error;
82
+ }
83
+ throw new DownloadError({ url: urlText, cause: error });
307
84
  }
308
85
  }
309
86
 
310
- // core/prompt/data-content.ts
311
- var dataContentSchema = import_zod3.z.union([
312
- import_zod3.z.string(),
313
- import_zod3.z.instanceof(Uint8Array),
314
- import_zod3.z.instanceof(ArrayBuffer),
315
- import_zod3.z.custom(
316
- // Buffer might not be available in some environments such as CloudFlare:
317
- (value) => {
318
- var _a6, _b;
319
- return (_b = (_a6 = globalThis.Buffer) == null ? void 0 : _a6.isBuffer(value)) != null ? _b : false;
320
- },
321
- { message: "Must be a Buffer" }
322
- )
323
- ]);
324
- function convertToLanguageModelV2DataContent(content) {
325
- if (content instanceof Uint8Array) {
326
- return { data: content, mediaType: void 0 };
327
- }
87
+ // core/util/detect-media-type.ts
88
+ var import_provider_utils = require("@ai-sdk/provider-utils");
89
+ var imageMediaTypeSignatures = [
90
+ {
91
+ mediaType: "image/gif",
92
+ bytesPrefix: [71, 73, 70],
93
+ base64Prefix: "R0lG"
94
+ },
95
+ {
96
+ mediaType: "image/png",
97
+ bytesPrefix: [137, 80, 78, 71],
98
+ base64Prefix: "iVBORw"
99
+ },
100
+ {
101
+ mediaType: "image/jpeg",
102
+ bytesPrefix: [255, 216],
103
+ base64Prefix: "/9j/"
104
+ },
105
+ {
106
+ mediaType: "image/webp",
107
+ bytesPrefix: [82, 73, 70, 70],
108
+ base64Prefix: "UklGRg"
109
+ },
110
+ {
111
+ mediaType: "image/bmp",
112
+ bytesPrefix: [66, 77],
113
+ base64Prefix: "Qk"
114
+ },
115
+ {
116
+ mediaType: "image/tiff",
117
+ bytesPrefix: [73, 73, 42, 0],
118
+ base64Prefix: "SUkqAA"
119
+ },
120
+ {
121
+ mediaType: "image/tiff",
122
+ bytesPrefix: [77, 77, 0, 42],
123
+ base64Prefix: "TU0AKg"
124
+ },
125
+ {
126
+ mediaType: "image/avif",
127
+ bytesPrefix: [
128
+ 0,
129
+ 0,
130
+ 0,
131
+ 32,
132
+ 102,
133
+ 116,
134
+ 121,
135
+ 112,
136
+ 97,
137
+ 118,
138
+ 105,
139
+ 102
140
+ ],
141
+ base64Prefix: "AAAAIGZ0eXBhdmlm"
142
+ },
143
+ {
144
+ mediaType: "image/heic",
145
+ bytesPrefix: [
146
+ 0,
147
+ 0,
148
+ 0,
149
+ 32,
150
+ 102,
151
+ 116,
152
+ 121,
153
+ 112,
154
+ 104,
155
+ 101,
156
+ 105,
157
+ 99
158
+ ],
159
+ base64Prefix: "AAAAIGZ0eXBoZWlj"
160
+ }
161
+ ];
162
+ var stripID3 = (data) => {
163
+ const bytes = typeof data === "string" ? (0, import_provider_utils.convertBase64ToUint8Array)(data) : data;
164
+ const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
165
+ return bytes.slice(id3Size + 10);
166
+ };
167
+ function stripID3TagsIfPresent(data) {
168
+ const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && // 'I'
169
+ data[1] === 68 && // 'D'
170
+ data[2] === 51;
171
+ return hasId3 ? stripID3(data) : data;
172
+ }
173
+ function detectMediaType({
174
+ data,
175
+ signatures
176
+ }) {
177
+ const processedData = stripID3TagsIfPresent(data);
178
+ for (const signature of signatures) {
179
+ if (typeof processedData === "string" ? processedData.startsWith(signature.base64Prefix) : processedData.length >= signature.bytesPrefix.length && signature.bytesPrefix.every(
180
+ (byte, index) => processedData[index] === byte
181
+ )) {
182
+ return signature.mediaType;
183
+ }
184
+ }
185
+ return void 0;
186
+ }
187
+
188
+ // core/prompt/data-content.ts
189
+ var import_provider2 = require("@ai-sdk/provider");
190
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
191
+ var import_zod = require("zod");
192
+
193
+ // core/prompt/split-data-url.ts
194
+ function splitDataUrl(dataUrl) {
195
+ try {
196
+ const [header, base64Content] = dataUrl.split(",");
197
+ return {
198
+ mediaType: header.split(";")[0].split(":")[1],
199
+ base64Content
200
+ };
201
+ } catch (error) {
202
+ return {
203
+ mediaType: void 0,
204
+ base64Content: void 0
205
+ };
206
+ }
207
+ }
208
+
209
+ // core/prompt/data-content.ts
210
+ var dataContentSchema = import_zod.z.union([
211
+ import_zod.z.string(),
212
+ import_zod.z.instanceof(Uint8Array),
213
+ import_zod.z.instanceof(ArrayBuffer),
214
+ import_zod.z.custom(
215
+ // Buffer might not be available in some environments such as CloudFlare:
216
+ (value) => {
217
+ var _a6, _b;
218
+ return (_b = (_a6 = globalThis.Buffer) == null ? void 0 : _a6.isBuffer(value)) != null ? _b : false;
219
+ },
220
+ { message: "Must be a Buffer" }
221
+ )
222
+ ]);
223
+ function convertToLanguageModelV2DataContent(content) {
224
+ if (content instanceof Uint8Array) {
225
+ return { data: content, mediaType: void 0 };
226
+ }
328
227
  if (content instanceof ArrayBuffer) {
329
228
  return { data: new Uint8Array(content), mediaType: void 0 };
330
229
  }
@@ -349,493 +248,245 @@ function convertToLanguageModelV2DataContent(content) {
349
248
  return { data: content, mediaType: void 0 };
350
249
  }
351
250
 
352
- // core/prompt/tool-result-content.ts
353
- var import_zod4 = require("zod");
354
- var toolResultContentSchema = import_zod4.z.array(
355
- import_zod4.z.union([
356
- import_zod4.z.object({ type: import_zod4.z.literal("text"), text: import_zod4.z.string() }),
357
- import_zod4.z.object({
358
- type: import_zod4.z.literal("image"),
359
- data: import_zod4.z.string(),
360
- mediaType: import_zod4.z.string().optional()
361
- })
362
- ])
363
- );
364
-
365
- // core/prompt/content-part.ts
366
- var textPartSchema = import_zod5.z.object({
367
- type: import_zod5.z.literal("text"),
368
- text: import_zod5.z.string(),
369
- providerOptions: providerMetadataSchema.optional()
370
- });
371
- var imagePartSchema = import_zod5.z.object({
372
- type: import_zod5.z.literal("image"),
373
- image: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
374
- mediaType: import_zod5.z.string().optional(),
375
- providerOptions: providerMetadataSchema.optional()
376
- });
377
- var filePartSchema = import_zod5.z.object({
378
- type: import_zod5.z.literal("file"),
379
- data: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
380
- filename: import_zod5.z.string().optional(),
381
- mediaType: import_zod5.z.string(),
382
- providerOptions: providerMetadataSchema.optional()
383
- });
384
- var reasoningPartSchema = import_zod5.z.object({
385
- type: import_zod5.z.literal("reasoning"),
386
- text: import_zod5.z.string(),
387
- providerOptions: providerMetadataSchema.optional()
388
- });
389
- var toolCallPartSchema = import_zod5.z.object({
390
- type: import_zod5.z.literal("tool-call"),
391
- toolCallId: import_zod5.z.string(),
392
- toolName: import_zod5.z.string(),
393
- args: import_zod5.z.unknown(),
394
- providerOptions: providerMetadataSchema.optional()
395
- });
396
- var toolResultPartSchema = import_zod5.z.object({
397
- type: import_zod5.z.literal("tool-result"),
398
- toolCallId: import_zod5.z.string(),
399
- toolName: import_zod5.z.string(),
400
- result: import_zod5.z.unknown(),
401
- content: toolResultContentSchema.optional(),
402
- isError: import_zod5.z.boolean().optional(),
403
- providerOptions: providerMetadataSchema.optional()
404
- });
405
-
406
- // core/prompt/message.ts
407
- var systemModelMessageSchema = import_zod6.z.object(
408
- {
409
- role: import_zod6.z.literal("system"),
410
- content: import_zod6.z.string(),
411
- providerOptions: providerMetadataSchema.optional()
251
+ // core/prompt/invalid-message-role-error.ts
252
+ var import_provider3 = require("@ai-sdk/provider");
253
+ var name2 = "AI_InvalidMessageRoleError";
254
+ var marker2 = `vercel.ai.error.${name2}`;
255
+ var symbol2 = Symbol.for(marker2);
256
+ var _a2;
257
+ var InvalidMessageRoleError = class extends import_provider3.AISDKError {
258
+ constructor({
259
+ role,
260
+ message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
261
+ }) {
262
+ super({ name: name2, message });
263
+ this[_a2] = true;
264
+ this.role = role;
412
265
  }
413
- );
414
- var userModelMessageSchema = import_zod6.z.object({
415
- role: import_zod6.z.literal("user"),
416
- content: import_zod6.z.union([
417
- import_zod6.z.string(),
418
- import_zod6.z.array(import_zod6.z.union([textPartSchema, imagePartSchema, filePartSchema]))
419
- ]),
420
- providerOptions: providerMetadataSchema.optional()
421
- });
422
- var assistantModelMessageSchema = import_zod6.z.object({
423
- role: import_zod6.z.literal("assistant"),
424
- content: import_zod6.z.union([
425
- import_zod6.z.string(),
426
- import_zod6.z.array(
427
- import_zod6.z.union([
428
- textPartSchema,
429
- filePartSchema,
430
- reasoningPartSchema,
431
- toolCallPartSchema
432
- ])
433
- )
434
- ]),
435
- providerOptions: providerMetadataSchema.optional()
436
- });
437
- var toolModelMessageSchema = import_zod6.z.object({
438
- role: import_zod6.z.literal("tool"),
439
- content: import_zod6.z.array(toolResultPartSchema),
440
- providerOptions: providerMetadataSchema.optional()
441
- });
442
- var modelMessageSchema = import_zod6.z.union([
443
- systemModelMessageSchema,
444
- userModelMessageSchema,
445
- assistantModelMessageSchema,
446
- toolModelMessageSchema
447
- ]);
266
+ static isInstance(error) {
267
+ return import_provider3.AISDKError.hasMarker(error, marker2);
268
+ }
269
+ };
270
+ _a2 = symbol2;
448
271
 
449
- // core/prompt/standardize-prompt.ts
450
- async function standardizePrompt({
272
+ // core/prompt/convert-to-language-model-prompt.ts
273
+ async function convertToLanguageModelPrompt({
451
274
  prompt,
452
- tools
275
+ supportedUrls,
276
+ downloadImplementation = download
453
277
  }) {
454
- if (prompt.prompt == null && prompt.messages == null) {
455
- throw new import_provider3.InvalidPromptError({
456
- prompt,
457
- message: "prompt or messages must be defined"
458
- });
459
- }
460
- if (prompt.prompt != null && prompt.messages != null) {
461
- throw new import_provider3.InvalidPromptError({
462
- prompt,
463
- message: "prompt and messages cannot be defined at the same time"
464
- });
465
- }
466
- if (prompt.system != null && typeof prompt.system !== "string") {
467
- throw new import_provider3.InvalidPromptError({
468
- prompt,
469
- message: "system must be a string"
470
- });
471
- }
472
- if (prompt.prompt != null) {
473
- if (typeof prompt.prompt !== "string") {
474
- throw new import_provider3.InvalidPromptError({
475
- prompt,
476
- message: "prompt must be a string"
477
- });
278
+ const downloadedAssets = await downloadAssets(
279
+ prompt.messages,
280
+ downloadImplementation,
281
+ supportedUrls
282
+ );
283
+ return [
284
+ ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
285
+ ...prompt.messages.map(
286
+ (message) => convertToLanguageModelMessage(message, downloadedAssets)
287
+ )
288
+ ];
289
+ }
290
+ function convertToLanguageModelMessage(message, downloadedAssets) {
291
+ const role = message.role;
292
+ switch (role) {
293
+ case "system": {
294
+ return {
295
+ role: "system",
296
+ content: message.content,
297
+ providerOptions: message.providerOptions
298
+ };
478
299
  }
479
- return {
480
- system: prompt.system,
481
- messages: [
482
- {
300
+ case "user": {
301
+ if (typeof message.content === "string") {
302
+ return {
483
303
  role: "user",
484
- content: prompt.prompt
485
- }
486
- ]
487
- };
488
- }
489
- if (prompt.messages != null) {
490
- const promptType = detectPromptType(prompt.messages);
491
- if (promptType === "other") {
492
- throw new import_provider3.InvalidPromptError({
493
- prompt,
494
- message: "messages must be an array of ModelMessage or UIMessage"
495
- });
496
- }
497
- const messages = promptType === "ui-messages" ? convertToModelMessages(prompt.messages, {
498
- tools
499
- }) : prompt.messages;
500
- if (messages.length === 0) {
501
- throw new import_provider3.InvalidPromptError({
502
- prompt,
503
- message: "messages must not be empty"
504
- });
505
- }
506
- const validationResult = await (0, import_provider_utils2.safeValidateTypes)({
507
- value: messages,
508
- schema: import_zod7.z.array(modelMessageSchema)
509
- });
510
- if (!validationResult.success) {
511
- throw new import_provider3.InvalidPromptError({
512
- prompt,
513
- message: "messages must be an array of ModelMessage or UIMessage",
514
- cause: validationResult.error
515
- });
516
- }
517
- return {
518
- messages,
519
- system: prompt.system
520
- };
521
- }
522
- throw new Error("unreachable");
523
- }
524
-
525
- // core/util/index.ts
526
- var import_provider_utils3 = require("@ai-sdk/provider-utils");
527
-
528
- // core/util/data-stream-parts.ts
529
- var textStreamPart = {
530
- code: "0",
531
- name: "text",
532
- parse: (value) => {
533
- if (typeof value !== "string") {
534
- throw new Error('"text" parts expect a string value.');
304
+ content: [{ type: "text", text: message.content }],
305
+ providerOptions: message.providerOptions
306
+ };
307
+ }
308
+ return {
309
+ role: "user",
310
+ content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
311
+ providerOptions: message.providerOptions
312
+ };
535
313
  }
536
- return { type: "text", value };
537
- }
538
- };
539
- var dataStreamPart = {
540
- code: "2",
541
- name: "data",
542
- parse: (value) => {
543
- if (!Array.isArray(value)) {
544
- throw new Error('"data" parts expect an array value.');
314
+ case "assistant": {
315
+ if (typeof message.content === "string") {
316
+ return {
317
+ role: "assistant",
318
+ content: [{ type: "text", text: message.content }],
319
+ providerOptions: message.providerOptions
320
+ };
321
+ }
322
+ return {
323
+ role: "assistant",
324
+ content: message.content.filter(
325
+ // remove empty text parts:
326
+ (part) => part.type !== "text" || part.text !== ""
327
+ ).map((part) => {
328
+ const providerOptions = part.providerOptions;
329
+ switch (part.type) {
330
+ case "file": {
331
+ const { data, mediaType } = convertToLanguageModelV2DataContent(
332
+ part.data
333
+ );
334
+ return {
335
+ type: "file",
336
+ data,
337
+ filename: part.filename,
338
+ mediaType: mediaType != null ? mediaType : part.mediaType,
339
+ providerOptions
340
+ };
341
+ }
342
+ case "reasoning": {
343
+ return {
344
+ type: "reasoning",
345
+ text: part.text,
346
+ providerOptions
347
+ };
348
+ }
349
+ case "text": {
350
+ return {
351
+ type: "text",
352
+ text: part.text,
353
+ providerOptions
354
+ };
355
+ }
356
+ case "tool-call": {
357
+ return {
358
+ type: "tool-call",
359
+ toolCallId: part.toolCallId,
360
+ toolName: part.toolName,
361
+ args: part.args,
362
+ providerOptions
363
+ };
364
+ }
365
+ }
366
+ }),
367
+ providerOptions: message.providerOptions
368
+ };
545
369
  }
546
- return { type: "data", value };
547
- }
548
- };
549
- var errorStreamPart = {
550
- code: "3",
551
- name: "error",
552
- parse: (value) => {
553
- if (typeof value !== "string") {
554
- throw new Error('"error" parts expect a string value.');
370
+ case "tool": {
371
+ return {
372
+ role: "tool",
373
+ content: message.content.map((part) => ({
374
+ type: "tool-result",
375
+ toolCallId: part.toolCallId,
376
+ toolName: part.toolName,
377
+ result: part.result,
378
+ content: part.experimental_content,
379
+ isError: part.isError,
380
+ providerOptions: part.providerOptions
381
+ })),
382
+ providerOptions: message.providerOptions
383
+ };
555
384
  }
556
- return { type: "error", value };
557
- }
558
- };
559
- var messageAnnotationsStreamPart = {
560
- code: "8",
561
- name: "message_annotations",
562
- parse: (value) => {
563
- if (!Array.isArray(value)) {
564
- throw new Error('"message_annotations" parts expect an array value.');
385
+ default: {
386
+ const _exhaustiveCheck = role;
387
+ throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
565
388
  }
566
- return { type: "message_annotations", value };
567
389
  }
568
- };
569
- var toolCallStreamPart = {
570
- code: "9",
571
- name: "tool_call",
572
- parse: (value) => {
573
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
574
- throw new Error(
575
- '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
576
- );
390
+ }
391
+ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
392
+ const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
393
+ (content) => Array.isArray(content)
394
+ ).flat().filter(
395
+ (part) => part.type === "image" || part.type === "file"
396
+ ).map((part) => {
397
+ var _a6;
398
+ const mediaType = (_a6 = part.mediaType) != null ? _a6 : part.type === "image" ? "image/*" : void 0;
399
+ let data = part.type === "image" ? part.image : part.data;
400
+ if (typeof data === "string") {
401
+ try {
402
+ data = new URL(data);
403
+ } catch (ignored) {
404
+ }
577
405
  }
406
+ return { mediaType, data };
407
+ }).filter(
408
+ (part) => part.data instanceof URL && part.mediaType != null && !(0, import_provider_utils3.isUrlSupported)({
409
+ url: part.data.toString(),
410
+ mediaType: part.mediaType,
411
+ supportedUrls
412
+ })
413
+ ).map((part) => part.data);
414
+ const downloadedImages = await Promise.all(
415
+ urls.map(async (url) => ({
416
+ url,
417
+ data: await downloadImplementation({ url })
418
+ }))
419
+ );
420
+ return Object.fromEntries(
421
+ downloadedImages.map(({ url, data }) => [url.toString(), data])
422
+ );
423
+ }
424
+ function convertPartToLanguageModelPart(part, downloadedAssets) {
425
+ var _a6, _b;
426
+ if (part.type === "text") {
578
427
  return {
579
- type: "tool_call",
580
- value
428
+ type: "text",
429
+ text: part.text,
430
+ providerOptions: part.providerOptions
581
431
  };
582
432
  }
583
- };
584
- var toolResultStreamPart = {
585
- code: "a",
586
- name: "tool_result",
587
- parse: (value) => {
588
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) {
589
- throw new Error(
590
- '"tool_result" parts expect an object with a "toolCallId" and a "result" property.'
591
- );
592
- }
593
- return {
594
- type: "tool_result",
595
- value
596
- };
433
+ let originalData;
434
+ const type = part.type;
435
+ switch (type) {
436
+ case "image":
437
+ originalData = part.image;
438
+ break;
439
+ case "file":
440
+ originalData = part.data;
441
+ break;
442
+ default:
443
+ throw new Error(`Unsupported part type: ${type}`);
597
444
  }
598
- };
599
- var toolCallStreamingStartStreamPart = {
600
- code: "b",
601
- name: "tool_call_streaming_start",
602
- parse: (value) => {
603
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") {
604
- throw new Error(
605
- '"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.'
606
- );
445
+ const { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV2DataContent(originalData);
446
+ let mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;
447
+ let data = convertedData;
448
+ if (data instanceof URL) {
449
+ const downloadedFile = downloadedAssets[data.toString()];
450
+ if (downloadedFile) {
451
+ data = downloadedFile.data;
452
+ mediaType = (_a6 = downloadedFile.mediaType) != null ? _a6 : mediaType;
607
453
  }
608
- return {
609
- type: "tool_call_streaming_start",
610
- value
611
- };
612
454
  }
613
- };
614
- var toolCallDeltaStreamPart = {
615
- code: "c",
616
- name: "tool_call_delta",
617
- parse: (value) => {
618
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") {
619
- throw new Error(
620
- '"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.'
621
- );
455
+ switch (type) {
456
+ case "image": {
457
+ if (data instanceof Uint8Array || typeof data === "string") {
458
+ mediaType = (_b = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _b : mediaType;
459
+ }
460
+ return {
461
+ type: "file",
462
+ mediaType: mediaType != null ? mediaType : "image/*",
463
+ // any image
464
+ filename: void 0,
465
+ data,
466
+ providerOptions: part.providerOptions
467
+ };
622
468
  }
623
- return {
624
- type: "tool_call_delta",
625
- value
626
- };
627
- }
628
- };
629
- var finishMessageStreamPart = {
630
- code: "d",
631
- name: "finish_message",
632
- parse: (value) => {
633
- if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
634
- throw new Error(
635
- '"finish_message" parts expect an object with a "finishReason" property.'
636
- );
637
- }
638
- const result = {
639
- finishReason: value.finishReason
640
- };
641
- if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
642
- result.usage = {
643
- promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
644
- completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
645
- };
646
- }
647
- return {
648
- type: "finish_message",
649
- value: result
650
- };
651
- }
652
- };
653
- var finishStepStreamPart = {
654
- code: "e",
655
- name: "finish_step",
656
- parse: (value) => {
657
- if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
658
- throw new Error(
659
- '"finish_step" parts expect an object with a "finishReason" property.'
660
- );
661
- }
662
- const result = {
663
- finishReason: value.finishReason,
664
- isContinued: false
665
- };
666
- if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
667
- result.usage = {
668
- promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
669
- completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
670
- };
671
- }
672
- if ("isContinued" in value && typeof value.isContinued === "boolean") {
673
- result.isContinued = value.isContinued;
674
- }
675
- return {
676
- type: "finish_step",
677
- value: result
678
- };
679
- }
680
- };
681
- var startStepStreamPart = {
682
- code: "f",
683
- name: "start_step",
684
- parse: (value) => {
685
- if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") {
686
- throw new Error(
687
- '"start_step" parts expect an object with an "id" property.'
688
- );
689
- }
690
- return {
691
- type: "start_step",
692
- value: {
693
- messageId: value.messageId
694
- }
695
- };
696
- }
697
- };
698
- var reasoningStreamPart = {
699
- code: "g",
700
- name: "reasoning",
701
- parse: (value) => {
702
- if (value == null || typeof value !== "object" || !("text" in value) || typeof value.text !== "string" || "providerMetadata" in value && typeof value.providerMetadata !== "object") {
703
- throw new Error(
704
- '"reasoning" parts expect an object with a "text" property.'
705
- );
706
- }
707
- return {
708
- type: "reasoning",
709
- value: {
710
- text: value.text,
711
- providerMetadata: value.providerMetadata
469
+ case "file": {
470
+ if (mediaType == null) {
471
+ throw new Error(`Media type is missing for file part`);
712
472
  }
713
- };
714
- }
715
- };
716
- var sourcePart = {
717
- code: "h",
718
- name: "source",
719
- parse: (value) => {
720
- if (value == null || typeof value !== "object") {
721
- throw new Error('"source" parts expect a Source object.');
722
- }
723
- return {
724
- type: "source",
725
- value
726
- };
727
- }
728
- };
729
- var fileStreamPart = {
730
- code: "k",
731
- name: "file",
732
- parse: (value) => {
733
- if (value == null || typeof value !== "object" || !("url" in value) || typeof value.url !== "string" || !("mediaType" in value) || typeof value.mediaType !== "string") {
734
- throw new Error(
735
- '"file" parts expect an object with a "url" and "mediaType" property.'
736
- );
473
+ return {
474
+ type: "file",
475
+ mediaType,
476
+ filename: part.filename,
477
+ data,
478
+ providerOptions: part.providerOptions
479
+ };
737
480
  }
738
- return { type: "file", value };
739
- }
740
- };
741
- var reasoningPartFinishStreamPart = {
742
- code: "l",
743
- name: "reasoning_part_finish",
744
- parse: () => {
745
- return {
746
- type: "reasoning_part_finish",
747
- value: {}
748
- };
749
- }
750
- };
751
- var dataStreamParts = [
752
- textStreamPart,
753
- dataStreamPart,
754
- errorStreamPart,
755
- messageAnnotationsStreamPart,
756
- toolCallStreamPart,
757
- toolResultStreamPart,
758
- toolCallStreamingStartStreamPart,
759
- toolCallDeltaStreamPart,
760
- finishMessageStreamPart,
761
- finishStepStreamPart,
762
- startStepStreamPart,
763
- reasoningStreamPart,
764
- sourcePart,
765
- reasoningPartFinishStreamPart,
766
- fileStreamPart
767
- ];
768
- var dataStreamPartsByCode = Object.fromEntries(
769
- dataStreamParts.map((part) => [part.code, part])
770
- );
771
- var DataStreamStringPrefixes = Object.fromEntries(
772
- dataStreamParts.map((part) => [part.name, part.code])
773
- );
774
- var validCodes = dataStreamParts.map((part) => part.code);
775
- function formatDataStreamPart(type, value) {
776
- const streamPart = dataStreamParts.find((part) => part.name === type);
777
- if (!streamPart) {
778
- throw new Error(`Invalid stream part type: ${type}`);
779
- }
780
- return `${streamPart.code}:${JSON.stringify(value)}
781
- `;
782
- }
783
-
784
- // core/util/is-non-empty-object.ts
785
- function isNonEmptyObject(object) {
786
- return object != null && Object.keys(object).length > 0;
787
- }
788
-
789
- // core/prompt/prepare-tools-and-tool-choice.ts
790
- function prepareToolsAndToolChoice({
791
- tools,
792
- toolChoice,
793
- activeTools
794
- }) {
795
- if (!isNonEmptyObject(tools)) {
796
- return {
797
- tools: void 0,
798
- toolChoice: void 0
799
- };
800
481
  }
801
- const filteredTools = activeTools != null ? Object.entries(tools).filter(
802
- ([name6]) => activeTools.includes(name6)
803
- ) : Object.entries(tools);
804
- return {
805
- tools: filteredTools.map(([name6, tool]) => {
806
- const toolType = tool.type;
807
- switch (toolType) {
808
- case void 0:
809
- case "function":
810
- return {
811
- type: "function",
812
- name: name6,
813
- description: tool.description,
814
- parameters: (0, import_provider_utils3.asSchema)(tool.parameters).jsonSchema
815
- };
816
- case "provider-defined":
817
- return {
818
- type: "provider-defined",
819
- name: name6,
820
- id: tool.id,
821
- args: tool.args
822
- };
823
- default: {
824
- const exhaustiveCheck = toolType;
825
- throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
826
- }
827
- }
828
- }),
829
- toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
830
- };
831
482
  }
832
483
 
833
484
  // errors/invalid-argument-error.ts
834
485
  var import_provider4 = require("@ai-sdk/provider");
835
- var name2 = "AI_InvalidArgumentError";
836
- var marker2 = `vercel.ai.error.${name2}`;
837
- var symbol2 = Symbol.for(marker2);
838
- var _a2;
486
+ var name3 = "AI_InvalidArgumentError";
487
+ var marker3 = `vercel.ai.error.${name3}`;
488
+ var symbol3 = Symbol.for(marker3);
489
+ var _a3;
839
490
  var InvalidArgumentError = class extends import_provider4.AISDKError {
840
491
  constructor({
841
492
  parameter,
@@ -843,127 +494,19 @@ var InvalidArgumentError = class extends import_provider4.AISDKError {
843
494
  message
844
495
  }) {
845
496
  super({
846
- name: name2,
497
+ name: name3,
847
498
  message: `Invalid argument for parameter ${parameter}: ${message}`
848
499
  });
849
- this[_a2] = true;
500
+ this[_a3] = true;
850
501
  this.parameter = parameter;
851
502
  this.value = value;
852
503
  }
853
504
  static isInstance(error) {
854
- return import_provider4.AISDKError.hasMarker(error, marker2);
855
- }
856
- };
857
- _a2 = symbol2;
858
-
859
- // util/retry-with-exponential-backoff.ts
860
- var import_provider6 = require("@ai-sdk/provider");
861
- var import_provider_utils4 = require("@ai-sdk/provider-utils");
862
-
863
- // util/retry-error.ts
864
- var import_provider5 = require("@ai-sdk/provider");
865
- var name3 = "AI_RetryError";
866
- var marker3 = `vercel.ai.error.${name3}`;
867
- var symbol3 = Symbol.for(marker3);
868
- var _a3;
869
- var RetryError = class extends import_provider5.AISDKError {
870
- constructor({
871
- message,
872
- reason,
873
- errors
874
- }) {
875
- super({ name: name3, message });
876
- this[_a3] = true;
877
- this.reason = reason;
878
- this.errors = errors;
879
- this.lastError = errors[errors.length - 1];
880
- }
881
- static isInstance(error) {
882
- return import_provider5.AISDKError.hasMarker(error, marker3);
505
+ return import_provider4.AISDKError.hasMarker(error, marker3);
883
506
  }
884
507
  };
885
508
  _a3 = symbol3;
886
509
 
887
- // util/retry-with-exponential-backoff.ts
888
- var retryWithExponentialBackoff = ({
889
- maxRetries = 2,
890
- initialDelayInMs = 2e3,
891
- backoffFactor = 2
892
- } = {}) => async (f) => _retryWithExponentialBackoff(f, {
893
- maxRetries,
894
- delayInMs: initialDelayInMs,
895
- backoffFactor
896
- });
897
- async function _retryWithExponentialBackoff(f, {
898
- maxRetries,
899
- delayInMs,
900
- backoffFactor
901
- }, errors = []) {
902
- try {
903
- return await f();
904
- } catch (error) {
905
- if ((0, import_provider_utils4.isAbortError)(error)) {
906
- throw error;
907
- }
908
- if (maxRetries === 0) {
909
- throw error;
910
- }
911
- const errorMessage = (0, import_provider_utils4.getErrorMessage)(error);
912
- const newErrors = [...errors, error];
913
- const tryNumber = newErrors.length;
914
- if (tryNumber > maxRetries) {
915
- throw new RetryError({
916
- message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
917
- reason: "maxRetriesExceeded",
918
- errors: newErrors
919
- });
920
- }
921
- if (error instanceof Error && import_provider6.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
922
- await (0, import_provider_utils4.delay)(delayInMs);
923
- return _retryWithExponentialBackoff(
924
- f,
925
- { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
926
- newErrors
927
- );
928
- }
929
- if (tryNumber === 1) {
930
- throw error;
931
- }
932
- throw new RetryError({
933
- message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
934
- reason: "errorNotRetryable",
935
- errors: newErrors
936
- });
937
- }
938
- }
939
-
940
- // core/prompt/prepare-retries.ts
941
- function prepareRetries({
942
- maxRetries
943
- }) {
944
- if (maxRetries != null) {
945
- if (!Number.isInteger(maxRetries)) {
946
- throw new InvalidArgumentError({
947
- parameter: "maxRetries",
948
- value: maxRetries,
949
- message: "maxRetries must be an integer"
950
- });
951
- }
952
- if (maxRetries < 0) {
953
- throw new InvalidArgumentError({
954
- parameter: "maxRetries",
955
- value: maxRetries,
956
- message: "maxRetries must be >= 0"
957
- });
958
- }
959
- }
960
- const maxRetriesResult = maxRetries != null ? maxRetries : 2;
961
- return {
962
- maxRetries: maxRetriesResult,
963
- retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
964
- };
965
- }
966
-
967
510
  // core/prompt/prepare-call-settings.ts
968
511
  function prepareCallSettings({
969
512
  maxOutputTokens,
@@ -1057,512 +600,591 @@ function prepareCallSettings({
1057
600
  };
1058
601
  }
1059
602
 
1060
- // core/prompt/convert-to-language-model-prompt.ts
1061
- var import_provider_utils6 = require("@ai-sdk/provider-utils");
603
+ // util/retry-with-exponential-backoff.ts
604
+ var import_provider6 = require("@ai-sdk/provider");
605
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
1062
606
 
1063
- // util/download-error.ts
1064
- var import_provider7 = require("@ai-sdk/provider");
1065
- var name4 = "AI_DownloadError";
607
+ // util/retry-error.ts
608
+ var import_provider5 = require("@ai-sdk/provider");
609
+ var name4 = "AI_RetryError";
1066
610
  var marker4 = `vercel.ai.error.${name4}`;
1067
611
  var symbol4 = Symbol.for(marker4);
1068
612
  var _a4;
1069
- var DownloadError = class extends import_provider7.AISDKError {
613
+ var RetryError = class extends import_provider5.AISDKError {
1070
614
  constructor({
1071
- url,
1072
- statusCode,
1073
- statusText,
1074
- cause,
1075
- message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
615
+ message,
616
+ reason,
617
+ errors
1076
618
  }) {
1077
- super({ name: name4, message, cause });
619
+ super({ name: name4, message });
1078
620
  this[_a4] = true;
1079
- this.url = url;
1080
- this.statusCode = statusCode;
1081
- this.statusText = statusText;
621
+ this.reason = reason;
622
+ this.errors = errors;
623
+ this.lastError = errors[errors.length - 1];
1082
624
  }
1083
625
  static isInstance(error) {
1084
- return import_provider7.AISDKError.hasMarker(error, marker4);
626
+ return import_provider5.AISDKError.hasMarker(error, marker4);
1085
627
  }
1086
628
  };
1087
629
  _a4 = symbol4;
1088
630
 
1089
- // util/download.ts
1090
- async function download({ url }) {
1091
- var _a6;
1092
- const urlText = url.toString();
1093
- try {
1094
- const response = await fetch(urlText);
1095
- if (!response.ok) {
1096
- throw new DownloadError({
1097
- url: urlText,
1098
- statusCode: response.status,
1099
- statusText: response.statusText
1100
- });
1101
- }
1102
- return {
1103
- data: new Uint8Array(await response.arrayBuffer()),
1104
- mediaType: (_a6 = response.headers.get("content-type")) != null ? _a6 : void 0
1105
- };
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();
1106
648
  } catch (error) {
1107
- if (DownloadError.isInstance(error)) {
649
+ if ((0, import_provider_utils4.isAbortError)(error)) {
1108
650
  throw error;
1109
651
  }
1110
- throw new DownloadError({ url: urlText, cause: error });
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
+ });
1111
681
  }
1112
682
  }
1113
683
 
1114
- // core/util/detect-media-type.ts
1115
- var import_provider_utils5 = require("@ai-sdk/provider-utils");
1116
- var imageMediaTypeSignatures = [
1117
- {
1118
- mediaType: "image/gif",
1119
- bytesPrefix: [71, 73, 70],
1120
- base64Prefix: "R0lG"
1121
- },
1122
- {
1123
- mediaType: "image/png",
1124
- bytesPrefix: [137, 80, 78, 71],
1125
- base64Prefix: "iVBORw"
1126
- },
1127
- {
1128
- mediaType: "image/jpeg",
1129
- bytesPrefix: [255, 216],
1130
- base64Prefix: "/9j/"
1131
- },
1132
- {
1133
- mediaType: "image/webp",
1134
- bytesPrefix: [82, 73, 70, 70],
1135
- base64Prefix: "UklGRg"
1136
- },
1137
- {
1138
- mediaType: "image/bmp",
1139
- bytesPrefix: [66, 77],
1140
- base64Prefix: "Qk"
1141
- },
1142
- {
1143
- mediaType: "image/tiff",
1144
- bytesPrefix: [73, 73, 42, 0],
1145
- base64Prefix: "SUkqAA"
1146
- },
1147
- {
1148
- mediaType: "image/tiff",
1149
- bytesPrefix: [77, 77, 0, 42],
1150
- base64Prefix: "TU0AKg"
1151
- },
1152
- {
1153
- mediaType: "image/avif",
1154
- bytesPrefix: [
1155
- 0,
1156
- 0,
1157
- 0,
1158
- 32,
1159
- 102,
1160
- 116,
1161
- 121,
1162
- 112,
1163
- 97,
1164
- 118,
1165
- 105,
1166
- 102
1167
- ],
1168
- base64Prefix: "AAAAIGZ0eXBhdmlm"
1169
- },
1170
- {
1171
- mediaType: "image/heic",
1172
- bytesPrefix: [
1173
- 0,
1174
- 0,
1175
- 0,
1176
- 32,
1177
- 102,
1178
- 116,
1179
- 121,
1180
- 112,
1181
- 104,
1182
- 101,
1183
- 105,
1184
- 99
1185
- ],
1186
- base64Prefix: "AAAAIGZ0eXBoZWlj"
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
+ }
1187
703
  }
1188
- ];
1189
- var stripID3 = (data) => {
1190
- const bytes = typeof data === "string" ? (0, import_provider_utils5.convertBase64ToUint8Array)(data) : data;
1191
- const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
1192
- return bytes.slice(id3Size + 10);
1193
- };
1194
- function stripID3TagsIfPresent(data) {
1195
- const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && // 'I'
1196
- data[1] === 68 && // 'D'
1197
- data[2] === 51;
1198
- return hasId3 ? stripID3(data) : data;
704
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
705
+ return {
706
+ maxRetries: maxRetriesResult,
707
+ retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
708
+ };
1199
709
  }
1200
- function detectMediaType({
1201
- data,
1202
- signatures
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
715
+ function isNonEmptyObject(object) {
716
+ return object != null && Object.keys(object).length > 0;
717
+ }
718
+
719
+ // core/prompt/prepare-tools-and-tool-choice.ts
720
+ function prepareToolsAndToolChoice({
721
+ tools,
722
+ toolChoice,
723
+ activeTools
1203
724
  }) {
1204
- const processedData = stripID3TagsIfPresent(data);
1205
- for (const signature of signatures) {
1206
- if (typeof processedData === "string" ? processedData.startsWith(signature.base64Prefix) : processedData.length >= signature.bytesPrefix.length && signature.bytesPrefix.every(
1207
- (byte, index) => processedData[index] === byte
1208
- )) {
1209
- return signature.mediaType;
1210
- }
725
+ if (!isNonEmptyObject(tools)) {
726
+ return {
727
+ tools: void 0,
728
+ toolChoice: void 0
729
+ };
1211
730
  }
1212
- return void 0;
731
+ const filteredTools = activeTools != null ? Object.entries(tools).filter(
732
+ ([name6]) => activeTools.includes(name6)
733
+ ) : Object.entries(tools);
734
+ return {
735
+ tools: filteredTools.map(([name6, tool]) => {
736
+ const toolType = tool.type;
737
+ switch (toolType) {
738
+ case void 0:
739
+ case "function":
740
+ return {
741
+ type: "function",
742
+ name: name6,
743
+ description: tool.description,
744
+ parameters: (0, import_provider_utils5.asSchema)(tool.parameters).jsonSchema
745
+ };
746
+ case "provider-defined":
747
+ return {
748
+ type: "provider-defined",
749
+ name: name6,
750
+ id: tool.id,
751
+ args: tool.args
752
+ };
753
+ default: {
754
+ const exhaustiveCheck = toolType;
755
+ throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
756
+ }
757
+ }
758
+ }),
759
+ toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
760
+ };
1213
761
  }
1214
762
 
1215
- // core/prompt/invalid-message-role-error.ts
763
+ // core/prompt/standardize-prompt.ts
1216
764
  var import_provider8 = require("@ai-sdk/provider");
1217
- var name5 = "AI_InvalidMessageRoleError";
765
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
766
+ var import_zod7 = require("zod");
767
+
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";
1218
776
  var marker5 = `vercel.ai.error.${name5}`;
1219
777
  var symbol5 = Symbol.for(marker5);
1220
778
  var _a5;
1221
- var InvalidMessageRoleError = class extends import_provider8.AISDKError {
779
+ var MessageConversionError = class extends import_provider7.AISDKError {
1222
780
  constructor({
1223
- role,
1224
- message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
781
+ originalMessage,
782
+ message
1225
783
  }) {
1226
784
  super({ name: name5, message });
1227
785
  this[_a5] = true;
1228
- this.role = role;
786
+ this.originalMessage = originalMessage;
1229
787
  }
1230
788
  static isInstance(error) {
1231
- return import_provider8.AISDKError.hasMarker(error, marker5);
789
+ return import_provider7.AISDKError.hasMarker(error, marker5);
1232
790
  }
1233
791
  };
1234
792
  _a5 = symbol5;
1235
793
 
1236
- // core/prompt/convert-to-language-model-prompt.ts
1237
- async function convertToLanguageModelPrompt({
1238
- prompt,
1239
- supportedUrls,
1240
- downloadImplementation = download
1241
- }) {
1242
- const downloadedAssets = await downloadAssets(
1243
- prompt.messages,
1244
- downloadImplementation,
1245
- supportedUrls
1246
- );
1247
- return [
1248
- ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
1249
- ...prompt.messages.map(
1250
- (message) => convertToLanguageModelMessage(message, downloadedAssets)
1251
- )
1252
- ];
1253
- }
1254
- function convertToLanguageModelMessage(message, downloadedAssets) {
1255
- const role = message.role;
1256
- switch (role) {
1257
- case "system": {
1258
- return {
1259
- role: "system",
1260
- content: message.content,
1261
- providerOptions: message.providerOptions
1262
- };
1263
- }
1264
- case "user": {
1265
- if (typeof message.content === "string") {
1266
- return {
1267
- role: "user",
1268
- content: [{ type: "text", text: message.content }],
1269
- providerOptions: message.providerOptions
1270
- };
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;
1271
807
  }
1272
- return {
1273
- role: "user",
1274
- content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
1275
- providerOptions: message.providerOptions
1276
- };
1277
- }
1278
- case "assistant": {
1279
- if (typeof message.content === "string") {
1280
- return {
1281
- role: "assistant",
1282
- content: [{ type: "text", text: message.content }],
1283
- providerOptions: message.providerOptions
1284
- };
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;
1285
823
  }
1286
- return {
1287
- role: "assistant",
1288
- content: message.content.filter(
1289
- // remove empty text parts:
1290
- (part) => part.type !== "text" || part.text !== ""
1291
- ).map((part) => {
1292
- const providerOptions = part.providerOptions;
1293
- switch (part.type) {
1294
- case "file": {
1295
- const { data, mediaType } = convertToLanguageModelV2DataContent(
1296
- part.data
1297
- );
1298
- return {
1299
- type: "file",
1300
- data,
1301
- filename: part.filename,
1302
- mediaType: mediaType != null ? mediaType : part.mediaType,
1303
- providerOptions
1304
- };
1305
- }
1306
- case "reasoning": {
1307
- return {
1308
- type: "reasoning",
1309
- text: part.text,
1310
- providerOptions
1311
- };
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
+ }
1312
863
  }
1313
- case "text": {
1314
- return {
1315
- type: "text",
1316
- text: part.text,
1317
- providerOptions
1318
- };
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
+ });
1319
899
  }
1320
- case "tool-call": {
1321
- return {
1322
- type: "tool-call",
1323
- toolCallId: part.toolCallId,
1324
- toolName: part.toolName,
1325
- args: part.args,
1326
- providerOptions
1327
- };
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
+ }
1328
930
  }
1329
931
  }
1330
- }),
1331
- providerOptions: message.providerOptions
1332
- };
1333
- }
1334
- case "tool": {
1335
- return {
1336
- role: "tool",
1337
- content: message.content.map((part) => ({
1338
- type: "tool-result",
1339
- toolCallId: part.toolCallId,
1340
- toolName: part.toolName,
1341
- result: part.result,
1342
- content: part.experimental_content,
1343
- isError: part.isError,
1344
- providerOptions: part.providerOptions
1345
- })),
1346
- providerOptions: message.providerOptions
1347
- };
1348
- }
1349
- default: {
1350
- const _exhaustiveCheck = role;
1351
- throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
1352
- }
1353
- }
1354
- }
1355
- async function downloadAssets(messages, downloadImplementation, supportedUrls) {
1356
- const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
1357
- (content) => Array.isArray(content)
1358
- ).flat().filter(
1359
- (part) => part.type === "image" || part.type === "file"
1360
- ).map((part) => {
1361
- var _a6;
1362
- const mediaType = (_a6 = part.mediaType) != null ? _a6 : part.type === "image" ? "image/*" : void 0;
1363
- let data = part.type === "image" ? part.image : part.data;
1364
- if (typeof data === "string") {
1365
- try {
1366
- data = new URL(data);
1367
- } catch (ignored) {
1368
- }
1369
- }
1370
- return { mediaType, data };
1371
- }).filter(
1372
- (part) => part.data instanceof URL && part.mediaType != null && !(0, import_provider_utils6.isUrlSupported)({
1373
- url: part.data.toString(),
1374
- mediaType: part.mediaType,
1375
- supportedUrls
1376
- })
1377
- ).map((part) => part.data);
1378
- const downloadedImages = await Promise.all(
1379
- urls.map(async (url) => ({
1380
- url,
1381
- data: await downloadImplementation({ url })
1382
- }))
1383
- );
1384
- return Object.fromEntries(
1385
- downloadedImages.map(({ url, data }) => [url.toString(), data])
1386
- );
1387
- }
1388
- function convertPartToLanguageModelPart(part, downloadedAssets) {
1389
- var _a6, _b;
1390
- if (part.type === "text") {
1391
- return {
1392
- type: "text",
1393
- text: part.text,
1394
- providerOptions: part.providerOptions
1395
- };
1396
- }
1397
- let originalData;
1398
- const type = part.type;
1399
- switch (type) {
1400
- case "image":
1401
- originalData = part.image;
1402
- break;
1403
- case "file":
1404
- originalData = part.data;
1405
- break;
1406
- default:
1407
- throw new Error(`Unsupported part type: ${type}`);
1408
- }
1409
- const { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV2DataContent(originalData);
1410
- let mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;
1411
- let data = convertedData;
1412
- if (data instanceof URL) {
1413
- const downloadedFile = downloadedAssets[data.toString()];
1414
- if (downloadedFile) {
1415
- data = downloadedFile.data;
1416
- mediaType = (_a6 = downloadedFile.mediaType) != null ? _a6 : mediaType;
1417
- }
1418
- }
1419
- switch (type) {
1420
- case "image": {
1421
- if (data instanceof Uint8Array || typeof data === "string") {
1422
- mediaType = (_b = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _b : mediaType;
1423
- }
1424
- return {
1425
- type: "file",
1426
- mediaType: mediaType != null ? mediaType : "image/*",
1427
- // any image
1428
- filename: void 0,
1429
- data,
1430
- providerOptions: part.providerOptions
1431
- };
1432
- }
1433
- case "file": {
1434
- if (mediaType == null) {
1435
- throw new Error(`Media type is missing for file part`);
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
+ });
1436
943
  }
1437
- return {
1438
- type: "file",
1439
- mediaType,
1440
- filename: part.filename,
1441
- data,
1442
- providerOptions: part.providerOptions
1443
- };
1444
944
  }
1445
945
  }
946
+ return modelMessages;
1446
947
  }
1447
948
 
1448
- // core/types/usage.ts
1449
- function calculateLanguageModelUsage({
1450
- inputTokens,
1451
- outputTokens
1452
- }) {
1453
- return {
1454
- promptTokens: inputTokens != null ? inputTokens : NaN,
1455
- completionTokens: outputTokens != null ? outputTokens : NaN,
1456
- totalTokens: (inputTokens != null ? inputTokens : 0) + (outputTokens != null ? outputTokens : 0)
1457
- };
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
+ }
1458
983
  }
1459
984
 
1460
- // core/util/prepare-response-headers.ts
1461
- function prepareResponseHeaders(headers, {
1462
- contentType,
1463
- dataStreamVersion
985
+ // core/prompt/message.ts
986
+ var import_zod6 = require("zod");
987
+
988
+ // core/types/provider-metadata.ts
989
+ var import_zod3 = require("zod");
990
+
991
+ // core/types/json-value.ts
992
+ var import_zod2 = require("zod");
993
+ var jsonValueSchema = import_zod2.z.lazy(
994
+ () => import_zod2.z.union([
995
+ import_zod2.z.null(),
996
+ import_zod2.z.string(),
997
+ import_zod2.z.number(),
998
+ import_zod2.z.boolean(),
999
+ import_zod2.z.record(import_zod2.z.string(), jsonValueSchema),
1000
+ import_zod2.z.array(jsonValueSchema)
1001
+ ])
1002
+ );
1003
+
1004
+ // core/types/provider-metadata.ts
1005
+ var providerMetadataSchema = import_zod3.z.record(
1006
+ import_zod3.z.string(),
1007
+ import_zod3.z.record(import_zod3.z.string(), jsonValueSchema)
1008
+ );
1009
+
1010
+ // core/prompt/content-part.ts
1011
+ var import_zod5 = require("zod");
1012
+
1013
+ // core/prompt/tool-result-content.ts
1014
+ var import_zod4 = require("zod");
1015
+ var toolResultContentSchema = import_zod4.z.array(
1016
+ import_zod4.z.union([
1017
+ import_zod4.z.object({ type: import_zod4.z.literal("text"), text: import_zod4.z.string() }),
1018
+ import_zod4.z.object({
1019
+ type: import_zod4.z.literal("image"),
1020
+ data: import_zod4.z.string(),
1021
+ mediaType: import_zod4.z.string().optional()
1022
+ })
1023
+ ])
1024
+ );
1025
+
1026
+ // core/prompt/content-part.ts
1027
+ var textPartSchema = import_zod5.z.object({
1028
+ type: import_zod5.z.literal("text"),
1029
+ text: import_zod5.z.string(),
1030
+ providerOptions: providerMetadataSchema.optional()
1031
+ });
1032
+ var imagePartSchema = import_zod5.z.object({
1033
+ type: import_zod5.z.literal("image"),
1034
+ image: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
1035
+ mediaType: import_zod5.z.string().optional(),
1036
+ providerOptions: providerMetadataSchema.optional()
1037
+ });
1038
+ var filePartSchema = import_zod5.z.object({
1039
+ type: import_zod5.z.literal("file"),
1040
+ data: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
1041
+ filename: import_zod5.z.string().optional(),
1042
+ mediaType: import_zod5.z.string(),
1043
+ providerOptions: providerMetadataSchema.optional()
1044
+ });
1045
+ var reasoningPartSchema = import_zod5.z.object({
1046
+ type: import_zod5.z.literal("reasoning"),
1047
+ text: import_zod5.z.string(),
1048
+ providerOptions: providerMetadataSchema.optional()
1049
+ });
1050
+ var toolCallPartSchema = import_zod5.z.object({
1051
+ type: import_zod5.z.literal("tool-call"),
1052
+ toolCallId: import_zod5.z.string(),
1053
+ toolName: import_zod5.z.string(),
1054
+ args: import_zod5.z.unknown(),
1055
+ providerOptions: providerMetadataSchema.optional()
1056
+ });
1057
+ var toolResultPartSchema = import_zod5.z.object({
1058
+ type: import_zod5.z.literal("tool-result"),
1059
+ toolCallId: import_zod5.z.string(),
1060
+ toolName: import_zod5.z.string(),
1061
+ result: import_zod5.z.unknown(),
1062
+ content: toolResultContentSchema.optional(),
1063
+ isError: import_zod5.z.boolean().optional(),
1064
+ providerOptions: providerMetadataSchema.optional()
1065
+ });
1066
+
1067
+ // core/prompt/message.ts
1068
+ var systemModelMessageSchema = import_zod6.z.object(
1069
+ {
1070
+ role: import_zod6.z.literal("system"),
1071
+ content: import_zod6.z.string(),
1072
+ providerOptions: providerMetadataSchema.optional()
1073
+ }
1074
+ );
1075
+ var userModelMessageSchema = import_zod6.z.object({
1076
+ role: import_zod6.z.literal("user"),
1077
+ content: import_zod6.z.union([
1078
+ import_zod6.z.string(),
1079
+ import_zod6.z.array(import_zod6.z.union([textPartSchema, imagePartSchema, filePartSchema]))
1080
+ ]),
1081
+ providerOptions: providerMetadataSchema.optional()
1082
+ });
1083
+ var assistantModelMessageSchema = import_zod6.z.object({
1084
+ role: import_zod6.z.literal("assistant"),
1085
+ content: import_zod6.z.union([
1086
+ import_zod6.z.string(),
1087
+ import_zod6.z.array(
1088
+ import_zod6.z.union([
1089
+ textPartSchema,
1090
+ filePartSchema,
1091
+ reasoningPartSchema,
1092
+ toolCallPartSchema
1093
+ ])
1094
+ )
1095
+ ]),
1096
+ providerOptions: providerMetadataSchema.optional()
1097
+ });
1098
+ var toolModelMessageSchema = import_zod6.z.object({
1099
+ role: import_zod6.z.literal("tool"),
1100
+ content: import_zod6.z.array(toolResultPartSchema),
1101
+ providerOptions: providerMetadataSchema.optional()
1102
+ });
1103
+ var modelMessageSchema = import_zod6.z.union([
1104
+ systemModelMessageSchema,
1105
+ userModelMessageSchema,
1106
+ assistantModelMessageSchema,
1107
+ toolModelMessageSchema
1108
+ ]);
1109
+
1110
+ // core/prompt/standardize-prompt.ts
1111
+ async function standardizePrompt({
1112
+ prompt,
1113
+ tools
1464
1114
  }) {
1465
- const responseHeaders = new Headers(headers != null ? headers : {});
1466
- if (!responseHeaders.has("Content-Type")) {
1467
- responseHeaders.set("Content-Type", contentType);
1115
+ if (prompt.prompt == null && prompt.messages == null) {
1116
+ throw new import_provider8.InvalidPromptError({
1117
+ prompt,
1118
+ message: "prompt or messages must be defined"
1119
+ });
1468
1120
  }
1469
- if (dataStreamVersion !== void 0) {
1470
- responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
1121
+ if (prompt.prompt != null && prompt.messages != null) {
1122
+ throw new import_provider8.InvalidPromptError({
1123
+ prompt,
1124
+ message: "prompt and messages cannot be defined at the same time"
1125
+ });
1471
1126
  }
1472
- return responseHeaders;
1473
- }
1474
-
1475
- // core/util/merge-streams.ts
1476
- function mergeStreams(stream1, stream2) {
1477
- const reader1 = stream1.getReader();
1478
- const reader2 = stream2.getReader();
1479
- let lastRead1 = void 0;
1480
- let lastRead2 = void 0;
1481
- let stream1Done = false;
1482
- let stream2Done = false;
1483
- async function readStream1(controller) {
1484
- try {
1485
- if (lastRead1 == null) {
1486
- lastRead1 = reader1.read();
1487
- }
1488
- const result = await lastRead1;
1489
- lastRead1 = void 0;
1490
- if (!result.done) {
1491
- controller.enqueue(result.value);
1492
- } else {
1493
- controller.close();
1494
- }
1495
- } catch (error) {
1496
- controller.error(error);
1497
- }
1127
+ if (prompt.system != null && typeof prompt.system !== "string") {
1128
+ throw new import_provider8.InvalidPromptError({
1129
+ prompt,
1130
+ message: "system must be a string"
1131
+ });
1498
1132
  }
1499
- async function readStream2(controller) {
1500
- try {
1501
- if (lastRead2 == null) {
1502
- lastRead2 = reader2.read();
1503
- }
1504
- const result = await lastRead2;
1505
- lastRead2 = void 0;
1506
- if (!result.done) {
1507
- controller.enqueue(result.value);
1508
- } else {
1509
- controller.close();
1510
- }
1511
- } catch (error) {
1512
- controller.error(error);
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
+ });
1513
1139
  }
1514
- }
1515
- return new ReadableStream({
1516
- async pull(controller) {
1517
- try {
1518
- if (stream1Done) {
1519
- await readStream2(controller);
1520
- return;
1521
- }
1522
- if (stream2Done) {
1523
- await readStream1(controller);
1524
- return;
1525
- }
1526
- if (lastRead1 == null) {
1527
- lastRead1 = reader1.read();
1528
- }
1529
- if (lastRead2 == null) {
1530
- lastRead2 = reader2.read();
1531
- }
1532
- const { result, reader } = await Promise.race([
1533
- lastRead1.then((result2) => ({ result: result2, reader: reader1 })),
1534
- lastRead2.then((result2) => ({ result: result2, reader: reader2 }))
1535
- ]);
1536
- if (!result.done) {
1537
- controller.enqueue(result.value);
1538
- }
1539
- if (reader === reader1) {
1540
- lastRead1 = void 0;
1541
- if (result.done) {
1542
- await readStream2(controller);
1543
- stream1Done = true;
1544
- }
1545
- } else {
1546
- lastRead2 = void 0;
1547
- if (result.done) {
1548
- stream2Done = true;
1549
- await readStream1(controller);
1550
- }
1140
+ return {
1141
+ system: prompt.system,
1142
+ messages: [
1143
+ {
1144
+ role: "user",
1145
+ content: prompt.prompt
1551
1146
  }
1552
- } catch (error) {
1553
- controller.error(error);
1554
- }
1555
- },
1556
- cancel() {
1557
- reader1.cancel();
1558
- reader2.cancel();
1147
+ ]
1148
+ };
1149
+ }
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
+ });
1559
1157
  }
1560
- });
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
+ });
1166
+ }
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
1176
+ });
1177
+ }
1178
+ return {
1179
+ messages,
1180
+ system: prompt.system
1181
+ };
1182
+ }
1183
+ throw new Error("unreachable");
1561
1184
  }
1562
1185
 
1563
1186
  // streams/stream-callbacks.ts
1564
1187
  function createCallbacksTransformer(callbacks = {}) {
1565
- const textEncoder = new TextEncoder();
1566
1188
  let aggregatedResponse = "";
1567
1189
  return new TransformStream({
1568
1190
  async start() {
@@ -1570,7 +1192,7 @@ function createCallbacksTransformer(callbacks = {}) {
1570
1192
  await callbacks.onStart();
1571
1193
  },
1572
1194
  async transform(message, controller) {
1573
- controller.enqueue(textEncoder.encode(message));
1195
+ controller.enqueue(message);
1574
1196
  aggregatedResponse += message;
1575
1197
  if (callbacks.onToken)
1576
1198
  await callbacks.onToken(message);
@@ -1579,9 +1201,6 @@ function createCallbacksTransformer(callbacks = {}) {
1579
1201
  }
1580
1202
  },
1581
1203
  async flush() {
1582
- if (callbacks.onCompletion) {
1583
- await callbacks.onCompletion(aggregatedResponse);
1584
- }
1585
1204
  if (callbacks.onFinal) {
1586
1205
  await callbacks.onFinal(aggregatedResponse);
1587
1206
  }
@@ -1591,80 +1210,12 @@ function createCallbacksTransformer(callbacks = {}) {
1591
1210
 
1592
1211
  // util/constants.ts
1593
1212
  var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
1594
-
1595
- // streams/stream-data.ts
1596
- var StreamData = class {
1597
- constructor() {
1598
- this.encoder = new TextEncoder();
1599
- this.controller = null;
1600
- this.isClosed = false;
1601
- this.warningTimeout = null;
1602
- const self = this;
1603
- this.stream = new ReadableStream({
1604
- start: async (controller) => {
1605
- self.controller = controller;
1606
- if (process.env.NODE_ENV === "development") {
1607
- self.warningTimeout = setTimeout(() => {
1608
- console.warn(
1609
- "The data stream is hanging. Did you forget to close it with `data.close()`?"
1610
- );
1611
- }, HANGING_STREAM_WARNING_TIME_MS);
1612
- }
1613
- },
1614
- pull: (controller) => {
1615
- },
1616
- cancel: (reason) => {
1617
- this.isClosed = true;
1618
- }
1619
- });
1620
- }
1621
- async close() {
1622
- if (this.isClosed) {
1623
- throw new Error("Data Stream has already been closed.");
1624
- }
1625
- if (!this.controller) {
1626
- throw new Error("Stream controller is not initialized.");
1627
- }
1628
- this.controller.close();
1629
- this.isClosed = true;
1630
- if (this.warningTimeout) {
1631
- clearTimeout(this.warningTimeout);
1632
- }
1633
- }
1634
- append(value) {
1635
- if (this.isClosed) {
1636
- throw new Error("Data Stream has already been closed.");
1637
- }
1638
- if (!this.controller) {
1639
- throw new Error("Stream controller is not initialized.");
1640
- }
1641
- this.controller.enqueue(
1642
- this.encoder.encode(formatDataStreamPart("data", [value]))
1643
- );
1644
- }
1645
- appendMessageAnnotation(value) {
1646
- if (this.isClosed) {
1647
- throw new Error("Data Stream has already been closed.");
1648
- }
1649
- if (!this.controller) {
1650
- throw new Error("Stream controller is not initialized.");
1651
- }
1652
- this.controller.enqueue(
1653
- this.encoder.encode(formatDataStreamPart("message_annotations", [value]))
1654
- );
1655
- }
1656
- };
1657
1213
  // Annotate the CommonJS export names for ESM import in node:
1658
1214
  0 && (module.exports = {
1659
1215
  HANGING_STREAM_WARNING_TIME_MS,
1660
- StreamData,
1661
- calculateLanguageModelUsage,
1662
1216
  convertToLanguageModelPrompt,
1663
1217
  createCallbacksTransformer,
1664
- formatDataStreamPart,
1665
- mergeStreams,
1666
1218
  prepareCallSettings,
1667
- prepareResponseHeaders,
1668
1219
  prepareRetries,
1669
1220
  prepareToolsAndToolChoice,
1670
1221
  standardizePrompt