ai 5.0.0-canary.3 → 5.0.0-canary.4

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.
@@ -0,0 +1,1429 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name7 in all)
8
+ __defProp(target, name7, { get: all[name7], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // internal/index.ts
21
+ var internal_exports = {};
22
+ __export(internal_exports, {
23
+ HANGING_STREAM_WARNING_TIME_MS: () => HANGING_STREAM_WARNING_TIME_MS,
24
+ calculateLanguageModelUsage: () => calculateLanguageModelUsage,
25
+ convertToLanguageModelPrompt: () => convertToLanguageModelPrompt,
26
+ prepareCallSettings: () => prepareCallSettings,
27
+ prepareRetries: () => prepareRetries,
28
+ prepareToolsAndToolChoice: () => prepareToolsAndToolChoice,
29
+ standardizePrompt: () => standardizePrompt
30
+ });
31
+ module.exports = __toCommonJS(internal_exports);
32
+
33
+ // core/prompt/standardize-prompt.ts
34
+ var import_provider3 = require("@ai-sdk/provider");
35
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
36
+ var import_zod7 = require("zod");
37
+
38
+ // core/prompt/data-content.ts
39
+ var import_provider_utils = require("@ai-sdk/provider-utils");
40
+
41
+ // core/prompt/invalid-data-content-error.ts
42
+ var import_provider = require("@ai-sdk/provider");
43
+ var name = "AI_InvalidDataContentError";
44
+ var marker = `vercel.ai.error.${name}`;
45
+ var symbol = Symbol.for(marker);
46
+ var _a;
47
+ var InvalidDataContentError = class extends import_provider.AISDKError {
48
+ constructor({
49
+ content,
50
+ cause,
51
+ message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
52
+ }) {
53
+ super({ name, message, cause });
54
+ this[_a] = true;
55
+ this.content = content;
56
+ }
57
+ static isInstance(error) {
58
+ return import_provider.AISDKError.hasMarker(error, marker);
59
+ }
60
+ };
61
+ _a = symbol;
62
+
63
+ // core/prompt/data-content.ts
64
+ var import_zod = require("zod");
65
+ var dataContentSchema = import_zod.z.union([
66
+ import_zod.z.string(),
67
+ import_zod.z.instanceof(Uint8Array),
68
+ import_zod.z.instanceof(ArrayBuffer),
69
+ import_zod.z.custom(
70
+ // Buffer might not be available in some environments such as CloudFlare:
71
+ (value) => {
72
+ var _a7, _b;
73
+ return (_b = (_a7 = globalThis.Buffer) == null ? void 0 : _a7.isBuffer(value)) != null ? _b : false;
74
+ },
75
+ { message: "Must be a Buffer" }
76
+ )
77
+ ]);
78
+ function convertDataContentToBase64String(content) {
79
+ if (typeof content === "string") {
80
+ return content;
81
+ }
82
+ if (content instanceof ArrayBuffer) {
83
+ return (0, import_provider_utils.convertUint8ArrayToBase64)(new Uint8Array(content));
84
+ }
85
+ return (0, import_provider_utils.convertUint8ArrayToBase64)(content);
86
+ }
87
+ function convertDataContentToUint8Array(content) {
88
+ if (content instanceof Uint8Array) {
89
+ return content;
90
+ }
91
+ if (typeof content === "string") {
92
+ try {
93
+ return (0, import_provider_utils.convertBase64ToUint8Array)(content);
94
+ } catch (error) {
95
+ throw new InvalidDataContentError({
96
+ message: "Invalid data content. Content string is not a base64-encoded media.",
97
+ content,
98
+ cause: error
99
+ });
100
+ }
101
+ }
102
+ if (content instanceof ArrayBuffer) {
103
+ return new Uint8Array(content);
104
+ }
105
+ throw new InvalidDataContentError({ content });
106
+ }
107
+ function convertUint8ArrayToText(uint8Array) {
108
+ try {
109
+ return new TextDecoder().decode(uint8Array);
110
+ } catch (error) {
111
+ throw new Error("Error decoding Uint8Array to text");
112
+ }
113
+ }
114
+
115
+ // core/prompt/attachments-to-parts.ts
116
+ function attachmentsToParts(attachments) {
117
+ var _a7, _b, _c;
118
+ const parts = [];
119
+ for (const attachment of attachments) {
120
+ let url;
121
+ try {
122
+ url = new URL(attachment.url);
123
+ } catch (error) {
124
+ throw new Error(`Invalid URL: ${attachment.url}`);
125
+ }
126
+ switch (url.protocol) {
127
+ case "http:":
128
+ case "https:": {
129
+ if ((_a7 = attachment.contentType) == null ? void 0 : _a7.startsWith("image/")) {
130
+ parts.push({ type: "image", image: url });
131
+ } else {
132
+ if (!attachment.contentType) {
133
+ throw new Error(
134
+ "If the attachment is not an image, it must specify a content type"
135
+ );
136
+ }
137
+ parts.push({
138
+ type: "file",
139
+ data: url,
140
+ mediaType: attachment.contentType
141
+ });
142
+ }
143
+ break;
144
+ }
145
+ case "data:": {
146
+ let header;
147
+ let base64Content;
148
+ let mediaType;
149
+ try {
150
+ [header, base64Content] = attachment.url.split(",");
151
+ mediaType = header.split(";")[0].split(":")[1];
152
+ } catch (error) {
153
+ throw new Error(`Error processing data URL: ${attachment.url}`);
154
+ }
155
+ if (mediaType == null || base64Content == null) {
156
+ throw new Error(`Invalid data URL format: ${attachment.url}`);
157
+ }
158
+ if ((_b = attachment.contentType) == null ? void 0 : _b.startsWith("image/")) {
159
+ parts.push({
160
+ type: "image",
161
+ image: convertDataContentToUint8Array(base64Content)
162
+ });
163
+ } else if ((_c = attachment.contentType) == null ? void 0 : _c.startsWith("text/")) {
164
+ parts.push({
165
+ type: "text",
166
+ text: convertUint8ArrayToText(
167
+ convertDataContentToUint8Array(base64Content)
168
+ )
169
+ });
170
+ } else {
171
+ if (!attachment.contentType) {
172
+ throw new Error(
173
+ "If the attachment is not an image or text, it must specify a content type"
174
+ );
175
+ }
176
+ parts.push({
177
+ type: "file",
178
+ data: base64Content,
179
+ mediaType: attachment.contentType
180
+ });
181
+ }
182
+ break;
183
+ }
184
+ default: {
185
+ throw new Error(`Unsupported URL protocol: ${url.protocol}`);
186
+ }
187
+ }
188
+ }
189
+ return parts;
190
+ }
191
+
192
+ // core/prompt/message-conversion-error.ts
193
+ var import_provider2 = require("@ai-sdk/provider");
194
+ var name2 = "AI_MessageConversionError";
195
+ var marker2 = `vercel.ai.error.${name2}`;
196
+ var symbol2 = Symbol.for(marker2);
197
+ var _a2;
198
+ var MessageConversionError = class extends import_provider2.AISDKError {
199
+ constructor({
200
+ originalMessage,
201
+ message
202
+ }) {
203
+ super({ name: name2, message });
204
+ this[_a2] = true;
205
+ this.originalMessage = originalMessage;
206
+ }
207
+ static isInstance(error) {
208
+ return import_provider2.AISDKError.hasMarker(error, marker2);
209
+ }
210
+ };
211
+ _a2 = symbol2;
212
+
213
+ // core/prompt/convert-to-core-messages.ts
214
+ function convertToCoreMessages(messages, options) {
215
+ var _a7, _b;
216
+ const tools = (_a7 = options == null ? void 0 : options.tools) != null ? _a7 : {};
217
+ const coreMessages = [];
218
+ for (let i = 0; i < messages.length; i++) {
219
+ const message = messages[i];
220
+ const isLastMessage = i === messages.length - 1;
221
+ const { role, content, experimental_attachments } = message;
222
+ switch (role) {
223
+ case "system": {
224
+ coreMessages.push({
225
+ role: "system",
226
+ content
227
+ });
228
+ break;
229
+ }
230
+ case "user": {
231
+ if (message.parts == null) {
232
+ coreMessages.push({
233
+ role: "user",
234
+ content: experimental_attachments ? [
235
+ { type: "text", text: content },
236
+ ...attachmentsToParts(experimental_attachments)
237
+ ] : content
238
+ });
239
+ } else {
240
+ const textParts = message.parts.filter((part) => part.type === "text").map((part) => ({
241
+ type: "text",
242
+ text: part.text
243
+ }));
244
+ coreMessages.push({
245
+ role: "user",
246
+ content: experimental_attachments ? [...textParts, ...attachmentsToParts(experimental_attachments)] : textParts
247
+ });
248
+ }
249
+ break;
250
+ }
251
+ case "assistant": {
252
+ if (message.parts != null) {
253
+ let processBlock2 = function() {
254
+ var _a8;
255
+ const content2 = [];
256
+ for (const part of block) {
257
+ switch (part.type) {
258
+ case "text": {
259
+ content2.push(part);
260
+ break;
261
+ }
262
+ case "file": {
263
+ content2.push({
264
+ type: "file",
265
+ data: part.data,
266
+ mediaType: (_a8 = part.mediaType) != null ? _a8 : part.mimeType
267
+ // TODO migration, remove
268
+ });
269
+ break;
270
+ }
271
+ case "reasoning": {
272
+ for (const detail of part.details) {
273
+ switch (detail.type) {
274
+ case "text":
275
+ content2.push({
276
+ type: "reasoning",
277
+ text: detail.text,
278
+ signature: detail.signature
279
+ });
280
+ break;
281
+ case "redacted":
282
+ content2.push({
283
+ type: "redacted-reasoning",
284
+ data: detail.data
285
+ });
286
+ break;
287
+ }
288
+ }
289
+ break;
290
+ }
291
+ case "tool-invocation":
292
+ content2.push({
293
+ type: "tool-call",
294
+ toolCallId: part.toolInvocation.toolCallId,
295
+ toolName: part.toolInvocation.toolName,
296
+ args: part.toolInvocation.args
297
+ });
298
+ break;
299
+ default: {
300
+ const _exhaustiveCheck = part;
301
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
302
+ }
303
+ }
304
+ }
305
+ coreMessages.push({
306
+ role: "assistant",
307
+ content: content2
308
+ });
309
+ const stepInvocations = block.filter(
310
+ (part) => part.type === "tool-invocation"
311
+ ).map((part) => part.toolInvocation);
312
+ if (stepInvocations.length > 0) {
313
+ coreMessages.push({
314
+ role: "tool",
315
+ content: stepInvocations.map(
316
+ (toolInvocation) => {
317
+ if (!("result" in toolInvocation)) {
318
+ throw new MessageConversionError({
319
+ originalMessage: message,
320
+ message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
321
+ });
322
+ }
323
+ const { toolCallId, toolName, result } = toolInvocation;
324
+ const tool = tools[toolName];
325
+ return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
326
+ type: "tool-result",
327
+ toolCallId,
328
+ toolName,
329
+ result: tool.experimental_toToolResultContent(result),
330
+ experimental_content: tool.experimental_toToolResultContent(result)
331
+ } : {
332
+ type: "tool-result",
333
+ toolCallId,
334
+ toolName,
335
+ result
336
+ };
337
+ }
338
+ )
339
+ });
340
+ }
341
+ block = [];
342
+ blockHasToolInvocations = false;
343
+ currentStep++;
344
+ };
345
+ var processBlock = processBlock2;
346
+ let currentStep = 0;
347
+ let blockHasToolInvocations = false;
348
+ let block = [];
349
+ for (const part of message.parts) {
350
+ switch (part.type) {
351
+ case "text": {
352
+ if (blockHasToolInvocations) {
353
+ processBlock2();
354
+ }
355
+ block.push(part);
356
+ break;
357
+ }
358
+ case "file":
359
+ case "reasoning": {
360
+ block.push(part);
361
+ break;
362
+ }
363
+ case "tool-invocation": {
364
+ if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
365
+ processBlock2();
366
+ }
367
+ block.push(part);
368
+ blockHasToolInvocations = true;
369
+ break;
370
+ }
371
+ }
372
+ }
373
+ processBlock2();
374
+ break;
375
+ }
376
+ const toolInvocations = message.toolInvocations;
377
+ if (toolInvocations == null || toolInvocations.length === 0) {
378
+ coreMessages.push({ role: "assistant", content });
379
+ break;
380
+ }
381
+ const maxStep = toolInvocations.reduce((max, toolInvocation) => {
382
+ var _a8;
383
+ return Math.max(max, (_a8 = toolInvocation.step) != null ? _a8 : 0);
384
+ }, 0);
385
+ for (let i2 = 0; i2 <= maxStep; i2++) {
386
+ const stepInvocations = toolInvocations.filter(
387
+ (toolInvocation) => {
388
+ var _a8;
389
+ return ((_a8 = toolInvocation.step) != null ? _a8 : 0) === i2;
390
+ }
391
+ );
392
+ if (stepInvocations.length === 0) {
393
+ continue;
394
+ }
395
+ coreMessages.push({
396
+ role: "assistant",
397
+ content: [
398
+ ...isLastMessage && content && i2 === 0 ? [{ type: "text", text: content }] : [],
399
+ ...stepInvocations.map(
400
+ ({ toolCallId, toolName, args }) => ({
401
+ type: "tool-call",
402
+ toolCallId,
403
+ toolName,
404
+ args
405
+ })
406
+ )
407
+ ]
408
+ });
409
+ coreMessages.push({
410
+ role: "tool",
411
+ content: stepInvocations.map((toolInvocation) => {
412
+ if (!("result" in toolInvocation)) {
413
+ throw new MessageConversionError({
414
+ originalMessage: message,
415
+ message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
416
+ });
417
+ }
418
+ const { toolCallId, toolName, result } = toolInvocation;
419
+ const tool = tools[toolName];
420
+ return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
421
+ type: "tool-result",
422
+ toolCallId,
423
+ toolName,
424
+ result: tool.experimental_toToolResultContent(result),
425
+ experimental_content: tool.experimental_toToolResultContent(result)
426
+ } : {
427
+ type: "tool-result",
428
+ toolCallId,
429
+ toolName,
430
+ result
431
+ };
432
+ })
433
+ });
434
+ }
435
+ if (content && !isLastMessage) {
436
+ coreMessages.push({ role: "assistant", content });
437
+ }
438
+ break;
439
+ }
440
+ case "data": {
441
+ break;
442
+ }
443
+ default: {
444
+ const _exhaustiveCheck = role;
445
+ throw new MessageConversionError({
446
+ originalMessage: message,
447
+ message: `Unsupported role: ${_exhaustiveCheck}`
448
+ });
449
+ }
450
+ }
451
+ }
452
+ return coreMessages;
453
+ }
454
+
455
+ // core/prompt/detect-prompt-type.ts
456
+ function detectPromptType(prompt) {
457
+ if (!Array.isArray(prompt)) {
458
+ return "other";
459
+ }
460
+ if (prompt.length === 0) {
461
+ return "messages";
462
+ }
463
+ const characteristics = prompt.map(detectSingleMessageCharacteristics);
464
+ if (characteristics.some((c) => c === "has-ui-specific-parts")) {
465
+ return "ui-messages";
466
+ } else if (characteristics.every(
467
+ (c) => c === "has-core-specific-parts" || c === "message"
468
+ )) {
469
+ return "messages";
470
+ } else {
471
+ return "other";
472
+ }
473
+ }
474
+ function detectSingleMessageCharacteristics(message) {
475
+ if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
476
+ message.role === "data" || // UI-only role
477
+ "toolInvocations" in message || // UI-specific field
478
+ "parts" in message || // UI-specific field
479
+ "experimental_attachments" in message)) {
480
+ return "has-ui-specific-parts";
481
+ } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
482
+ "experimental_providerMetadata" in message || "providerOptions" in message)) {
483
+ return "has-core-specific-parts";
484
+ } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
485
+ return "message";
486
+ } else {
487
+ return "other";
488
+ }
489
+ }
490
+
491
+ // core/prompt/message.ts
492
+ var import_zod6 = require("zod");
493
+
494
+ // core/types/provider-metadata.ts
495
+ var import_zod3 = require("zod");
496
+
497
+ // core/types/json-value.ts
498
+ var import_zod2 = require("zod");
499
+ var jsonValueSchema = import_zod2.z.lazy(
500
+ () => import_zod2.z.union([
501
+ import_zod2.z.null(),
502
+ import_zod2.z.string(),
503
+ import_zod2.z.number(),
504
+ import_zod2.z.boolean(),
505
+ import_zod2.z.record(import_zod2.z.string(), jsonValueSchema),
506
+ import_zod2.z.array(jsonValueSchema)
507
+ ])
508
+ );
509
+
510
+ // core/types/provider-metadata.ts
511
+ var providerMetadataSchema = import_zod3.z.record(
512
+ import_zod3.z.string(),
513
+ import_zod3.z.record(import_zod3.z.string(), jsonValueSchema)
514
+ );
515
+
516
+ // core/prompt/content-part.ts
517
+ var import_zod5 = require("zod");
518
+
519
+ // core/prompt/tool-result-content.ts
520
+ var import_zod4 = require("zod");
521
+ var toolResultContentSchema = import_zod4.z.array(
522
+ import_zod4.z.union([
523
+ import_zod4.z.object({ type: import_zod4.z.literal("text"), text: import_zod4.z.string() }),
524
+ import_zod4.z.object({
525
+ type: import_zod4.z.literal("image"),
526
+ data: import_zod4.z.string(),
527
+ mediaType: import_zod4.z.string().optional()
528
+ })
529
+ ])
530
+ );
531
+
532
+ // core/prompt/content-part.ts
533
+ var textPartSchema = import_zod5.z.object({
534
+ type: import_zod5.z.literal("text"),
535
+ text: import_zod5.z.string(),
536
+ providerOptions: providerMetadataSchema.optional(),
537
+ experimental_providerMetadata: providerMetadataSchema.optional()
538
+ });
539
+ var imagePartSchema = import_zod5.z.object({
540
+ type: import_zod5.z.literal("image"),
541
+ image: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
542
+ mediaType: import_zod5.z.string().optional(),
543
+ mimeType: import_zod5.z.string().optional(),
544
+ providerOptions: providerMetadataSchema.optional(),
545
+ experimental_providerMetadata: providerMetadataSchema.optional()
546
+ });
547
+ var filePartSchema = import_zod5.z.object({
548
+ type: import_zod5.z.literal("file"),
549
+ data: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
550
+ filename: import_zod5.z.string().optional(),
551
+ mediaType: import_zod5.z.string(),
552
+ mimeType: import_zod5.z.string().optional(),
553
+ providerOptions: providerMetadataSchema.optional(),
554
+ experimental_providerMetadata: providerMetadataSchema.optional()
555
+ });
556
+ var reasoningPartSchema = import_zod5.z.object({
557
+ type: import_zod5.z.literal("reasoning"),
558
+ text: import_zod5.z.string(),
559
+ providerOptions: providerMetadataSchema.optional(),
560
+ experimental_providerMetadata: providerMetadataSchema.optional()
561
+ });
562
+ var redactedReasoningPartSchema = import_zod5.z.object({
563
+ type: import_zod5.z.literal("redacted-reasoning"),
564
+ data: import_zod5.z.string(),
565
+ providerOptions: providerMetadataSchema.optional(),
566
+ experimental_providerMetadata: providerMetadataSchema.optional()
567
+ });
568
+ var toolCallPartSchema = import_zod5.z.object({
569
+ type: import_zod5.z.literal("tool-call"),
570
+ toolCallId: import_zod5.z.string(),
571
+ toolName: import_zod5.z.string(),
572
+ args: import_zod5.z.unknown(),
573
+ providerOptions: providerMetadataSchema.optional(),
574
+ experimental_providerMetadata: providerMetadataSchema.optional()
575
+ });
576
+ var toolResultPartSchema = import_zod5.z.object({
577
+ type: import_zod5.z.literal("tool-result"),
578
+ toolCallId: import_zod5.z.string(),
579
+ toolName: import_zod5.z.string(),
580
+ result: import_zod5.z.unknown(),
581
+ content: toolResultContentSchema.optional(),
582
+ isError: import_zod5.z.boolean().optional(),
583
+ providerOptions: providerMetadataSchema.optional(),
584
+ experimental_providerMetadata: providerMetadataSchema.optional()
585
+ });
586
+
587
+ // core/prompt/message.ts
588
+ var coreSystemMessageSchema = import_zod6.z.object({
589
+ role: import_zod6.z.literal("system"),
590
+ content: import_zod6.z.string(),
591
+ providerOptions: providerMetadataSchema.optional(),
592
+ experimental_providerMetadata: providerMetadataSchema.optional()
593
+ });
594
+ var coreUserMessageSchema = import_zod6.z.object({
595
+ role: import_zod6.z.literal("user"),
596
+ content: import_zod6.z.union([
597
+ import_zod6.z.string(),
598
+ import_zod6.z.array(import_zod6.z.union([textPartSchema, imagePartSchema, filePartSchema]))
599
+ ]),
600
+ providerOptions: providerMetadataSchema.optional(),
601
+ experimental_providerMetadata: providerMetadataSchema.optional()
602
+ });
603
+ var coreAssistantMessageSchema = import_zod6.z.object({
604
+ role: import_zod6.z.literal("assistant"),
605
+ content: import_zod6.z.union([
606
+ import_zod6.z.string(),
607
+ import_zod6.z.array(
608
+ import_zod6.z.union([
609
+ textPartSchema,
610
+ filePartSchema,
611
+ reasoningPartSchema,
612
+ redactedReasoningPartSchema,
613
+ toolCallPartSchema
614
+ ])
615
+ )
616
+ ]),
617
+ providerOptions: providerMetadataSchema.optional(),
618
+ experimental_providerMetadata: providerMetadataSchema.optional()
619
+ });
620
+ var coreToolMessageSchema = import_zod6.z.object({
621
+ role: import_zod6.z.literal("tool"),
622
+ content: import_zod6.z.array(toolResultPartSchema),
623
+ providerOptions: providerMetadataSchema.optional(),
624
+ experimental_providerMetadata: providerMetadataSchema.optional()
625
+ });
626
+ var coreMessageSchema = import_zod6.z.union([
627
+ coreSystemMessageSchema,
628
+ coreUserMessageSchema,
629
+ coreAssistantMessageSchema,
630
+ coreToolMessageSchema
631
+ ]);
632
+
633
+ // core/prompt/standardize-prompt.ts
634
+ function standardizePrompt({
635
+ prompt,
636
+ tools
637
+ }) {
638
+ if (prompt.prompt == null && prompt.messages == null) {
639
+ throw new import_provider3.InvalidPromptError({
640
+ prompt,
641
+ message: "prompt or messages must be defined"
642
+ });
643
+ }
644
+ if (prompt.prompt != null && prompt.messages != null) {
645
+ throw new import_provider3.InvalidPromptError({
646
+ prompt,
647
+ message: "prompt and messages cannot be defined at the same time"
648
+ });
649
+ }
650
+ if (prompt.system != null && typeof prompt.system !== "string") {
651
+ throw new import_provider3.InvalidPromptError({
652
+ prompt,
653
+ message: "system must be a string"
654
+ });
655
+ }
656
+ if (prompt.prompt != null) {
657
+ if (typeof prompt.prompt !== "string") {
658
+ throw new import_provider3.InvalidPromptError({
659
+ prompt,
660
+ message: "prompt must be a string"
661
+ });
662
+ }
663
+ return {
664
+ type: "prompt",
665
+ system: prompt.system,
666
+ messages: [
667
+ {
668
+ role: "user",
669
+ content: prompt.prompt
670
+ }
671
+ ]
672
+ };
673
+ }
674
+ if (prompt.messages != null) {
675
+ const promptType = detectPromptType(prompt.messages);
676
+ if (promptType === "other") {
677
+ throw new import_provider3.InvalidPromptError({
678
+ prompt,
679
+ message: "messages must be an array of CoreMessage or UIMessage"
680
+ });
681
+ }
682
+ const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
683
+ tools
684
+ }) : prompt.messages;
685
+ if (messages.length === 0) {
686
+ throw new import_provider3.InvalidPromptError({
687
+ prompt,
688
+ message: "messages must not be empty"
689
+ });
690
+ }
691
+ const validationResult = (0, import_provider_utils2.safeValidateTypes)({
692
+ value: messages,
693
+ schema: import_zod7.z.array(coreMessageSchema)
694
+ });
695
+ if (!validationResult.success) {
696
+ throw new import_provider3.InvalidPromptError({
697
+ prompt,
698
+ message: "messages must be an array of CoreMessage or UIMessage",
699
+ cause: validationResult.error
700
+ });
701
+ }
702
+ return {
703
+ type: "messages",
704
+ messages,
705
+ system: prompt.system
706
+ };
707
+ }
708
+ throw new Error("unreachable");
709
+ }
710
+
711
+ // core/prompt/prepare-tools-and-tool-choice.ts
712
+ var import_ui_utils = require("@ai-sdk/ui-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
724
+ }) {
725
+ if (!isNonEmptyObject(tools)) {
726
+ return {
727
+ tools: void 0,
728
+ toolChoice: void 0
729
+ };
730
+ }
731
+ const filteredTools = activeTools != null ? Object.entries(tools).filter(
732
+ ([name7]) => activeTools.includes(name7)
733
+ ) : Object.entries(tools);
734
+ return {
735
+ tools: filteredTools.map(([name7, tool]) => {
736
+ const toolType = tool.type;
737
+ switch (toolType) {
738
+ case void 0:
739
+ case "function":
740
+ return {
741
+ type: "function",
742
+ name: name7,
743
+ description: tool.description,
744
+ parameters: (0, import_ui_utils.asSchema)(tool.parameters).jsonSchema
745
+ };
746
+ case "provider-defined":
747
+ return {
748
+ type: "provider-defined",
749
+ name: name7,
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
+ };
761
+ }
762
+
763
+ // errors/invalid-argument-error.ts
764
+ var import_provider4 = require("@ai-sdk/provider");
765
+ var name3 = "AI_InvalidArgumentError";
766
+ var marker3 = `vercel.ai.error.${name3}`;
767
+ var symbol3 = Symbol.for(marker3);
768
+ var _a3;
769
+ var InvalidArgumentError = class extends import_provider4.AISDKError {
770
+ constructor({
771
+ parameter,
772
+ value,
773
+ message
774
+ }) {
775
+ super({
776
+ name: name3,
777
+ message: `Invalid argument for parameter ${parameter}: ${message}`
778
+ });
779
+ this[_a3] = true;
780
+ this.parameter = parameter;
781
+ this.value = value;
782
+ }
783
+ static isInstance(error) {
784
+ return import_provider4.AISDKError.hasMarker(error, marker3);
785
+ }
786
+ };
787
+ _a3 = symbol3;
788
+
789
+ // util/retry-with-exponential-backoff.ts
790
+ var import_provider6 = require("@ai-sdk/provider");
791
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
792
+
793
+ // util/retry-error.ts
794
+ var import_provider5 = require("@ai-sdk/provider");
795
+ var name4 = "AI_RetryError";
796
+ var marker4 = `vercel.ai.error.${name4}`;
797
+ var symbol4 = Symbol.for(marker4);
798
+ var _a4;
799
+ var RetryError = class extends import_provider5.AISDKError {
800
+ constructor({
801
+ message,
802
+ reason,
803
+ errors
804
+ }) {
805
+ super({ name: name4, message });
806
+ this[_a4] = true;
807
+ this.reason = reason;
808
+ this.errors = errors;
809
+ this.lastError = errors[errors.length - 1];
810
+ }
811
+ static isInstance(error) {
812
+ return import_provider5.AISDKError.hasMarker(error, marker4);
813
+ }
814
+ };
815
+ _a4 = symbol4;
816
+
817
+ // util/retry-with-exponential-backoff.ts
818
+ var retryWithExponentialBackoff = ({
819
+ maxRetries = 2,
820
+ initialDelayInMs = 2e3,
821
+ backoffFactor = 2
822
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
823
+ maxRetries,
824
+ delayInMs: initialDelayInMs,
825
+ backoffFactor
826
+ });
827
+ async function _retryWithExponentialBackoff(f, {
828
+ maxRetries,
829
+ delayInMs,
830
+ backoffFactor
831
+ }, errors = []) {
832
+ try {
833
+ return await f();
834
+ } catch (error) {
835
+ if ((0, import_provider_utils3.isAbortError)(error)) {
836
+ throw error;
837
+ }
838
+ if (maxRetries === 0) {
839
+ throw error;
840
+ }
841
+ const errorMessage = (0, import_provider_utils3.getErrorMessage)(error);
842
+ const newErrors = [...errors, error];
843
+ const tryNumber = newErrors.length;
844
+ if (tryNumber > maxRetries) {
845
+ throw new RetryError({
846
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
847
+ reason: "maxRetriesExceeded",
848
+ errors: newErrors
849
+ });
850
+ }
851
+ if (error instanceof Error && import_provider6.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
852
+ await (0, import_provider_utils3.delay)(delayInMs);
853
+ return _retryWithExponentialBackoff(
854
+ f,
855
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
856
+ newErrors
857
+ );
858
+ }
859
+ if (tryNumber === 1) {
860
+ throw error;
861
+ }
862
+ throw new RetryError({
863
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
864
+ reason: "errorNotRetryable",
865
+ errors: newErrors
866
+ });
867
+ }
868
+ }
869
+
870
+ // core/prompt/prepare-retries.ts
871
+ function prepareRetries({
872
+ maxRetries
873
+ }) {
874
+ if (maxRetries != null) {
875
+ if (!Number.isInteger(maxRetries)) {
876
+ throw new InvalidArgumentError({
877
+ parameter: "maxRetries",
878
+ value: maxRetries,
879
+ message: "maxRetries must be an integer"
880
+ });
881
+ }
882
+ if (maxRetries < 0) {
883
+ throw new InvalidArgumentError({
884
+ parameter: "maxRetries",
885
+ value: maxRetries,
886
+ message: "maxRetries must be >= 0"
887
+ });
888
+ }
889
+ }
890
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
891
+ return {
892
+ maxRetries: maxRetriesResult,
893
+ retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
894
+ };
895
+ }
896
+
897
+ // core/prompt/prepare-call-settings.ts
898
+ function prepareCallSettings({
899
+ maxTokens,
900
+ temperature,
901
+ topP,
902
+ topK,
903
+ presencePenalty,
904
+ frequencyPenalty,
905
+ stopSequences,
906
+ seed
907
+ }) {
908
+ if (maxTokens != null) {
909
+ if (!Number.isInteger(maxTokens)) {
910
+ throw new InvalidArgumentError({
911
+ parameter: "maxTokens",
912
+ value: maxTokens,
913
+ message: "maxTokens must be an integer"
914
+ });
915
+ }
916
+ if (maxTokens < 1) {
917
+ throw new InvalidArgumentError({
918
+ parameter: "maxTokens",
919
+ value: maxTokens,
920
+ message: "maxTokens must be >= 1"
921
+ });
922
+ }
923
+ }
924
+ if (temperature != null) {
925
+ if (typeof temperature !== "number") {
926
+ throw new InvalidArgumentError({
927
+ parameter: "temperature",
928
+ value: temperature,
929
+ message: "temperature must be a number"
930
+ });
931
+ }
932
+ }
933
+ if (topP != null) {
934
+ if (typeof topP !== "number") {
935
+ throw new InvalidArgumentError({
936
+ parameter: "topP",
937
+ value: topP,
938
+ message: "topP must be a number"
939
+ });
940
+ }
941
+ }
942
+ if (topK != null) {
943
+ if (typeof topK !== "number") {
944
+ throw new InvalidArgumentError({
945
+ parameter: "topK",
946
+ value: topK,
947
+ message: "topK must be a number"
948
+ });
949
+ }
950
+ }
951
+ if (presencePenalty != null) {
952
+ if (typeof presencePenalty !== "number") {
953
+ throw new InvalidArgumentError({
954
+ parameter: "presencePenalty",
955
+ value: presencePenalty,
956
+ message: "presencePenalty must be a number"
957
+ });
958
+ }
959
+ }
960
+ if (frequencyPenalty != null) {
961
+ if (typeof frequencyPenalty !== "number") {
962
+ throw new InvalidArgumentError({
963
+ parameter: "frequencyPenalty",
964
+ value: frequencyPenalty,
965
+ message: "frequencyPenalty must be a number"
966
+ });
967
+ }
968
+ }
969
+ if (seed != null) {
970
+ if (!Number.isInteger(seed)) {
971
+ throw new InvalidArgumentError({
972
+ parameter: "seed",
973
+ value: seed,
974
+ message: "seed must be an integer"
975
+ });
976
+ }
977
+ }
978
+ return {
979
+ maxTokens,
980
+ // TODO v5 remove default 0 for temperature
981
+ temperature: temperature != null ? temperature : 0,
982
+ topP,
983
+ topK,
984
+ presencePenalty,
985
+ frequencyPenalty,
986
+ stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : void 0,
987
+ seed
988
+ };
989
+ }
990
+
991
+ // core/prompt/convert-to-language-model-prompt.ts
992
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
993
+
994
+ // util/download-error.ts
995
+ var import_provider7 = require("@ai-sdk/provider");
996
+ var name5 = "AI_DownloadError";
997
+ var marker5 = `vercel.ai.error.${name5}`;
998
+ var symbol5 = Symbol.for(marker5);
999
+ var _a5;
1000
+ var DownloadError = class extends import_provider7.AISDKError {
1001
+ constructor({
1002
+ url,
1003
+ statusCode,
1004
+ statusText,
1005
+ cause,
1006
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
1007
+ }) {
1008
+ super({ name: name5, message, cause });
1009
+ this[_a5] = true;
1010
+ this.url = url;
1011
+ this.statusCode = statusCode;
1012
+ this.statusText = statusText;
1013
+ }
1014
+ static isInstance(error) {
1015
+ return import_provider7.AISDKError.hasMarker(error, marker5);
1016
+ }
1017
+ };
1018
+ _a5 = symbol5;
1019
+
1020
+ // util/download.ts
1021
+ async function download({ url }) {
1022
+ var _a7;
1023
+ const urlText = url.toString();
1024
+ try {
1025
+ const response = await fetch(urlText);
1026
+ if (!response.ok) {
1027
+ throw new DownloadError({
1028
+ url: urlText,
1029
+ statusCode: response.status,
1030
+ statusText: response.statusText
1031
+ });
1032
+ }
1033
+ return {
1034
+ data: new Uint8Array(await response.arrayBuffer()),
1035
+ mediaType: (_a7 = response.headers.get("content-type")) != null ? _a7 : void 0
1036
+ };
1037
+ } catch (error) {
1038
+ if (DownloadError.isInstance(error)) {
1039
+ throw error;
1040
+ }
1041
+ throw new DownloadError({ url: urlText, cause: error });
1042
+ }
1043
+ }
1044
+
1045
+ // core/util/detect-media-type.ts
1046
+ var imageMediaTypeSignatures = [
1047
+ {
1048
+ mediaType: "image/gif",
1049
+ bytesPrefix: [71, 73, 70],
1050
+ base64Prefix: "R0lG"
1051
+ },
1052
+ {
1053
+ mediaType: "image/png",
1054
+ bytesPrefix: [137, 80, 78, 71],
1055
+ base64Prefix: "iVBORw"
1056
+ },
1057
+ {
1058
+ mediaType: "image/jpeg",
1059
+ bytesPrefix: [255, 216],
1060
+ base64Prefix: "/9j/"
1061
+ },
1062
+ {
1063
+ mediaType: "image/webp",
1064
+ bytesPrefix: [82, 73, 70, 70],
1065
+ base64Prefix: "UklGRg"
1066
+ },
1067
+ {
1068
+ mediaType: "image/bmp",
1069
+ bytesPrefix: [66, 77],
1070
+ base64Prefix: "Qk"
1071
+ },
1072
+ {
1073
+ mediaType: "image/tiff",
1074
+ bytesPrefix: [73, 73, 42, 0],
1075
+ base64Prefix: "SUkqAA"
1076
+ },
1077
+ {
1078
+ mediaType: "image/tiff",
1079
+ bytesPrefix: [77, 77, 0, 42],
1080
+ base64Prefix: "TU0AKg"
1081
+ },
1082
+ {
1083
+ mediaType: "image/avif",
1084
+ bytesPrefix: [
1085
+ 0,
1086
+ 0,
1087
+ 0,
1088
+ 32,
1089
+ 102,
1090
+ 116,
1091
+ 121,
1092
+ 112,
1093
+ 97,
1094
+ 118,
1095
+ 105,
1096
+ 102
1097
+ ],
1098
+ base64Prefix: "AAAAIGZ0eXBhdmlm"
1099
+ },
1100
+ {
1101
+ mediaType: "image/heic",
1102
+ bytesPrefix: [
1103
+ 0,
1104
+ 0,
1105
+ 0,
1106
+ 32,
1107
+ 102,
1108
+ 116,
1109
+ 121,
1110
+ 112,
1111
+ 104,
1112
+ 101,
1113
+ 105,
1114
+ 99
1115
+ ],
1116
+ base64Prefix: "AAAAIGZ0eXBoZWlj"
1117
+ }
1118
+ ];
1119
+ function detectMediaType({
1120
+ data,
1121
+ signatures
1122
+ }) {
1123
+ for (const signature of signatures) {
1124
+ if (typeof data === "string" ? data.startsWith(signature.base64Prefix) : data.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => data[index] === byte)) {
1125
+ return signature.mediaType;
1126
+ }
1127
+ }
1128
+ return void 0;
1129
+ }
1130
+
1131
+ // core/prompt/invalid-message-role-error.ts
1132
+ var import_provider8 = require("@ai-sdk/provider");
1133
+ var name6 = "AI_InvalidMessageRoleError";
1134
+ var marker6 = `vercel.ai.error.${name6}`;
1135
+ var symbol6 = Symbol.for(marker6);
1136
+ var _a6;
1137
+ var InvalidMessageRoleError = class extends import_provider8.AISDKError {
1138
+ constructor({
1139
+ role,
1140
+ message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
1141
+ }) {
1142
+ super({ name: name6, message });
1143
+ this[_a6] = true;
1144
+ this.role = role;
1145
+ }
1146
+ static isInstance(error) {
1147
+ return import_provider8.AISDKError.hasMarker(error, marker6);
1148
+ }
1149
+ };
1150
+ _a6 = symbol6;
1151
+
1152
+ // core/prompt/split-data-url.ts
1153
+ function splitDataUrl(dataUrl) {
1154
+ try {
1155
+ const [header, base64Content] = dataUrl.split(",");
1156
+ return {
1157
+ mediaType: header.split(";")[0].split(":")[1],
1158
+ base64Content
1159
+ };
1160
+ } catch (error) {
1161
+ return {
1162
+ mediaType: void 0,
1163
+ base64Content: void 0
1164
+ };
1165
+ }
1166
+ }
1167
+
1168
+ // core/prompt/convert-to-language-model-prompt.ts
1169
+ async function convertToLanguageModelPrompt({
1170
+ prompt,
1171
+ modelSupportsImageUrls = true,
1172
+ modelSupportsUrl = () => false,
1173
+ downloadImplementation = download
1174
+ }) {
1175
+ const downloadedAssets = await downloadAssets(
1176
+ prompt.messages,
1177
+ downloadImplementation,
1178
+ modelSupportsImageUrls,
1179
+ modelSupportsUrl
1180
+ );
1181
+ return [
1182
+ ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
1183
+ ...prompt.messages.map(
1184
+ (message) => convertToLanguageModelMessage(message, downloadedAssets)
1185
+ )
1186
+ ];
1187
+ }
1188
+ function convertToLanguageModelMessage(message, downloadedAssets) {
1189
+ var _a7, _b, _c, _d, _e, _f;
1190
+ const role = message.role;
1191
+ switch (role) {
1192
+ case "system": {
1193
+ return {
1194
+ role: "system",
1195
+ content: message.content,
1196
+ providerOptions: (_a7 = message.providerOptions) != null ? _a7 : message.experimental_providerMetadata
1197
+ };
1198
+ }
1199
+ case "user": {
1200
+ if (typeof message.content === "string") {
1201
+ return {
1202
+ role: "user",
1203
+ content: [{ type: "text", text: message.content }],
1204
+ providerOptions: (_b = message.providerOptions) != null ? _b : message.experimental_providerMetadata
1205
+ };
1206
+ }
1207
+ return {
1208
+ role: "user",
1209
+ content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
1210
+ providerOptions: (_c = message.providerOptions) != null ? _c : message.experimental_providerMetadata
1211
+ };
1212
+ }
1213
+ case "assistant": {
1214
+ if (typeof message.content === "string") {
1215
+ return {
1216
+ role: "assistant",
1217
+ content: [{ type: "text", text: message.content }],
1218
+ providerOptions: (_d = message.providerOptions) != null ? _d : message.experimental_providerMetadata
1219
+ };
1220
+ }
1221
+ return {
1222
+ role: "assistant",
1223
+ content: message.content.filter(
1224
+ // remove empty text parts:
1225
+ (part) => part.type !== "text" || part.text !== ""
1226
+ ).map((part) => {
1227
+ var _a8, _b2;
1228
+ const providerOptions = (_a8 = part.providerOptions) != null ? _a8 : part.experimental_providerMetadata;
1229
+ switch (part.type) {
1230
+ case "file": {
1231
+ return {
1232
+ type: "file",
1233
+ data: part.data instanceof URL ? part.data : convertDataContentToBase64String(part.data),
1234
+ filename: part.filename,
1235
+ mediaType: (_b2 = part.mediaType) != null ? _b2 : part.mimeType,
1236
+ providerOptions
1237
+ };
1238
+ }
1239
+ case "reasoning": {
1240
+ return {
1241
+ type: "reasoning",
1242
+ text: part.text,
1243
+ signature: part.signature,
1244
+ providerOptions
1245
+ };
1246
+ }
1247
+ case "redacted-reasoning": {
1248
+ return {
1249
+ type: "redacted-reasoning",
1250
+ data: part.data,
1251
+ providerOptions
1252
+ };
1253
+ }
1254
+ case "text": {
1255
+ return {
1256
+ type: "text",
1257
+ text: part.text,
1258
+ providerOptions
1259
+ };
1260
+ }
1261
+ case "tool-call": {
1262
+ return {
1263
+ type: "tool-call",
1264
+ toolCallId: part.toolCallId,
1265
+ toolName: part.toolName,
1266
+ args: part.args,
1267
+ providerOptions
1268
+ };
1269
+ }
1270
+ }
1271
+ }),
1272
+ providerOptions: (_e = message.providerOptions) != null ? _e : message.experimental_providerMetadata
1273
+ };
1274
+ }
1275
+ case "tool": {
1276
+ return {
1277
+ role: "tool",
1278
+ content: message.content.map((part) => {
1279
+ var _a8;
1280
+ return {
1281
+ type: "tool-result",
1282
+ toolCallId: part.toolCallId,
1283
+ toolName: part.toolName,
1284
+ result: part.result,
1285
+ content: part.experimental_content,
1286
+ isError: part.isError,
1287
+ providerOptions: (_a8 = part.providerOptions) != null ? _a8 : part.experimental_providerMetadata
1288
+ };
1289
+ }),
1290
+ providerOptions: (_f = message.providerOptions) != null ? _f : message.experimental_providerMetadata
1291
+ };
1292
+ }
1293
+ default: {
1294
+ const _exhaustiveCheck = role;
1295
+ throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
1296
+ }
1297
+ }
1298
+ }
1299
+ async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
1300
+ const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
1301
+ (content) => Array.isArray(content)
1302
+ ).flat().filter(
1303
+ (part) => part.type === "image" || part.type === "file"
1304
+ ).filter(
1305
+ (part) => !(part.type === "image" && modelSupportsImageUrls === true)
1306
+ ).map((part) => part.type === "image" ? part.image : part.data).map(
1307
+ (part) => (
1308
+ // support string urls:
1309
+ typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part
1310
+ )
1311
+ ).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
1312
+ const downloadedImages = await Promise.all(
1313
+ urls.map(async (url) => ({
1314
+ url,
1315
+ data: await downloadImplementation({ url })
1316
+ }))
1317
+ );
1318
+ return Object.fromEntries(
1319
+ downloadedImages.map(({ url, data }) => [url.toString(), data])
1320
+ );
1321
+ }
1322
+ function convertPartToLanguageModelPart(part, downloadedAssets) {
1323
+ var _a7, _b, _c, _d, _e;
1324
+ if (part.type === "text") {
1325
+ return {
1326
+ type: "text",
1327
+ text: part.text,
1328
+ providerOptions: (_a7 = part.providerOptions) != null ? _a7 : part.experimental_providerMetadata
1329
+ };
1330
+ }
1331
+ let mediaType = (_b = part.mediaType) != null ? _b : part.mimeType;
1332
+ let data;
1333
+ let content;
1334
+ let normalizedData;
1335
+ const type = part.type;
1336
+ switch (type) {
1337
+ case "image":
1338
+ data = part.image;
1339
+ break;
1340
+ case "file":
1341
+ data = part.data;
1342
+ break;
1343
+ default:
1344
+ throw new Error(`Unsupported part type: ${type}`);
1345
+ }
1346
+ try {
1347
+ content = typeof data === "string" ? new URL(data) : data;
1348
+ } catch (error) {
1349
+ content = data;
1350
+ }
1351
+ if (content instanceof URL) {
1352
+ if (content.protocol === "data:") {
1353
+ const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(
1354
+ content.toString()
1355
+ );
1356
+ if (dataUrlMediaType == null || base64Content == null) {
1357
+ throw new Error(`Invalid data URL format in part ${type}`);
1358
+ }
1359
+ mediaType = dataUrlMediaType;
1360
+ normalizedData = convertDataContentToUint8Array(base64Content);
1361
+ } else {
1362
+ const downloadedFile = downloadedAssets[content.toString()];
1363
+ if (downloadedFile) {
1364
+ normalizedData = downloadedFile.data;
1365
+ mediaType != null ? mediaType : mediaType = downloadedFile.mediaType;
1366
+ } else {
1367
+ normalizedData = content;
1368
+ }
1369
+ }
1370
+ } else {
1371
+ normalizedData = convertDataContentToUint8Array(content);
1372
+ }
1373
+ switch (type) {
1374
+ case "image": {
1375
+ if (normalizedData instanceof Uint8Array) {
1376
+ mediaType = (_c = detectMediaType({
1377
+ data: normalizedData,
1378
+ signatures: imageMediaTypeSignatures
1379
+ })) != null ? _c : mediaType;
1380
+ }
1381
+ return {
1382
+ type: "file",
1383
+ mediaType: mediaType != null ? mediaType : "image/*",
1384
+ // any image
1385
+ filename: void 0,
1386
+ data: normalizedData instanceof Uint8Array ? (0, import_provider_utils4.convertUint8ArrayToBase64)(normalizedData) : normalizedData,
1387
+ providerOptions: (_d = part.providerOptions) != null ? _d : part.experimental_providerMetadata
1388
+ };
1389
+ }
1390
+ case "file": {
1391
+ if (mediaType == null) {
1392
+ throw new Error(`Media type is missing for file part`);
1393
+ }
1394
+ return {
1395
+ type: "file",
1396
+ mediaType,
1397
+ filename: part.filename,
1398
+ data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
1399
+ providerOptions: (_e = part.providerOptions) != null ? _e : part.experimental_providerMetadata
1400
+ };
1401
+ }
1402
+ }
1403
+ }
1404
+
1405
+ // core/types/usage.ts
1406
+ function calculateLanguageModelUsage({
1407
+ promptTokens,
1408
+ completionTokens
1409
+ }) {
1410
+ return {
1411
+ promptTokens,
1412
+ completionTokens,
1413
+ totalTokens: promptTokens + completionTokens
1414
+ };
1415
+ }
1416
+
1417
+ // util/constants.ts
1418
+ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
1419
+ // Annotate the CommonJS export names for ESM import in node:
1420
+ 0 && (module.exports = {
1421
+ HANGING_STREAM_WARNING_TIME_MS,
1422
+ calculateLanguageModelUsage,
1423
+ convertToLanguageModelPrompt,
1424
+ prepareCallSettings,
1425
+ prepareRetries,
1426
+ prepareToolsAndToolChoice,
1427
+ standardizePrompt
1428
+ });
1429
+ //# sourceMappingURL=index.js.map