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.
@@ -1,351 +1,7 @@
1
- // rsc/ai-state.tsx
2
- import * as jsondiffpatch from "jsondiffpatch";
3
- import { AsyncLocalStorage } from "async_hooks";
4
-
5
- // util/create-resolvable-promise.ts
6
- function createResolvablePromise() {
7
- let resolve;
8
- let reject;
9
- const promise = new Promise((res, rej) => {
10
- resolve = res;
11
- reject = rej;
12
- });
13
- return {
14
- promise,
15
- resolve,
16
- reject
17
- };
18
- }
19
-
20
- // util/is-function.ts
21
- var isFunction = (value) => typeof value === "function";
22
-
23
- // rsc/ai-state.tsx
24
- var asyncAIStateStorage = new AsyncLocalStorage();
25
- function getAIStateStoreOrThrow(message) {
26
- const store = asyncAIStateStorage.getStore();
27
- if (!store) {
28
- throw new Error(message);
29
- }
30
- return store;
31
- }
32
- function withAIState({ state, options }, fn) {
33
- return asyncAIStateStorage.run(
34
- {
35
- currentState: JSON.parse(JSON.stringify(state)),
36
- // deep clone object
37
- originalState: state,
38
- sealed: false,
39
- options
40
- },
41
- fn
42
- );
43
- }
44
- function getAIStateDeltaPromise() {
45
- const store = getAIStateStoreOrThrow("Internal error occurred.");
46
- return store.mutationDeltaPromise;
47
- }
48
- function sealMutableAIState() {
49
- const store = getAIStateStoreOrThrow("Internal error occurred.");
50
- store.sealed = true;
51
- }
52
- function getAIState(...args) {
53
- const store = getAIStateStoreOrThrow(
54
- "`getAIState` must be called within an AI Action."
55
- );
56
- if (args.length > 0) {
57
- const key = args[0];
58
- if (typeof store.currentState !== "object") {
59
- throw new Error(
60
- `You can't get the "${String(
61
- key
62
- )}" field from the AI state because it's not an object.`
63
- );
64
- }
65
- return store.currentState[key];
66
- }
67
- return store.currentState;
68
- }
69
- function getMutableAIState(...args) {
70
- const store = getAIStateStoreOrThrow(
71
- "`getMutableAIState` must be called within an AI Action."
72
- );
73
- if (store.sealed) {
74
- throw new Error(
75
- "`getMutableAIState` must be called before returning from an AI Action. Please move it to the top level of the Action's function body."
76
- );
77
- }
78
- if (!store.mutationDeltaPromise) {
79
- const { promise, resolve } = createResolvablePromise();
80
- store.mutationDeltaPromise = promise;
81
- store.mutationDeltaResolve = resolve;
82
- }
83
- function doUpdate(newState, done) {
84
- var _a9, _b;
85
- if (args.length > 0) {
86
- if (typeof store.currentState !== "object") {
87
- const key = args[0];
88
- throw new Error(
89
- `You can't modify the "${String(
90
- key
91
- )}" field of the AI state because it's not an object.`
92
- );
93
- }
94
- }
95
- if (isFunction(newState)) {
96
- if (args.length > 0) {
97
- store.currentState[args[0]] = newState(store.currentState[args[0]]);
98
- } else {
99
- store.currentState = newState(store.currentState);
100
- }
101
- } else {
102
- if (args.length > 0) {
103
- store.currentState[args[0]] = newState;
104
- } else {
105
- store.currentState = newState;
106
- }
107
- }
108
- (_b = (_a9 = store.options).onSetAIState) == null ? void 0 : _b.call(_a9, {
109
- key: args.length > 0 ? args[0] : void 0,
110
- state: store.currentState,
111
- done
112
- });
113
- }
114
- const mutableState = {
115
- get: () => {
116
- if (args.length > 0) {
117
- const key = args[0];
118
- if (typeof store.currentState !== "object") {
119
- throw new Error(
120
- `You can't get the "${String(
121
- key
122
- )}" field from the AI state because it's not an object.`
123
- );
124
- }
125
- return store.currentState[key];
126
- }
127
- return store.currentState;
128
- },
129
- update: function update(newAIState) {
130
- doUpdate(newAIState, false);
131
- },
132
- done: function done(...doneArgs) {
133
- if (doneArgs.length > 0) {
134
- doUpdate(doneArgs[0], true);
135
- }
136
- const delta = jsondiffpatch.diff(store.originalState, store.currentState);
137
- store.mutationDeltaResolve(delta);
138
- }
139
- };
140
- return mutableState;
141
- }
142
-
143
- // rsc/provider.tsx
144
- import * as React from "react";
145
- import { InternalAIProvider } from "./rsc-shared.mjs";
146
- import { jsx } from "react/jsx-runtime";
147
- async function innerAction({
148
- action,
149
- options
150
- }, state, ...args) {
151
- "use server";
152
- return await withAIState(
153
- {
154
- state,
155
- options
156
- },
157
- async () => {
158
- const result = await action(...args);
159
- sealMutableAIState();
160
- return [getAIStateDeltaPromise(), result];
161
- }
162
- );
163
- }
164
- function wrapAction(action, options) {
165
- return innerAction.bind(null, { action, options });
166
- }
167
- function createAI({
168
- actions,
169
- initialAIState,
170
- initialUIState,
171
- onSetAIState,
172
- onGetUIState
173
- }) {
174
- const wrappedActions = {};
175
- for (const name9 in actions) {
176
- wrappedActions[name9] = wrapAction(actions[name9], {
177
- onSetAIState
178
- });
179
- }
180
- const wrappedSyncUIState = onGetUIState ? wrapAction(onGetUIState, {}) : void 0;
181
- const AI = async (props) => {
182
- var _a9, _b;
183
- if ("useState" in React) {
184
- throw new Error(
185
- "This component can only be used inside Server Components."
186
- );
187
- }
188
- let uiState = (_a9 = props.initialUIState) != null ? _a9 : initialUIState;
189
- let aiState = (_b = props.initialAIState) != null ? _b : initialAIState;
190
- let aiStateDelta = void 0;
191
- if (wrappedSyncUIState) {
192
- const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);
193
- if (newUIState !== void 0) {
194
- aiStateDelta = newAIStateDelta;
195
- uiState = newUIState;
196
- }
197
- }
198
- return /* @__PURE__ */ jsx(
199
- InternalAIProvider,
200
- {
201
- wrappedActions,
202
- wrappedSyncUIState,
203
- initialUIState: uiState,
204
- initialAIState: aiState,
205
- initialAIStatePatch: aiStateDelta,
206
- children: props.children
207
- }
208
- );
209
- };
210
- return AI;
211
- }
212
-
213
- // rsc/stream-ui/stream-ui.tsx
214
- import { safeParseJSON } from "@ai-sdk/provider-utils";
215
-
216
- // util/download-error.ts
217
- import { AISDKError } from "@ai-sdk/provider";
218
- var name = "AI_DownloadError";
219
- var marker = `vercel.ai.error.${name}`;
220
- var symbol = Symbol.for(marker);
221
- var _a;
222
- var DownloadError = class extends AISDKError {
223
- constructor({
224
- url,
225
- statusCode,
226
- statusText,
227
- cause,
228
- message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
229
- }) {
230
- super({ name, message, cause });
231
- this[_a] = true;
232
- this.url = url;
233
- this.statusCode = statusCode;
234
- this.statusText = statusText;
235
- }
236
- static isInstance(error) {
237
- return AISDKError.hasMarker(error, marker);
238
- }
239
- };
240
- _a = symbol;
241
-
242
- // util/download.ts
243
- async function download({ url }) {
244
- var _a9;
245
- const urlText = url.toString();
246
- try {
247
- const response = await fetch(urlText);
248
- if (!response.ok) {
249
- throw new DownloadError({
250
- url: urlText,
251
- statusCode: response.status,
252
- statusText: response.statusText
253
- });
254
- }
255
- return {
256
- data: new Uint8Array(await response.arrayBuffer()),
257
- mimeType: (_a9 = response.headers.get("content-type")) != null ? _a9 : void 0
258
- };
259
- } catch (error) {
260
- if (DownloadError.isInstance(error)) {
261
- throw error;
262
- }
263
- throw new DownloadError({ url: urlText, cause: error });
264
- }
265
- }
266
-
267
- // core/util/detect-image-mimetype.ts
268
- var mimeTypeSignatures = [
269
- {
270
- mimeType: "image/gif",
271
- bytesPrefix: [71, 73, 70],
272
- base64Prefix: "R0lG"
273
- },
274
- {
275
- mimeType: "image/png",
276
- bytesPrefix: [137, 80, 78, 71],
277
- base64Prefix: "iVBORw"
278
- },
279
- {
280
- mimeType: "image/jpeg",
281
- bytesPrefix: [255, 216],
282
- base64Prefix: "/9j/"
283
- },
284
- {
285
- mimeType: "image/webp",
286
- bytesPrefix: [82, 73, 70, 70],
287
- base64Prefix: "UklGRg"
288
- },
289
- {
290
- mimeType: "image/bmp",
291
- bytesPrefix: [66, 77],
292
- base64Prefix: "Qk"
293
- },
294
- {
295
- mimeType: "image/tiff",
296
- bytesPrefix: [73, 73, 42, 0],
297
- base64Prefix: "SUkqAA"
298
- },
299
- {
300
- mimeType: "image/tiff",
301
- bytesPrefix: [77, 77, 0, 42],
302
- base64Prefix: "TU0AKg"
303
- },
304
- {
305
- mimeType: "image/avif",
306
- bytesPrefix: [
307
- 0,
308
- 0,
309
- 0,
310
- 32,
311
- 102,
312
- 116,
313
- 121,
314
- 112,
315
- 97,
316
- 118,
317
- 105,
318
- 102
319
- ],
320
- base64Prefix: "AAAAIGZ0eXBhdmlm"
321
- },
322
- {
323
- mimeType: "image/heic",
324
- bytesPrefix: [
325
- 0,
326
- 0,
327
- 0,
328
- 32,
329
- 102,
330
- 116,
331
- 121,
332
- 112,
333
- 104,
334
- 101,
335
- 105,
336
- 99
337
- ],
338
- base64Prefix: "AAAAIGZ0eXBoZWlj"
339
- }
340
- ];
341
- function detectImageMimeType(image) {
342
- for (const signature of mimeTypeSignatures) {
343
- if (typeof image === "string" ? image.startsWith(signature.base64Prefix) : image.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => image[index] === byte)) {
344
- return signature.mimeType;
345
- }
346
- }
347
- return void 0;
348
- }
1
+ // core/prompt/standardize-prompt.ts
2
+ import { InvalidPromptError } from "@ai-sdk/provider";
3
+ import { safeValidateTypes } from "@ai-sdk/provider-utils";
4
+ import { z as z7 } from "zod";
349
5
 
350
6
  // core/prompt/data-content.ts
351
7
  import {
@@ -354,26 +10,26 @@ import {
354
10
  } from "@ai-sdk/provider-utils";
355
11
 
356
12
  // core/prompt/invalid-data-content-error.ts
357
- import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
358
- var name2 = "AI_InvalidDataContentError";
359
- var marker2 = `vercel.ai.error.${name2}`;
360
- var symbol2 = Symbol.for(marker2);
361
- var _a2;
362
- var InvalidDataContentError = class extends AISDKError2 {
13
+ import { AISDKError } from "@ai-sdk/provider";
14
+ var name = "AI_InvalidDataContentError";
15
+ var marker = `vercel.ai.error.${name}`;
16
+ var symbol = Symbol.for(marker);
17
+ var _a;
18
+ var InvalidDataContentError = class extends AISDKError {
363
19
  constructor({
364
20
  content,
365
21
  cause,
366
22
  message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
367
23
  }) {
368
- super({ name: name2, message, cause });
369
- this[_a2] = true;
24
+ super({ name, message, cause });
25
+ this[_a] = true;
370
26
  this.content = content;
371
27
  }
372
28
  static isInstance(error) {
373
- return AISDKError2.hasMarker(error, marker2);
29
+ return AISDKError.hasMarker(error, marker);
374
30
  }
375
31
  };
376
- _a2 = symbol2;
32
+ _a = symbol;
377
33
 
378
34
  // core/prompt/data-content.ts
379
35
  import { z } from "zod";
@@ -384,8 +40,8 @@ var dataContentSchema = z.union([
384
40
  z.custom(
385
41
  // Buffer might not be available in some environments such as CloudFlare:
386
42
  (value) => {
387
- var _a9, _b;
388
- return (_b = (_a9 = globalThis.Buffer) == null ? void 0 : _a9.isBuffer(value)) != null ? _b : false;
43
+ var _a7, _b;
44
+ return (_b = (_a7 = globalThis.Buffer) == null ? void 0 : _a7.isBuffer(value)) != null ? _b : false;
389
45
  },
390
46
  { message: "Must be a Buffer" }
391
47
  )
@@ -427,662 +83,108 @@ function convertUint8ArrayToText(uint8Array) {
427
83
  }
428
84
  }
429
85
 
430
- // core/prompt/invalid-message-role-error.ts
431
- import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
432
- var name3 = "AI_InvalidMessageRoleError";
433
- var marker3 = `vercel.ai.error.${name3}`;
434
- var symbol3 = Symbol.for(marker3);
435
- var _a3;
436
- var InvalidMessageRoleError = class extends AISDKError3 {
437
- constructor({
438
- role,
439
- message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
440
- }) {
441
- super({ name: name3, message });
442
- this[_a3] = true;
443
- this.role = role;
444
- }
445
- static isInstance(error) {
446
- return AISDKError3.hasMarker(error, marker3);
447
- }
448
- };
449
- _a3 = symbol3;
450
-
451
- // core/prompt/split-data-url.ts
452
- function splitDataUrl(dataUrl) {
453
- try {
454
- const [header, base64Content] = dataUrl.split(",");
455
- return {
456
- mimeType: header.split(";")[0].split(":")[1],
457
- base64Content
458
- };
459
- } catch (error) {
460
- return {
461
- mimeType: void 0,
462
- base64Content: void 0
463
- };
464
- }
465
- }
466
-
467
- // core/prompt/convert-to-language-model-prompt.ts
468
- async function convertToLanguageModelPrompt({
469
- prompt,
470
- modelSupportsImageUrls = true,
471
- modelSupportsUrl = () => false,
472
- downloadImplementation = download
473
- }) {
474
- const downloadedAssets = await downloadAssets(
475
- prompt.messages,
476
- downloadImplementation,
477
- modelSupportsImageUrls,
478
- modelSupportsUrl
479
- );
480
- return [
481
- ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
482
- ...prompt.messages.map(
483
- (message) => convertToLanguageModelMessage(message, downloadedAssets)
484
- )
485
- ];
486
- }
487
- function convertToLanguageModelMessage(message, downloadedAssets) {
488
- var _a9, _b, _c, _d, _e, _f;
489
- const role = message.role;
490
- switch (role) {
491
- case "system": {
492
- return {
493
- role: "system",
494
- content: message.content,
495
- providerOptions: (_a9 = message.providerOptions) != null ? _a9 : message.experimental_providerMetadata
496
- };
497
- }
498
- case "user": {
499
- if (typeof message.content === "string") {
500
- return {
501
- role: "user",
502
- content: [{ type: "text", text: message.content }],
503
- providerOptions: (_b = message.providerOptions) != null ? _b : message.experimental_providerMetadata
504
- };
505
- }
506
- return {
507
- role: "user",
508
- content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
509
- providerOptions: (_c = message.providerOptions) != null ? _c : message.experimental_providerMetadata
510
- };
86
+ // core/prompt/attachments-to-parts.ts
87
+ function attachmentsToParts(attachments) {
88
+ var _a7, _b, _c;
89
+ const parts = [];
90
+ for (const attachment of attachments) {
91
+ let url;
92
+ try {
93
+ url = new URL(attachment.url);
94
+ } catch (error) {
95
+ throw new Error(`Invalid URL: ${attachment.url}`);
511
96
  }
512
- case "assistant": {
513
- if (typeof message.content === "string") {
514
- return {
515
- role: "assistant",
516
- content: [{ type: "text", text: message.content }],
517
- providerOptions: (_d = message.providerOptions) != null ? _d : message.experimental_providerMetadata
518
- };
519
- }
520
- return {
521
- role: "assistant",
522
- content: message.content.filter(
523
- // remove empty text parts:
524
- (part) => part.type !== "text" || part.text !== ""
525
- ).map((part) => {
526
- var _a10;
527
- const providerOptions = (_a10 = part.providerOptions) != null ? _a10 : part.experimental_providerMetadata;
528
- switch (part.type) {
529
- case "file": {
530
- return {
531
- type: "file",
532
- data: part.data instanceof URL ? part.data : convertDataContentToBase64String(part.data),
533
- filename: part.filename,
534
- mimeType: part.mimeType,
535
- providerOptions
536
- };
537
- }
538
- case "reasoning": {
539
- return {
540
- type: "reasoning",
541
- text: part.text,
542
- signature: part.signature,
543
- providerOptions
544
- };
545
- }
546
- case "redacted-reasoning": {
547
- return {
548
- type: "redacted-reasoning",
549
- data: part.data,
550
- providerOptions
551
- };
552
- }
553
- case "text": {
554
- return {
555
- type: "text",
556
- text: part.text,
557
- providerOptions
558
- };
559
- }
560
- case "tool-call": {
561
- return {
562
- type: "tool-call",
563
- toolCallId: part.toolCallId,
564
- toolName: part.toolName,
565
- args: part.args,
566
- providerOptions
567
- };
568
- }
97
+ switch (url.protocol) {
98
+ case "http:":
99
+ case "https:": {
100
+ if ((_a7 = attachment.contentType) == null ? void 0 : _a7.startsWith("image/")) {
101
+ parts.push({ type: "image", image: url });
102
+ } else {
103
+ if (!attachment.contentType) {
104
+ throw new Error(
105
+ "If the attachment is not an image, it must specify a content type"
106
+ );
569
107
  }
570
- }),
571
- providerOptions: (_e = message.providerOptions) != null ? _e : message.experimental_providerMetadata
572
- };
573
- }
574
- case "tool": {
575
- return {
576
- role: "tool",
577
- content: message.content.map((part) => {
578
- var _a10;
579
- return {
580
- type: "tool-result",
581
- toolCallId: part.toolCallId,
582
- toolName: part.toolName,
583
- result: part.result,
584
- content: part.experimental_content,
585
- isError: part.isError,
586
- providerOptions: (_a10 = part.providerOptions) != null ? _a10 : part.experimental_providerMetadata
587
- };
588
- }),
589
- providerOptions: (_f = message.providerOptions) != null ? _f : message.experimental_providerMetadata
590
- };
591
- }
592
- default: {
593
- const _exhaustiveCheck = role;
594
- throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
595
- }
596
- }
597
- }
598
- async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
599
- const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
600
- (content) => Array.isArray(content)
601
- ).flat().filter(
602
- (part) => part.type === "image" || part.type === "file"
603
- ).filter(
604
- (part) => !(part.type === "image" && modelSupportsImageUrls === true)
605
- ).map((part) => part.type === "image" ? part.image : part.data).map(
606
- (part) => (
607
- // support string urls:
608
- typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part
609
- )
610
- ).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
611
- const downloadedImages = await Promise.all(
612
- urls.map(async (url) => ({
613
- url,
614
- data: await downloadImplementation({ url })
615
- }))
616
- );
617
- return Object.fromEntries(
618
- downloadedImages.map(({ url, data }) => [url.toString(), data])
619
- );
620
- }
621
- function convertPartToLanguageModelPart(part, downloadedAssets) {
622
- var _a9, _b, _c, _d;
623
- if (part.type === "text") {
624
- return {
625
- type: "text",
626
- text: part.text,
627
- providerOptions: (_a9 = part.providerOptions) != null ? _a9 : part.experimental_providerMetadata
628
- };
629
- }
630
- let mimeType = part.mimeType;
631
- let data;
632
- let content;
633
- let normalizedData;
634
- const type = part.type;
635
- switch (type) {
636
- case "image":
637
- data = part.image;
638
- break;
639
- case "file":
640
- data = part.data;
641
- break;
642
- default:
643
- throw new Error(`Unsupported part type: ${type}`);
644
- }
645
- try {
646
- content = typeof data === "string" ? new URL(data) : data;
647
- } catch (error) {
648
- content = data;
649
- }
650
- if (content instanceof URL) {
651
- if (content.protocol === "data:") {
652
- const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(
653
- content.toString()
654
- );
655
- if (dataUrlMimeType == null || base64Content == null) {
656
- throw new Error(`Invalid data URL format in part ${type}`);
657
- }
658
- mimeType = dataUrlMimeType;
659
- normalizedData = convertDataContentToUint8Array(base64Content);
660
- } else {
661
- const downloadedFile = downloadedAssets[content.toString()];
662
- if (downloadedFile) {
663
- normalizedData = downloadedFile.data;
664
- mimeType != null ? mimeType : mimeType = downloadedFile.mimeType;
665
- } else {
666
- normalizedData = content;
108
+ parts.push({
109
+ type: "file",
110
+ data: url,
111
+ mediaType: attachment.contentType
112
+ });
113
+ }
114
+ break;
667
115
  }
668
- }
669
- } else {
670
- normalizedData = convertDataContentToUint8Array(content);
671
- }
672
- switch (type) {
673
- case "image": {
674
- if (normalizedData instanceof Uint8Array) {
675
- mimeType = (_b = detectImageMimeType(normalizedData)) != null ? _b : mimeType;
116
+ case "data:": {
117
+ let header;
118
+ let base64Content;
119
+ let mediaType;
120
+ try {
121
+ [header, base64Content] = attachment.url.split(",");
122
+ mediaType = header.split(";")[0].split(":")[1];
123
+ } catch (error) {
124
+ throw new Error(`Error processing data URL: ${attachment.url}`);
125
+ }
126
+ if (mediaType == null || base64Content == null) {
127
+ throw new Error(`Invalid data URL format: ${attachment.url}`);
128
+ }
129
+ if ((_b = attachment.contentType) == null ? void 0 : _b.startsWith("image/")) {
130
+ parts.push({
131
+ type: "image",
132
+ image: convertDataContentToUint8Array(base64Content)
133
+ });
134
+ } else if ((_c = attachment.contentType) == null ? void 0 : _c.startsWith("text/")) {
135
+ parts.push({
136
+ type: "text",
137
+ text: convertUint8ArrayToText(
138
+ convertDataContentToUint8Array(base64Content)
139
+ )
140
+ });
141
+ } else {
142
+ if (!attachment.contentType) {
143
+ throw new Error(
144
+ "If the attachment is not an image or text, it must specify a content type"
145
+ );
146
+ }
147
+ parts.push({
148
+ type: "file",
149
+ data: base64Content,
150
+ mediaType: attachment.contentType
151
+ });
152
+ }
153
+ break;
676
154
  }
677
- return {
678
- type: "image",
679
- image: normalizedData,
680
- mimeType,
681
- providerOptions: (_c = part.providerOptions) != null ? _c : part.experimental_providerMetadata
682
- };
683
- }
684
- case "file": {
685
- if (mimeType == null) {
686
- throw new Error(`Mime type is missing for file part`);
155
+ default: {
156
+ throw new Error(`Unsupported URL protocol: ${url.protocol}`);
687
157
  }
688
- return {
689
- type: "file",
690
- data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
691
- filename: part.filename,
692
- mimeType,
693
- providerOptions: (_d = part.providerOptions) != null ? _d : part.experimental_providerMetadata
694
- };
695
158
  }
696
159
  }
160
+ return parts;
697
161
  }
698
162
 
699
- // errors/invalid-argument-error.ts
700
- import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
701
- var name4 = "AI_InvalidArgumentError";
702
- var marker4 = `vercel.ai.error.${name4}`;
703
- var symbol4 = Symbol.for(marker4);
704
- var _a4;
705
- var InvalidArgumentError = class extends AISDKError4 {
163
+ // core/prompt/message-conversion-error.ts
164
+ import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
165
+ var name2 = "AI_MessageConversionError";
166
+ var marker2 = `vercel.ai.error.${name2}`;
167
+ var symbol2 = Symbol.for(marker2);
168
+ var _a2;
169
+ var MessageConversionError = class extends AISDKError2 {
706
170
  constructor({
707
- parameter,
708
- value,
171
+ originalMessage,
709
172
  message
710
173
  }) {
711
- super({
712
- name: name4,
713
- message: `Invalid argument for parameter ${parameter}: ${message}`
714
- });
715
- this[_a4] = true;
716
- this.parameter = parameter;
717
- this.value = value;
174
+ super({ name: name2, message });
175
+ this[_a2] = true;
176
+ this.originalMessage = originalMessage;
718
177
  }
719
178
  static isInstance(error) {
720
- return AISDKError4.hasMarker(error, marker4);
179
+ return AISDKError2.hasMarker(error, marker2);
721
180
  }
722
181
  };
723
- _a4 = symbol4;
724
-
725
- // core/prompt/prepare-call-settings.ts
726
- function prepareCallSettings({
727
- maxTokens,
728
- temperature,
729
- topP,
730
- topK,
731
- presencePenalty,
732
- frequencyPenalty,
733
- stopSequences,
734
- seed
735
- }) {
736
- if (maxTokens != null) {
737
- if (!Number.isInteger(maxTokens)) {
738
- throw new InvalidArgumentError({
739
- parameter: "maxTokens",
740
- value: maxTokens,
741
- message: "maxTokens must be an integer"
742
- });
743
- }
744
- if (maxTokens < 1) {
745
- throw new InvalidArgumentError({
746
- parameter: "maxTokens",
747
- value: maxTokens,
748
- message: "maxTokens must be >= 1"
749
- });
750
- }
751
- }
752
- if (temperature != null) {
753
- if (typeof temperature !== "number") {
754
- throw new InvalidArgumentError({
755
- parameter: "temperature",
756
- value: temperature,
757
- message: "temperature must be a number"
758
- });
759
- }
760
- }
761
- if (topP != null) {
762
- if (typeof topP !== "number") {
763
- throw new InvalidArgumentError({
764
- parameter: "topP",
765
- value: topP,
766
- message: "topP must be a number"
767
- });
768
- }
769
- }
770
- if (topK != null) {
771
- if (typeof topK !== "number") {
772
- throw new InvalidArgumentError({
773
- parameter: "topK",
774
- value: topK,
775
- message: "topK must be a number"
776
- });
777
- }
778
- }
779
- if (presencePenalty != null) {
780
- if (typeof presencePenalty !== "number") {
781
- throw new InvalidArgumentError({
782
- parameter: "presencePenalty",
783
- value: presencePenalty,
784
- message: "presencePenalty must be a number"
785
- });
786
- }
787
- }
788
- if (frequencyPenalty != null) {
789
- if (typeof frequencyPenalty !== "number") {
790
- throw new InvalidArgumentError({
791
- parameter: "frequencyPenalty",
792
- value: frequencyPenalty,
793
- message: "frequencyPenalty must be a number"
794
- });
795
- }
796
- }
797
- if (seed != null) {
798
- if (!Number.isInteger(seed)) {
799
- throw new InvalidArgumentError({
800
- parameter: "seed",
801
- value: seed,
802
- message: "seed must be an integer"
803
- });
804
- }
805
- }
806
- return {
807
- maxTokens,
808
- // TODO v5 remove default 0 for temperature
809
- temperature: temperature != null ? temperature : 0,
810
- topP,
811
- topK,
812
- presencePenalty,
813
- frequencyPenalty,
814
- stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : void 0,
815
- seed
816
- };
817
- }
818
-
819
- // util/retry-with-exponential-backoff.ts
820
- import { APICallError } from "@ai-sdk/provider";
821
- import { delay, getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
822
-
823
- // util/retry-error.ts
824
- import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
825
- var name5 = "AI_RetryError";
826
- var marker5 = `vercel.ai.error.${name5}`;
827
- var symbol5 = Symbol.for(marker5);
828
- var _a5;
829
- var RetryError = class extends AISDKError5 {
830
- constructor({
831
- message,
832
- reason,
833
- errors
834
- }) {
835
- super({ name: name5, message });
836
- this[_a5] = true;
837
- this.reason = reason;
838
- this.errors = errors;
839
- this.lastError = errors[errors.length - 1];
840
- }
841
- static isInstance(error) {
842
- return AISDKError5.hasMarker(error, marker5);
843
- }
844
- };
845
- _a5 = symbol5;
846
-
847
- // util/retry-with-exponential-backoff.ts
848
- var retryWithExponentialBackoff = ({
849
- maxRetries = 2,
850
- initialDelayInMs = 2e3,
851
- backoffFactor = 2
852
- } = {}) => async (f) => _retryWithExponentialBackoff(f, {
853
- maxRetries,
854
- delayInMs: initialDelayInMs,
855
- backoffFactor
856
- });
857
- async function _retryWithExponentialBackoff(f, {
858
- maxRetries,
859
- delayInMs,
860
- backoffFactor
861
- }, errors = []) {
862
- try {
863
- return await f();
864
- } catch (error) {
865
- if (isAbortError(error)) {
866
- throw error;
867
- }
868
- if (maxRetries === 0) {
869
- throw error;
870
- }
871
- const errorMessage = getErrorMessage(error);
872
- const newErrors = [...errors, error];
873
- const tryNumber = newErrors.length;
874
- if (tryNumber > maxRetries) {
875
- throw new RetryError({
876
- message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
877
- reason: "maxRetriesExceeded",
878
- errors: newErrors
879
- });
880
- }
881
- if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
882
- await delay(delayInMs);
883
- return _retryWithExponentialBackoff(
884
- f,
885
- { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
886
- newErrors
887
- );
888
- }
889
- if (tryNumber === 1) {
890
- throw error;
891
- }
892
- throw new RetryError({
893
- message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
894
- reason: "errorNotRetryable",
895
- errors: newErrors
896
- });
897
- }
898
- }
899
-
900
- // core/prompt/prepare-retries.ts
901
- function prepareRetries({
902
- maxRetries
903
- }) {
904
- if (maxRetries != null) {
905
- if (!Number.isInteger(maxRetries)) {
906
- throw new InvalidArgumentError({
907
- parameter: "maxRetries",
908
- value: maxRetries,
909
- message: "maxRetries must be an integer"
910
- });
911
- }
912
- if (maxRetries < 0) {
913
- throw new InvalidArgumentError({
914
- parameter: "maxRetries",
915
- value: maxRetries,
916
- message: "maxRetries must be >= 0"
917
- });
918
- }
919
- }
920
- const maxRetriesResult = maxRetries != null ? maxRetries : 2;
921
- return {
922
- maxRetries: maxRetriesResult,
923
- retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
924
- };
925
- }
926
-
927
- // core/prompt/prepare-tools-and-tool-choice.ts
928
- import { asSchema } from "@ai-sdk/ui-utils";
929
-
930
- // core/util/is-non-empty-object.ts
931
- function isNonEmptyObject(object) {
932
- return object != null && Object.keys(object).length > 0;
933
- }
934
-
935
- // core/prompt/prepare-tools-and-tool-choice.ts
936
- function prepareToolsAndToolChoice({
937
- tools,
938
- toolChoice,
939
- activeTools
940
- }) {
941
- if (!isNonEmptyObject(tools)) {
942
- return {
943
- tools: void 0,
944
- toolChoice: void 0
945
- };
946
- }
947
- const filteredTools = activeTools != null ? Object.entries(tools).filter(
948
- ([name9]) => activeTools.includes(name9)
949
- ) : Object.entries(tools);
950
- return {
951
- tools: filteredTools.map(([name9, tool]) => {
952
- const toolType = tool.type;
953
- switch (toolType) {
954
- case void 0:
955
- case "function":
956
- return {
957
- type: "function",
958
- name: name9,
959
- description: tool.description,
960
- parameters: asSchema(tool.parameters).jsonSchema
961
- };
962
- case "provider-defined":
963
- return {
964
- type: "provider-defined",
965
- name: name9,
966
- id: tool.id,
967
- args: tool.args
968
- };
969
- default: {
970
- const exhaustiveCheck = toolType;
971
- throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
972
- }
973
- }
974
- }),
975
- toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
976
- };
977
- }
978
-
979
- // core/prompt/standardize-prompt.ts
980
- import { InvalidPromptError } from "@ai-sdk/provider";
981
- import { safeValidateTypes } from "@ai-sdk/provider-utils";
982
- import { z as z7 } from "zod";
983
-
984
- // core/prompt/attachments-to-parts.ts
985
- function attachmentsToParts(attachments) {
986
- var _a9, _b, _c;
987
- const parts = [];
988
- for (const attachment of attachments) {
989
- let url;
990
- try {
991
- url = new URL(attachment.url);
992
- } catch (error) {
993
- throw new Error(`Invalid URL: ${attachment.url}`);
994
- }
995
- switch (url.protocol) {
996
- case "http:":
997
- case "https:": {
998
- if ((_a9 = attachment.contentType) == null ? void 0 : _a9.startsWith("image/")) {
999
- parts.push({ type: "image", image: url });
1000
- } else {
1001
- if (!attachment.contentType) {
1002
- throw new Error(
1003
- "If the attachment is not an image, it must specify a content type"
1004
- );
1005
- }
1006
- parts.push({
1007
- type: "file",
1008
- data: url,
1009
- mimeType: attachment.contentType
1010
- });
1011
- }
1012
- break;
1013
- }
1014
- case "data:": {
1015
- let header;
1016
- let base64Content;
1017
- let mimeType;
1018
- try {
1019
- [header, base64Content] = attachment.url.split(",");
1020
- mimeType = header.split(";")[0].split(":")[1];
1021
- } catch (error) {
1022
- throw new Error(`Error processing data URL: ${attachment.url}`);
1023
- }
1024
- if (mimeType == null || base64Content == null) {
1025
- throw new Error(`Invalid data URL format: ${attachment.url}`);
1026
- }
1027
- if ((_b = attachment.contentType) == null ? void 0 : _b.startsWith("image/")) {
1028
- parts.push({
1029
- type: "image",
1030
- image: convertDataContentToUint8Array(base64Content)
1031
- });
1032
- } else if ((_c = attachment.contentType) == null ? void 0 : _c.startsWith("text/")) {
1033
- parts.push({
1034
- type: "text",
1035
- text: convertUint8ArrayToText(
1036
- convertDataContentToUint8Array(base64Content)
1037
- )
1038
- });
1039
- } else {
1040
- if (!attachment.contentType) {
1041
- throw new Error(
1042
- "If the attachment is not an image or text, it must specify a content type"
1043
- );
1044
- }
1045
- parts.push({
1046
- type: "file",
1047
- data: base64Content,
1048
- mimeType: attachment.contentType
1049
- });
1050
- }
1051
- break;
1052
- }
1053
- default: {
1054
- throw new Error(`Unsupported URL protocol: ${url.protocol}`);
1055
- }
1056
- }
1057
- }
1058
- return parts;
1059
- }
1060
-
1061
- // core/prompt/message-conversion-error.ts
1062
- import { AISDKError as AISDKError6 } from "@ai-sdk/provider";
1063
- var name6 = "AI_MessageConversionError";
1064
- var marker6 = `vercel.ai.error.${name6}`;
1065
- var symbol6 = Symbol.for(marker6);
1066
- var _a6;
1067
- var MessageConversionError = class extends AISDKError6 {
1068
- constructor({
1069
- originalMessage,
1070
- message
1071
- }) {
1072
- super({ name: name6, message });
1073
- this[_a6] = true;
1074
- this.originalMessage = originalMessage;
1075
- }
1076
- static isInstance(error) {
1077
- return AISDKError6.hasMarker(error, marker6);
1078
- }
1079
- };
1080
- _a6 = symbol6;
182
+ _a2 = symbol2;
1081
183
 
1082
184
  // core/prompt/convert-to-core-messages.ts
1083
185
  function convertToCoreMessages(messages, options) {
1084
- var _a9, _b;
1085
- const tools = (_a9 = options == null ? void 0 : options.tools) != null ? _a9 : {};
186
+ var _a7, _b;
187
+ const tools = (_a7 = options == null ? void 0 : options.tools) != null ? _a7 : {};
1086
188
  const coreMessages = [];
1087
189
  for (let i = 0; i < messages.length; i++) {
1088
190
  const message = messages[i];
@@ -1120,14 +222,23 @@ function convertToCoreMessages(messages, options) {
1120
222
  case "assistant": {
1121
223
  if (message.parts != null) {
1122
224
  let processBlock2 = function() {
225
+ var _a8;
1123
226
  const content2 = [];
1124
227
  for (const part of block) {
1125
228
  switch (part.type) {
1126
- case "file":
1127
229
  case "text": {
1128
230
  content2.push(part);
1129
231
  break;
1130
232
  }
233
+ case "file": {
234
+ content2.push({
235
+ type: "file",
236
+ data: part.data,
237
+ mediaType: (_a8 = part.mediaType) != null ? _a8 : part.mimeType
238
+ // TODO migration, remove
239
+ });
240
+ break;
241
+ }
1131
242
  case "reasoning": {
1132
243
  for (const detail of part.details) {
1133
244
  switch (detail.type) {
@@ -1239,14 +350,14 @@ function convertToCoreMessages(messages, options) {
1239
350
  break;
1240
351
  }
1241
352
  const maxStep = toolInvocations.reduce((max, toolInvocation) => {
1242
- var _a10;
1243
- return Math.max(max, (_a10 = toolInvocation.step) != null ? _a10 : 0);
353
+ var _a8;
354
+ return Math.max(max, (_a8 = toolInvocation.step) != null ? _a8 : 0);
1244
355
  }, 0);
1245
356
  for (let i2 = 0; i2 <= maxStep; i2++) {
1246
357
  const stepInvocations = toolInvocations.filter(
1247
358
  (toolInvocation) => {
1248
- var _a10;
1249
- return ((_a10 = toolInvocation.step) != null ? _a10 : 0) === i2;
359
+ var _a8;
360
+ return ((_a8 = toolInvocation.step) != null ? _a8 : 0) === i2;
1250
361
  }
1251
362
  );
1252
363
  if (stepInvocations.length === 0) {
@@ -1295,845 +406,994 @@ function convertToCoreMessages(messages, options) {
1295
406
  if (content && !isLastMessage) {
1296
407
  coreMessages.push({ role: "assistant", content });
1297
408
  }
1298
- break;
1299
- }
1300
- case "data": {
1301
- break;
1302
- }
1303
- default: {
1304
- const _exhaustiveCheck = role;
1305
- throw new MessageConversionError({
1306
- originalMessage: message,
1307
- message: `Unsupported role: ${_exhaustiveCheck}`
1308
- });
1309
- }
409
+ break;
410
+ }
411
+ case "data": {
412
+ break;
413
+ }
414
+ default: {
415
+ const _exhaustiveCheck = role;
416
+ throw new MessageConversionError({
417
+ originalMessage: message,
418
+ message: `Unsupported role: ${_exhaustiveCheck}`
419
+ });
420
+ }
421
+ }
422
+ }
423
+ return coreMessages;
424
+ }
425
+
426
+ // core/prompt/detect-prompt-type.ts
427
+ function detectPromptType(prompt) {
428
+ if (!Array.isArray(prompt)) {
429
+ return "other";
430
+ }
431
+ if (prompt.length === 0) {
432
+ return "messages";
433
+ }
434
+ const characteristics = prompt.map(detectSingleMessageCharacteristics);
435
+ if (characteristics.some((c) => c === "has-ui-specific-parts")) {
436
+ return "ui-messages";
437
+ } else if (characteristics.every(
438
+ (c) => c === "has-core-specific-parts" || c === "message"
439
+ )) {
440
+ return "messages";
441
+ } else {
442
+ return "other";
443
+ }
444
+ }
445
+ function detectSingleMessageCharacteristics(message) {
446
+ if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
447
+ message.role === "data" || // UI-only role
448
+ "toolInvocations" in message || // UI-specific field
449
+ "parts" in message || // UI-specific field
450
+ "experimental_attachments" in message)) {
451
+ return "has-ui-specific-parts";
452
+ } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
453
+ "experimental_providerMetadata" in message || "providerOptions" in message)) {
454
+ return "has-core-specific-parts";
455
+ } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
456
+ return "message";
457
+ } else {
458
+ return "other";
459
+ }
460
+ }
461
+
462
+ // core/prompt/message.ts
463
+ import { z as z6 } from "zod";
464
+
465
+ // core/types/provider-metadata.ts
466
+ import { z as z3 } from "zod";
467
+
468
+ // core/types/json-value.ts
469
+ import { z as z2 } from "zod";
470
+ var jsonValueSchema = z2.lazy(
471
+ () => z2.union([
472
+ z2.null(),
473
+ z2.string(),
474
+ z2.number(),
475
+ z2.boolean(),
476
+ z2.record(z2.string(), jsonValueSchema),
477
+ z2.array(jsonValueSchema)
478
+ ])
479
+ );
480
+
481
+ // core/types/provider-metadata.ts
482
+ var providerMetadataSchema = z3.record(
483
+ z3.string(),
484
+ z3.record(z3.string(), jsonValueSchema)
485
+ );
486
+
487
+ // core/prompt/content-part.ts
488
+ import { z as z5 } from "zod";
489
+
490
+ // core/prompt/tool-result-content.ts
491
+ import { z as z4 } from "zod";
492
+ var toolResultContentSchema = z4.array(
493
+ z4.union([
494
+ z4.object({ type: z4.literal("text"), text: z4.string() }),
495
+ z4.object({
496
+ type: z4.literal("image"),
497
+ data: z4.string(),
498
+ mediaType: z4.string().optional()
499
+ })
500
+ ])
501
+ );
502
+
503
+ // core/prompt/content-part.ts
504
+ var textPartSchema = z5.object({
505
+ type: z5.literal("text"),
506
+ text: z5.string(),
507
+ providerOptions: providerMetadataSchema.optional(),
508
+ experimental_providerMetadata: providerMetadataSchema.optional()
509
+ });
510
+ var imagePartSchema = z5.object({
511
+ type: z5.literal("image"),
512
+ image: z5.union([dataContentSchema, z5.instanceof(URL)]),
513
+ mediaType: z5.string().optional(),
514
+ mimeType: z5.string().optional(),
515
+ providerOptions: providerMetadataSchema.optional(),
516
+ experimental_providerMetadata: providerMetadataSchema.optional()
517
+ });
518
+ var filePartSchema = z5.object({
519
+ type: z5.literal("file"),
520
+ data: z5.union([dataContentSchema, z5.instanceof(URL)]),
521
+ filename: z5.string().optional(),
522
+ mediaType: z5.string(),
523
+ mimeType: z5.string().optional(),
524
+ providerOptions: providerMetadataSchema.optional(),
525
+ experimental_providerMetadata: providerMetadataSchema.optional()
526
+ });
527
+ var reasoningPartSchema = z5.object({
528
+ type: z5.literal("reasoning"),
529
+ text: z5.string(),
530
+ providerOptions: providerMetadataSchema.optional(),
531
+ experimental_providerMetadata: providerMetadataSchema.optional()
532
+ });
533
+ var redactedReasoningPartSchema = z5.object({
534
+ type: z5.literal("redacted-reasoning"),
535
+ data: z5.string(),
536
+ providerOptions: providerMetadataSchema.optional(),
537
+ experimental_providerMetadata: providerMetadataSchema.optional()
538
+ });
539
+ var toolCallPartSchema = z5.object({
540
+ type: z5.literal("tool-call"),
541
+ toolCallId: z5.string(),
542
+ toolName: z5.string(),
543
+ args: z5.unknown(),
544
+ providerOptions: providerMetadataSchema.optional(),
545
+ experimental_providerMetadata: providerMetadataSchema.optional()
546
+ });
547
+ var toolResultPartSchema = z5.object({
548
+ type: z5.literal("tool-result"),
549
+ toolCallId: z5.string(),
550
+ toolName: z5.string(),
551
+ result: z5.unknown(),
552
+ content: toolResultContentSchema.optional(),
553
+ isError: z5.boolean().optional(),
554
+ providerOptions: providerMetadataSchema.optional(),
555
+ experimental_providerMetadata: providerMetadataSchema.optional()
556
+ });
557
+
558
+ // core/prompt/message.ts
559
+ var coreSystemMessageSchema = z6.object({
560
+ role: z6.literal("system"),
561
+ content: z6.string(),
562
+ providerOptions: providerMetadataSchema.optional(),
563
+ experimental_providerMetadata: providerMetadataSchema.optional()
564
+ });
565
+ var coreUserMessageSchema = z6.object({
566
+ role: z6.literal("user"),
567
+ content: z6.union([
568
+ z6.string(),
569
+ z6.array(z6.union([textPartSchema, imagePartSchema, filePartSchema]))
570
+ ]),
571
+ providerOptions: providerMetadataSchema.optional(),
572
+ experimental_providerMetadata: providerMetadataSchema.optional()
573
+ });
574
+ var coreAssistantMessageSchema = z6.object({
575
+ role: z6.literal("assistant"),
576
+ content: z6.union([
577
+ z6.string(),
578
+ z6.array(
579
+ z6.union([
580
+ textPartSchema,
581
+ filePartSchema,
582
+ reasoningPartSchema,
583
+ redactedReasoningPartSchema,
584
+ toolCallPartSchema
585
+ ])
586
+ )
587
+ ]),
588
+ providerOptions: providerMetadataSchema.optional(),
589
+ experimental_providerMetadata: providerMetadataSchema.optional()
590
+ });
591
+ var coreToolMessageSchema = z6.object({
592
+ role: z6.literal("tool"),
593
+ content: z6.array(toolResultPartSchema),
594
+ providerOptions: providerMetadataSchema.optional(),
595
+ experimental_providerMetadata: providerMetadataSchema.optional()
596
+ });
597
+ var coreMessageSchema = z6.union([
598
+ coreSystemMessageSchema,
599
+ coreUserMessageSchema,
600
+ coreAssistantMessageSchema,
601
+ coreToolMessageSchema
602
+ ]);
603
+
604
+ // core/prompt/standardize-prompt.ts
605
+ function standardizePrompt({
606
+ prompt,
607
+ tools
608
+ }) {
609
+ if (prompt.prompt == null && prompt.messages == null) {
610
+ throw new InvalidPromptError({
611
+ prompt,
612
+ message: "prompt or messages must be defined"
613
+ });
614
+ }
615
+ if (prompt.prompt != null && prompt.messages != null) {
616
+ throw new InvalidPromptError({
617
+ prompt,
618
+ message: "prompt and messages cannot be defined at the same time"
619
+ });
620
+ }
621
+ if (prompt.system != null && typeof prompt.system !== "string") {
622
+ throw new InvalidPromptError({
623
+ prompt,
624
+ message: "system must be a string"
625
+ });
626
+ }
627
+ if (prompt.prompt != null) {
628
+ if (typeof prompt.prompt !== "string") {
629
+ throw new InvalidPromptError({
630
+ prompt,
631
+ message: "prompt must be a string"
632
+ });
633
+ }
634
+ return {
635
+ type: "prompt",
636
+ system: prompt.system,
637
+ messages: [
638
+ {
639
+ role: "user",
640
+ content: prompt.prompt
641
+ }
642
+ ]
643
+ };
644
+ }
645
+ if (prompt.messages != null) {
646
+ const promptType = detectPromptType(prompt.messages);
647
+ if (promptType === "other") {
648
+ throw new InvalidPromptError({
649
+ prompt,
650
+ message: "messages must be an array of CoreMessage or UIMessage"
651
+ });
652
+ }
653
+ const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
654
+ tools
655
+ }) : prompt.messages;
656
+ if (messages.length === 0) {
657
+ throw new InvalidPromptError({
658
+ prompt,
659
+ message: "messages must not be empty"
660
+ });
661
+ }
662
+ const validationResult = safeValidateTypes({
663
+ value: messages,
664
+ schema: z7.array(coreMessageSchema)
665
+ });
666
+ if (!validationResult.success) {
667
+ throw new InvalidPromptError({
668
+ prompt,
669
+ message: "messages must be an array of CoreMessage or UIMessage",
670
+ cause: validationResult.error
671
+ });
1310
672
  }
673
+ return {
674
+ type: "messages",
675
+ messages,
676
+ system: prompt.system
677
+ };
1311
678
  }
1312
- return coreMessages;
679
+ throw new Error("unreachable");
1313
680
  }
1314
681
 
1315
- // core/prompt/detect-prompt-type.ts
1316
- function detectPromptType(prompt) {
1317
- if (!Array.isArray(prompt)) {
1318
- return "other";
682
+ // core/prompt/prepare-tools-and-tool-choice.ts
683
+ import { asSchema } from "@ai-sdk/ui-utils";
684
+
685
+ // core/util/is-non-empty-object.ts
686
+ function isNonEmptyObject(object) {
687
+ return object != null && Object.keys(object).length > 0;
688
+ }
689
+
690
+ // core/prompt/prepare-tools-and-tool-choice.ts
691
+ function prepareToolsAndToolChoice({
692
+ tools,
693
+ toolChoice,
694
+ activeTools
695
+ }) {
696
+ if (!isNonEmptyObject(tools)) {
697
+ return {
698
+ tools: void 0,
699
+ toolChoice: void 0
700
+ };
1319
701
  }
1320
- if (prompt.length === 0) {
1321
- return "messages";
702
+ const filteredTools = activeTools != null ? Object.entries(tools).filter(
703
+ ([name7]) => activeTools.includes(name7)
704
+ ) : Object.entries(tools);
705
+ return {
706
+ tools: filteredTools.map(([name7, tool]) => {
707
+ const toolType = tool.type;
708
+ switch (toolType) {
709
+ case void 0:
710
+ case "function":
711
+ return {
712
+ type: "function",
713
+ name: name7,
714
+ description: tool.description,
715
+ parameters: asSchema(tool.parameters).jsonSchema
716
+ };
717
+ case "provider-defined":
718
+ return {
719
+ type: "provider-defined",
720
+ name: name7,
721
+ id: tool.id,
722
+ args: tool.args
723
+ };
724
+ default: {
725
+ const exhaustiveCheck = toolType;
726
+ throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
727
+ }
728
+ }
729
+ }),
730
+ toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
731
+ };
732
+ }
733
+
734
+ // errors/invalid-argument-error.ts
735
+ import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
736
+ var name3 = "AI_InvalidArgumentError";
737
+ var marker3 = `vercel.ai.error.${name3}`;
738
+ var symbol3 = Symbol.for(marker3);
739
+ var _a3;
740
+ var InvalidArgumentError = class extends AISDKError3 {
741
+ constructor({
742
+ parameter,
743
+ value,
744
+ message
745
+ }) {
746
+ super({
747
+ name: name3,
748
+ message: `Invalid argument for parameter ${parameter}: ${message}`
749
+ });
750
+ this[_a3] = true;
751
+ this.parameter = parameter;
752
+ this.value = value;
1322
753
  }
1323
- const characteristics = prompt.map(detectSingleMessageCharacteristics);
1324
- if (characteristics.some((c) => c === "has-ui-specific-parts")) {
1325
- return "ui-messages";
1326
- } else if (characteristics.every(
1327
- (c) => c === "has-core-specific-parts" || c === "message"
1328
- )) {
1329
- return "messages";
1330
- } else {
1331
- return "other";
754
+ static isInstance(error) {
755
+ return AISDKError3.hasMarker(error, marker3);
756
+ }
757
+ };
758
+ _a3 = symbol3;
759
+
760
+ // util/retry-with-exponential-backoff.ts
761
+ import { APICallError } from "@ai-sdk/provider";
762
+ import { delay, getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
763
+
764
+ // util/retry-error.ts
765
+ import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
766
+ var name4 = "AI_RetryError";
767
+ var marker4 = `vercel.ai.error.${name4}`;
768
+ var symbol4 = Symbol.for(marker4);
769
+ var _a4;
770
+ var RetryError = class extends AISDKError4 {
771
+ constructor({
772
+ message,
773
+ reason,
774
+ errors
775
+ }) {
776
+ super({ name: name4, message });
777
+ this[_a4] = true;
778
+ this.reason = reason;
779
+ this.errors = errors;
780
+ this.lastError = errors[errors.length - 1];
781
+ }
782
+ static isInstance(error) {
783
+ return AISDKError4.hasMarker(error, marker4);
784
+ }
785
+ };
786
+ _a4 = symbol4;
787
+
788
+ // util/retry-with-exponential-backoff.ts
789
+ var retryWithExponentialBackoff = ({
790
+ maxRetries = 2,
791
+ initialDelayInMs = 2e3,
792
+ backoffFactor = 2
793
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
794
+ maxRetries,
795
+ delayInMs: initialDelayInMs,
796
+ backoffFactor
797
+ });
798
+ async function _retryWithExponentialBackoff(f, {
799
+ maxRetries,
800
+ delayInMs,
801
+ backoffFactor
802
+ }, errors = []) {
803
+ try {
804
+ return await f();
805
+ } catch (error) {
806
+ if (isAbortError(error)) {
807
+ throw error;
808
+ }
809
+ if (maxRetries === 0) {
810
+ throw error;
811
+ }
812
+ const errorMessage = getErrorMessage(error);
813
+ const newErrors = [...errors, error];
814
+ const tryNumber = newErrors.length;
815
+ if (tryNumber > maxRetries) {
816
+ throw new RetryError({
817
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
818
+ reason: "maxRetriesExceeded",
819
+ errors: newErrors
820
+ });
821
+ }
822
+ if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
823
+ await delay(delayInMs);
824
+ return _retryWithExponentialBackoff(
825
+ f,
826
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
827
+ newErrors
828
+ );
829
+ }
830
+ if (tryNumber === 1) {
831
+ throw error;
832
+ }
833
+ throw new RetryError({
834
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
835
+ reason: "errorNotRetryable",
836
+ errors: newErrors
837
+ });
1332
838
  }
1333
839
  }
1334
- function detectSingleMessageCharacteristics(message) {
1335
- if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
1336
- message.role === "data" || // UI-only role
1337
- "toolInvocations" in message || // UI-specific field
1338
- "parts" in message || // UI-specific field
1339
- "experimental_attachments" in message)) {
1340
- return "has-ui-specific-parts";
1341
- } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
1342
- "experimental_providerMetadata" in message || "providerOptions" in message)) {
1343
- return "has-core-specific-parts";
1344
- } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
1345
- return "message";
1346
- } else {
1347
- return "other";
840
+
841
+ // core/prompt/prepare-retries.ts
842
+ function prepareRetries({
843
+ maxRetries
844
+ }) {
845
+ if (maxRetries != null) {
846
+ if (!Number.isInteger(maxRetries)) {
847
+ throw new InvalidArgumentError({
848
+ parameter: "maxRetries",
849
+ value: maxRetries,
850
+ message: "maxRetries must be an integer"
851
+ });
852
+ }
853
+ if (maxRetries < 0) {
854
+ throw new InvalidArgumentError({
855
+ parameter: "maxRetries",
856
+ value: maxRetries,
857
+ message: "maxRetries must be >= 0"
858
+ });
859
+ }
1348
860
  }
861
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
862
+ return {
863
+ maxRetries: maxRetriesResult,
864
+ retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
865
+ };
1349
866
  }
1350
867
 
1351
- // core/prompt/message.ts
1352
- import { z as z6 } from "zod";
1353
-
1354
- // core/types/provider-metadata.ts
1355
- import { z as z3 } from "zod";
1356
-
1357
- // core/types/json-value.ts
1358
- import { z as z2 } from "zod";
1359
- var jsonValueSchema = z2.lazy(
1360
- () => z2.union([
1361
- z2.null(),
1362
- z2.string(),
1363
- z2.number(),
1364
- z2.boolean(),
1365
- z2.record(z2.string(), jsonValueSchema),
1366
- z2.array(jsonValueSchema)
1367
- ])
1368
- );
1369
-
1370
- // core/types/provider-metadata.ts
1371
- var providerMetadataSchema = z3.record(
1372
- z3.string(),
1373
- z3.record(z3.string(), jsonValueSchema)
1374
- );
1375
-
1376
- // core/prompt/content-part.ts
1377
- import { z as z5 } from "zod";
1378
-
1379
- // core/prompt/tool-result-content.ts
1380
- import { z as z4 } from "zod";
1381
- var toolResultContentSchema = z4.array(
1382
- z4.union([
1383
- z4.object({ type: z4.literal("text"), text: z4.string() }),
1384
- z4.object({
1385
- type: z4.literal("image"),
1386
- data: z4.string(),
1387
- mimeType: z4.string().optional()
1388
- })
1389
- ])
1390
- );
1391
-
1392
- // core/prompt/content-part.ts
1393
- var textPartSchema = z5.object({
1394
- type: z5.literal("text"),
1395
- text: z5.string(),
1396
- providerOptions: providerMetadataSchema.optional(),
1397
- experimental_providerMetadata: providerMetadataSchema.optional()
1398
- });
1399
- var imagePartSchema = z5.object({
1400
- type: z5.literal("image"),
1401
- image: z5.union([dataContentSchema, z5.instanceof(URL)]),
1402
- mimeType: z5.string().optional(),
1403
- providerOptions: providerMetadataSchema.optional(),
1404
- experimental_providerMetadata: providerMetadataSchema.optional()
1405
- });
1406
- var filePartSchema = z5.object({
1407
- type: z5.literal("file"),
1408
- data: z5.union([dataContentSchema, z5.instanceof(URL)]),
1409
- filename: z5.string().optional(),
1410
- mimeType: z5.string(),
1411
- providerOptions: providerMetadataSchema.optional(),
1412
- experimental_providerMetadata: providerMetadataSchema.optional()
1413
- });
1414
- var reasoningPartSchema = z5.object({
1415
- type: z5.literal("reasoning"),
1416
- text: z5.string(),
1417
- providerOptions: providerMetadataSchema.optional(),
1418
- experimental_providerMetadata: providerMetadataSchema.optional()
1419
- });
1420
- var redactedReasoningPartSchema = z5.object({
1421
- type: z5.literal("redacted-reasoning"),
1422
- data: z5.string(),
1423
- providerOptions: providerMetadataSchema.optional(),
1424
- experimental_providerMetadata: providerMetadataSchema.optional()
1425
- });
1426
- var toolCallPartSchema = z5.object({
1427
- type: z5.literal("tool-call"),
1428
- toolCallId: z5.string(),
1429
- toolName: z5.string(),
1430
- args: z5.unknown(),
1431
- providerOptions: providerMetadataSchema.optional(),
1432
- experimental_providerMetadata: providerMetadataSchema.optional()
1433
- });
1434
- var toolResultPartSchema = z5.object({
1435
- type: z5.literal("tool-result"),
1436
- toolCallId: z5.string(),
1437
- toolName: z5.string(),
1438
- result: z5.unknown(),
1439
- content: toolResultContentSchema.optional(),
1440
- isError: z5.boolean().optional(),
1441
- providerOptions: providerMetadataSchema.optional(),
1442
- experimental_providerMetadata: providerMetadataSchema.optional()
1443
- });
1444
-
1445
- // core/prompt/message.ts
1446
- var coreSystemMessageSchema = z6.object({
1447
- role: z6.literal("system"),
1448
- content: z6.string(),
1449
- providerOptions: providerMetadataSchema.optional(),
1450
- experimental_providerMetadata: providerMetadataSchema.optional()
1451
- });
1452
- var coreUserMessageSchema = z6.object({
1453
- role: z6.literal("user"),
1454
- content: z6.union([
1455
- z6.string(),
1456
- z6.array(z6.union([textPartSchema, imagePartSchema, filePartSchema]))
1457
- ]),
1458
- providerOptions: providerMetadataSchema.optional(),
1459
- experimental_providerMetadata: providerMetadataSchema.optional()
1460
- });
1461
- var coreAssistantMessageSchema = z6.object({
1462
- role: z6.literal("assistant"),
1463
- content: z6.union([
1464
- z6.string(),
1465
- z6.array(
1466
- z6.union([
1467
- textPartSchema,
1468
- filePartSchema,
1469
- reasoningPartSchema,
1470
- redactedReasoningPartSchema,
1471
- toolCallPartSchema
1472
- ])
1473
- )
1474
- ]),
1475
- providerOptions: providerMetadataSchema.optional(),
1476
- experimental_providerMetadata: providerMetadataSchema.optional()
1477
- });
1478
- var coreToolMessageSchema = z6.object({
1479
- role: z6.literal("tool"),
1480
- content: z6.array(toolResultPartSchema),
1481
- providerOptions: providerMetadataSchema.optional(),
1482
- experimental_providerMetadata: providerMetadataSchema.optional()
1483
- });
1484
- var coreMessageSchema = z6.union([
1485
- coreSystemMessageSchema,
1486
- coreUserMessageSchema,
1487
- coreAssistantMessageSchema,
1488
- coreToolMessageSchema
1489
- ]);
1490
-
1491
- // core/prompt/standardize-prompt.ts
1492
- function standardizePrompt({
1493
- prompt,
1494
- tools
868
+ // core/prompt/prepare-call-settings.ts
869
+ function prepareCallSettings({
870
+ maxTokens,
871
+ temperature,
872
+ topP,
873
+ topK,
874
+ presencePenalty,
875
+ frequencyPenalty,
876
+ stopSequences,
877
+ seed
1495
878
  }) {
1496
- if (prompt.prompt == null && prompt.messages == null) {
1497
- throw new InvalidPromptError({
1498
- prompt,
1499
- message: "prompt or messages must be defined"
1500
- });
1501
- }
1502
- if (prompt.prompt != null && prompt.messages != null) {
1503
- throw new InvalidPromptError({
1504
- prompt,
1505
- message: "prompt and messages cannot be defined at the same time"
1506
- });
879
+ if (maxTokens != null) {
880
+ if (!Number.isInteger(maxTokens)) {
881
+ throw new InvalidArgumentError({
882
+ parameter: "maxTokens",
883
+ value: maxTokens,
884
+ message: "maxTokens must be an integer"
885
+ });
886
+ }
887
+ if (maxTokens < 1) {
888
+ throw new InvalidArgumentError({
889
+ parameter: "maxTokens",
890
+ value: maxTokens,
891
+ message: "maxTokens must be >= 1"
892
+ });
893
+ }
1507
894
  }
1508
- if (prompt.system != null && typeof prompt.system !== "string") {
1509
- throw new InvalidPromptError({
1510
- prompt,
1511
- message: "system must be a string"
1512
- });
895
+ if (temperature != null) {
896
+ if (typeof temperature !== "number") {
897
+ throw new InvalidArgumentError({
898
+ parameter: "temperature",
899
+ value: temperature,
900
+ message: "temperature must be a number"
901
+ });
902
+ }
1513
903
  }
1514
- if (prompt.prompt != null) {
1515
- if (typeof prompt.prompt !== "string") {
1516
- throw new InvalidPromptError({
1517
- prompt,
1518
- message: "prompt must be a string"
904
+ if (topP != null) {
905
+ if (typeof topP !== "number") {
906
+ throw new InvalidArgumentError({
907
+ parameter: "topP",
908
+ value: topP,
909
+ message: "topP must be a number"
1519
910
  });
1520
911
  }
1521
- return {
1522
- type: "prompt",
1523
- system: prompt.system,
1524
- messages: [
1525
- {
1526
- role: "user",
1527
- content: prompt.prompt
1528
- }
1529
- ]
1530
- };
1531
912
  }
1532
- if (prompt.messages != null) {
1533
- const promptType = detectPromptType(prompt.messages);
1534
- if (promptType === "other") {
1535
- throw new InvalidPromptError({
1536
- prompt,
1537
- message: "messages must be an array of CoreMessage or UIMessage"
913
+ if (topK != null) {
914
+ if (typeof topK !== "number") {
915
+ throw new InvalidArgumentError({
916
+ parameter: "topK",
917
+ value: topK,
918
+ message: "topK must be a number"
1538
919
  });
1539
920
  }
1540
- const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
1541
- tools
1542
- }) : prompt.messages;
1543
- if (messages.length === 0) {
1544
- throw new InvalidPromptError({
1545
- prompt,
1546
- message: "messages must not be empty"
921
+ }
922
+ if (presencePenalty != null) {
923
+ if (typeof presencePenalty !== "number") {
924
+ throw new InvalidArgumentError({
925
+ parameter: "presencePenalty",
926
+ value: presencePenalty,
927
+ message: "presencePenalty must be a number"
1547
928
  });
1548
929
  }
1549
- const validationResult = safeValidateTypes({
1550
- value: messages,
1551
- schema: z7.array(coreMessageSchema)
1552
- });
1553
- if (!validationResult.success) {
1554
- throw new InvalidPromptError({
1555
- prompt,
1556
- message: "messages must be an array of CoreMessage or UIMessage",
1557
- cause: validationResult.error
930
+ }
931
+ if (frequencyPenalty != null) {
932
+ if (typeof frequencyPenalty !== "number") {
933
+ throw new InvalidArgumentError({
934
+ parameter: "frequencyPenalty",
935
+ value: frequencyPenalty,
936
+ message: "frequencyPenalty must be a number"
937
+ });
938
+ }
939
+ }
940
+ if (seed != null) {
941
+ if (!Number.isInteger(seed)) {
942
+ throw new InvalidArgumentError({
943
+ parameter: "seed",
944
+ value: seed,
945
+ message: "seed must be an integer"
1558
946
  });
1559
947
  }
1560
- return {
1561
- type: "messages",
1562
- messages,
1563
- system: prompt.system
1564
- };
1565
948
  }
1566
- throw new Error("unreachable");
1567
- }
1568
-
1569
- // core/types/usage.ts
1570
- function calculateLanguageModelUsage({
1571
- promptTokens,
1572
- completionTokens
1573
- }) {
1574
949
  return {
1575
- promptTokens,
1576
- completionTokens,
1577
- totalTokens: promptTokens + completionTokens
950
+ maxTokens,
951
+ // TODO v5 remove default 0 for temperature
952
+ temperature: temperature != null ? temperature : 0,
953
+ topP,
954
+ topK,
955
+ presencePenalty,
956
+ frequencyPenalty,
957
+ stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : void 0,
958
+ seed
1578
959
  };
1579
960
  }
1580
961
 
1581
- // errors/invalid-tool-arguments-error.ts
1582
- import { AISDKError as AISDKError7, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
1583
- var name7 = "AI_InvalidToolArgumentsError";
1584
- var marker7 = `vercel.ai.error.${name7}`;
1585
- var symbol7 = Symbol.for(marker7);
1586
- var _a7;
1587
- var InvalidToolArgumentsError = class extends AISDKError7 {
962
+ // core/prompt/convert-to-language-model-prompt.ts
963
+ import { convertUint8ArrayToBase64 as convertUint8ArrayToBase642 } from "@ai-sdk/provider-utils";
964
+
965
+ // util/download-error.ts
966
+ import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
967
+ var name5 = "AI_DownloadError";
968
+ var marker5 = `vercel.ai.error.${name5}`;
969
+ var symbol5 = Symbol.for(marker5);
970
+ var _a5;
971
+ var DownloadError = class extends AISDKError5 {
1588
972
  constructor({
1589
- toolArgs,
1590
- toolName,
973
+ url,
974
+ statusCode,
975
+ statusText,
1591
976
  cause,
1592
- message = `Invalid arguments for tool ${toolName}: ${getErrorMessage2(
1593
- cause
1594
- )}`
977
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
1595
978
  }) {
1596
- super({ name: name7, message, cause });
1597
- this[_a7] = true;
1598
- this.toolArgs = toolArgs;
1599
- this.toolName = toolName;
979
+ super({ name: name5, message, cause });
980
+ this[_a5] = true;
981
+ this.url = url;
982
+ this.statusCode = statusCode;
983
+ this.statusText = statusText;
1600
984
  }
1601
985
  static isInstance(error) {
1602
- return AISDKError7.hasMarker(error, marker7);
986
+ return AISDKError5.hasMarker(error, marker5);
1603
987
  }
1604
988
  };
1605
- _a7 = symbol7;
989
+ _a5 = symbol5;
990
+
991
+ // util/download.ts
992
+ async function download({ url }) {
993
+ var _a7;
994
+ const urlText = url.toString();
995
+ try {
996
+ const response = await fetch(urlText);
997
+ if (!response.ok) {
998
+ throw new DownloadError({
999
+ url: urlText,
1000
+ statusCode: response.status,
1001
+ statusText: response.statusText
1002
+ });
1003
+ }
1004
+ return {
1005
+ data: new Uint8Array(await response.arrayBuffer()),
1006
+ mediaType: (_a7 = response.headers.get("content-type")) != null ? _a7 : void 0
1007
+ };
1008
+ } catch (error) {
1009
+ if (DownloadError.isInstance(error)) {
1010
+ throw error;
1011
+ }
1012
+ throw new DownloadError({ url: urlText, cause: error });
1013
+ }
1014
+ }
1015
+
1016
+ // core/util/detect-media-type.ts
1017
+ var imageMediaTypeSignatures = [
1018
+ {
1019
+ mediaType: "image/gif",
1020
+ bytesPrefix: [71, 73, 70],
1021
+ base64Prefix: "R0lG"
1022
+ },
1023
+ {
1024
+ mediaType: "image/png",
1025
+ bytesPrefix: [137, 80, 78, 71],
1026
+ base64Prefix: "iVBORw"
1027
+ },
1028
+ {
1029
+ mediaType: "image/jpeg",
1030
+ bytesPrefix: [255, 216],
1031
+ base64Prefix: "/9j/"
1032
+ },
1033
+ {
1034
+ mediaType: "image/webp",
1035
+ bytesPrefix: [82, 73, 70, 70],
1036
+ base64Prefix: "UklGRg"
1037
+ },
1038
+ {
1039
+ mediaType: "image/bmp",
1040
+ bytesPrefix: [66, 77],
1041
+ base64Prefix: "Qk"
1042
+ },
1043
+ {
1044
+ mediaType: "image/tiff",
1045
+ bytesPrefix: [73, 73, 42, 0],
1046
+ base64Prefix: "SUkqAA"
1047
+ },
1048
+ {
1049
+ mediaType: "image/tiff",
1050
+ bytesPrefix: [77, 77, 0, 42],
1051
+ base64Prefix: "TU0AKg"
1052
+ },
1053
+ {
1054
+ mediaType: "image/avif",
1055
+ bytesPrefix: [
1056
+ 0,
1057
+ 0,
1058
+ 0,
1059
+ 32,
1060
+ 102,
1061
+ 116,
1062
+ 121,
1063
+ 112,
1064
+ 97,
1065
+ 118,
1066
+ 105,
1067
+ 102
1068
+ ],
1069
+ base64Prefix: "AAAAIGZ0eXBhdmlm"
1070
+ },
1071
+ {
1072
+ mediaType: "image/heic",
1073
+ bytesPrefix: [
1074
+ 0,
1075
+ 0,
1076
+ 0,
1077
+ 32,
1078
+ 102,
1079
+ 116,
1080
+ 121,
1081
+ 112,
1082
+ 104,
1083
+ 101,
1084
+ 105,
1085
+ 99
1086
+ ],
1087
+ base64Prefix: "AAAAIGZ0eXBoZWlj"
1088
+ }
1089
+ ];
1090
+ function detectMediaType({
1091
+ data,
1092
+ signatures
1093
+ }) {
1094
+ for (const signature of signatures) {
1095
+ if (typeof data === "string" ? data.startsWith(signature.base64Prefix) : data.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => data[index] === byte)) {
1096
+ return signature.mediaType;
1097
+ }
1098
+ }
1099
+ return void 0;
1100
+ }
1606
1101
 
1607
- // errors/no-such-tool-error.ts
1608
- import { AISDKError as AISDKError8 } from "@ai-sdk/provider";
1609
- var name8 = "AI_NoSuchToolError";
1610
- var marker8 = `vercel.ai.error.${name8}`;
1611
- var symbol8 = Symbol.for(marker8);
1612
- var _a8;
1613
- var NoSuchToolError = class extends AISDKError8 {
1102
+ // core/prompt/invalid-message-role-error.ts
1103
+ import { AISDKError as AISDKError6 } from "@ai-sdk/provider";
1104
+ var name6 = "AI_InvalidMessageRoleError";
1105
+ var marker6 = `vercel.ai.error.${name6}`;
1106
+ var symbol6 = Symbol.for(marker6);
1107
+ var _a6;
1108
+ var InvalidMessageRoleError = class extends AISDKError6 {
1614
1109
  constructor({
1615
- toolName,
1616
- availableTools = void 0,
1617
- message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
1110
+ role,
1111
+ message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
1618
1112
  }) {
1619
- super({ name: name8, message });
1620
- this[_a8] = true;
1621
- this.toolName = toolName;
1622
- this.availableTools = availableTools;
1113
+ super({ name: name6, message });
1114
+ this[_a6] = true;
1115
+ this.role = role;
1623
1116
  }
1624
1117
  static isInstance(error) {
1625
- return AISDKError8.hasMarker(error, marker8);
1118
+ return AISDKError6.hasMarker(error, marker6);
1626
1119
  }
1627
1120
  };
1628
- _a8 = symbol8;
1629
-
1630
- // util/is-async-generator.ts
1631
- function isAsyncGenerator(value) {
1632
- return value != null && typeof value === "object" && Symbol.asyncIterator in value;
1633
- }
1634
-
1635
- // util/is-generator.ts
1636
- function isGenerator(value) {
1637
- return value != null && typeof value === "object" && Symbol.iterator in value;
1638
- }
1639
-
1640
- // util/constants.ts
1641
- var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
1121
+ _a6 = symbol6;
1642
1122
 
1643
- // rsc/streamable-ui/create-suspended-chunk.tsx
1644
- import { Suspense } from "react";
1645
- import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
1646
- var R = [
1647
- async ({
1648
- c: current,
1649
- n: next
1650
- }) => {
1651
- const chunk = await next;
1652
- if (chunk.done) {
1653
- return chunk.value;
1654
- }
1655
- if (chunk.append) {
1656
- return /* @__PURE__ */ jsxs(Fragment, { children: [
1657
- current,
1658
- /* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) })
1659
- ] });
1660
- }
1661
- return /* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) });
1123
+ // core/prompt/split-data-url.ts
1124
+ function splitDataUrl(dataUrl) {
1125
+ try {
1126
+ const [header, base64Content] = dataUrl.split(",");
1127
+ return {
1128
+ mediaType: header.split(";")[0].split(":")[1],
1129
+ base64Content
1130
+ };
1131
+ } catch (error) {
1132
+ return {
1133
+ mediaType: void 0,
1134
+ base64Content: void 0
1135
+ };
1662
1136
  }
1663
- ][0];
1664
- function createSuspendedChunk(initialValue) {
1665
- const { promise, resolve, reject } = createResolvablePromise();
1666
- return {
1667
- row: /* @__PURE__ */ jsx2(Suspense, { fallback: initialValue, children: /* @__PURE__ */ jsx2(R, { c: initialValue, n: promise }) }),
1668
- resolve,
1669
- reject
1670
- };
1671
1137
  }
1672
1138
 
1673
- // rsc/streamable-ui/create-streamable-ui.tsx
1674
- function createStreamableUI(initialValue) {
1675
- let currentValue = initialValue;
1676
- let closed = false;
1677
- let { row, resolve, reject } = createSuspendedChunk(initialValue);
1678
- function assertStream(method) {
1679
- if (closed) {
1680
- throw new Error(method + ": UI stream is already closed.");
1681
- }
1682
- }
1683
- let warningTimeout;
1684
- function warnUnclosedStream() {
1685
- if (process.env.NODE_ENV === "development") {
1686
- if (warningTimeout) {
1687
- clearTimeout(warningTimeout);
1688
- }
1689
- warningTimeout = setTimeout(() => {
1690
- console.warn(
1691
- "The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
1692
- );
1693
- }, HANGING_STREAM_WARNING_TIME_MS);
1694
- }
1695
- }
1696
- warnUnclosedStream();
1697
- const streamable = {
1698
- value: row,
1699
- update(value) {
1700
- assertStream(".update()");
1701
- if (value === currentValue) {
1702
- warnUnclosedStream();
1703
- return streamable;
1704
- }
1705
- const resolvable = createResolvablePromise();
1706
- currentValue = value;
1707
- resolve({ value: currentValue, done: false, next: resolvable.promise });
1708
- resolve = resolvable.resolve;
1709
- reject = resolvable.reject;
1710
- warnUnclosedStream();
1711
- return streamable;
1712
- },
1713
- append(value) {
1714
- assertStream(".append()");
1715
- const resolvable = createResolvablePromise();
1716
- currentValue = value;
1717
- resolve({ value, done: false, append: true, next: resolvable.promise });
1718
- resolve = resolvable.resolve;
1719
- reject = resolvable.reject;
1720
- warnUnclosedStream();
1721
- return streamable;
1722
- },
1723
- error(error) {
1724
- assertStream(".error()");
1725
- if (warningTimeout) {
1726
- clearTimeout(warningTimeout);
1727
- }
1728
- closed = true;
1729
- reject(error);
1730
- return streamable;
1731
- },
1732
- done(...args) {
1733
- assertStream(".done()");
1734
- if (warningTimeout) {
1735
- clearTimeout(warningTimeout);
1736
- }
1737
- closed = true;
1738
- if (args.length) {
1739
- resolve({ value: args[0], done: true });
1740
- return streamable;
1741
- }
1742
- resolve({ value: currentValue, done: true });
1743
- return streamable;
1139
+ // core/prompt/convert-to-language-model-prompt.ts
1140
+ async function convertToLanguageModelPrompt({
1141
+ prompt,
1142
+ modelSupportsImageUrls = true,
1143
+ modelSupportsUrl = () => false,
1144
+ downloadImplementation = download
1145
+ }) {
1146
+ const downloadedAssets = await downloadAssets(
1147
+ prompt.messages,
1148
+ downloadImplementation,
1149
+ modelSupportsImageUrls,
1150
+ modelSupportsUrl
1151
+ );
1152
+ return [
1153
+ ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
1154
+ ...prompt.messages.map(
1155
+ (message) => convertToLanguageModelMessage(message, downloadedAssets)
1156
+ )
1157
+ ];
1158
+ }
1159
+ function convertToLanguageModelMessage(message, downloadedAssets) {
1160
+ var _a7, _b, _c, _d, _e, _f;
1161
+ const role = message.role;
1162
+ switch (role) {
1163
+ case "system": {
1164
+ return {
1165
+ role: "system",
1166
+ content: message.content,
1167
+ providerOptions: (_a7 = message.providerOptions) != null ? _a7 : message.experimental_providerMetadata
1168
+ };
1744
1169
  }
1745
- };
1746
- return streamable;
1747
- }
1748
-
1749
- // rsc/stream-ui/stream-ui.tsx
1750
- var defaultTextRenderer = ({ content }) => content;
1751
- async function streamUI({
1752
- model,
1753
- tools,
1754
- toolChoice,
1755
- system,
1756
- prompt,
1757
- messages,
1758
- maxRetries,
1759
- abortSignal,
1760
- headers,
1761
- initial,
1762
- text,
1763
- experimental_providerMetadata,
1764
- providerOptions = experimental_providerMetadata,
1765
- onFinish,
1766
- ...settings
1767
- }) {
1768
- if (typeof model === "string") {
1769
- throw new Error(
1770
- "`model` cannot be a string in `streamUI`. Use the actual model instance instead."
1771
- );
1772
- }
1773
- if ("functions" in settings) {
1774
- throw new Error(
1775
- "`functions` is not supported in `streamUI`, use `tools` instead."
1776
- );
1777
- }
1778
- if ("provider" in settings) {
1779
- throw new Error(
1780
- "`provider` is no longer needed in `streamUI`. Use `model` instead."
1781
- );
1782
- }
1783
- if (tools) {
1784
- for (const [name9, tool] of Object.entries(tools)) {
1785
- if ("render" in tool) {
1786
- throw new Error(
1787
- "Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: " + name9
1788
- );
1170
+ case "user": {
1171
+ if (typeof message.content === "string") {
1172
+ return {
1173
+ role: "user",
1174
+ content: [{ type: "text", text: message.content }],
1175
+ providerOptions: (_b = message.providerOptions) != null ? _b : message.experimental_providerMetadata
1176
+ };
1789
1177
  }
1178
+ return {
1179
+ role: "user",
1180
+ content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
1181
+ providerOptions: (_c = message.providerOptions) != null ? _c : message.experimental_providerMetadata
1182
+ };
1790
1183
  }
1791
- }
1792
- const ui = createStreamableUI(initial);
1793
- const textRender = text || defaultTextRenderer;
1794
- let finished;
1795
- let finishEvent = null;
1796
- async function render({
1797
- args,
1798
- renderer,
1799
- streamableUI,
1800
- isLastCall = false
1801
- }) {
1802
- if (!renderer)
1803
- return;
1804
- const renderFinished = createResolvablePromise();
1805
- finished = finished ? finished.then(() => renderFinished.promise) : renderFinished.promise;
1806
- const rendererResult = renderer(...args);
1807
- if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {
1808
- while (true) {
1809
- const { done, value } = await rendererResult.next();
1810
- const node = await value;
1811
- if (isLastCall && done) {
1812
- streamableUI.done(node);
1813
- } else {
1814
- streamableUI.update(node);
1815
- }
1816
- if (done)
1817
- break;
1818
- }
1819
- } else {
1820
- const node = await rendererResult;
1821
- if (isLastCall) {
1822
- streamableUI.done(node);
1823
- } else {
1824
- streamableUI.update(node);
1184
+ case "assistant": {
1185
+ if (typeof message.content === "string") {
1186
+ return {
1187
+ role: "assistant",
1188
+ content: [{ type: "text", text: message.content }],
1189
+ providerOptions: (_d = message.providerOptions) != null ? _d : message.experimental_providerMetadata
1190
+ };
1825
1191
  }
1826
- }
1827
- renderFinished.resolve(void 0);
1828
- }
1829
- const { retry } = prepareRetries({ maxRetries });
1830
- const validatedPrompt = standardizePrompt({
1831
- prompt: { system, prompt, messages },
1832
- tools: void 0
1833
- // streamUI tools don't support multi-modal tool result conversion
1834
- });
1835
- const result = await retry(
1836
- async () => {
1837
- var _a9;
1838
- return model.doStream({
1839
- ...prepareCallSettings(settings),
1840
- ...prepareToolsAndToolChoice({
1841
- tools,
1842
- toolChoice,
1843
- activeTools: void 0
1844
- }),
1845
- inputFormat: validatedPrompt.type,
1846
- prompt: await convertToLanguageModelPrompt({
1847
- prompt: validatedPrompt,
1848
- modelSupportsImageUrls: model.supportsImageUrls,
1849
- modelSupportsUrl: (_a9 = model.supportsUrl) == null ? void 0 : _a9.bind(model)
1850
- // support 'this' context
1851
- }),
1852
- providerOptions,
1853
- abortSignal,
1854
- headers
1855
- });
1856
- }
1857
- );
1858
- const [stream, forkedStream] = result.stream.tee();
1859
- (async () => {
1860
- try {
1861
- let content = "";
1862
- let hasToolCall = false;
1863
- const reader = forkedStream.getReader();
1864
- while (true) {
1865
- const { done, value } = await reader.read();
1866
- if (done)
1867
- break;
1868
- switch (value.type) {
1869
- case "text-delta": {
1870
- content += value.textDelta;
1871
- render({
1872
- renderer: textRender,
1873
- args: [{ content, done: false, delta: value.textDelta }],
1874
- streamableUI: ui
1875
- });
1876
- break;
1877
- }
1878
- case "tool-call-delta": {
1879
- hasToolCall = true;
1880
- break;
1881
- }
1882
- case "tool-call": {
1883
- const toolName = value.toolName;
1884
- if (!tools) {
1885
- throw new NoSuchToolError({ toolName });
1192
+ return {
1193
+ role: "assistant",
1194
+ content: message.content.filter(
1195
+ // remove empty text parts:
1196
+ (part) => part.type !== "text" || part.text !== ""
1197
+ ).map((part) => {
1198
+ var _a8, _b2;
1199
+ const providerOptions = (_a8 = part.providerOptions) != null ? _a8 : part.experimental_providerMetadata;
1200
+ switch (part.type) {
1201
+ case "file": {
1202
+ return {
1203
+ type: "file",
1204
+ data: part.data instanceof URL ? part.data : convertDataContentToBase64String(part.data),
1205
+ filename: part.filename,
1206
+ mediaType: (_b2 = part.mediaType) != null ? _b2 : part.mimeType,
1207
+ providerOptions
1208
+ };
1886
1209
  }
1887
- const tool = tools[toolName];
1888
- if (!tool) {
1889
- throw new NoSuchToolError({
1890
- toolName,
1891
- availableTools: Object.keys(tools)
1892
- });
1210
+ case "reasoning": {
1211
+ return {
1212
+ type: "reasoning",
1213
+ text: part.text,
1214
+ signature: part.signature,
1215
+ providerOptions
1216
+ };
1893
1217
  }
1894
- hasToolCall = true;
1895
- const parseResult = safeParseJSON({
1896
- text: value.args,
1897
- schema: tool.parameters
1898
- });
1899
- if (parseResult.success === false) {
1900
- throw new InvalidToolArgumentsError({
1901
- toolName,
1902
- toolArgs: value.args,
1903
- cause: parseResult.error
1904
- });
1218
+ case "redacted-reasoning": {
1219
+ return {
1220
+ type: "redacted-reasoning",
1221
+ data: part.data,
1222
+ providerOptions
1223
+ };
1224
+ }
1225
+ case "text": {
1226
+ return {
1227
+ type: "text",
1228
+ text: part.text,
1229
+ providerOptions
1230
+ };
1231
+ }
1232
+ case "tool-call": {
1233
+ return {
1234
+ type: "tool-call",
1235
+ toolCallId: part.toolCallId,
1236
+ toolName: part.toolName,
1237
+ args: part.args,
1238
+ providerOptions
1239
+ };
1905
1240
  }
1906
- render({
1907
- renderer: tool.generate,
1908
- args: [
1909
- parseResult.value,
1910
- {
1911
- toolName,
1912
- toolCallId: value.toolCallId
1913
- }
1914
- ],
1915
- streamableUI: ui,
1916
- isLastCall: true
1917
- });
1918
- break;
1919
- }
1920
- case "error": {
1921
- throw value.error;
1922
- }
1923
- case "finish": {
1924
- finishEvent = {
1925
- finishReason: value.finishReason,
1926
- usage: calculateLanguageModelUsage(value.usage),
1927
- warnings: result.warnings,
1928
- rawResponse: result.rawResponse
1929
- };
1930
- break;
1931
1241
  }
1932
- }
1933
- }
1934
- if (!hasToolCall) {
1935
- render({
1936
- renderer: textRender,
1937
- args: [{ content, done: true }],
1938
- streamableUI: ui,
1939
- isLastCall: true
1940
- });
1941
- }
1942
- await finished;
1943
- if (finishEvent && onFinish) {
1944
- await onFinish({
1945
- ...finishEvent,
1946
- value: ui.value
1947
- });
1948
- }
1949
- } catch (error) {
1950
- ui.error(error);
1951
- }
1952
- })();
1953
- return {
1954
- ...result,
1955
- stream,
1956
- value: ui.value
1957
- };
1958
- }
1959
-
1960
- // rsc/streamable-value/streamable-value.ts
1961
- var STREAMABLE_VALUE_TYPE = Symbol.for("ui.streamable.value");
1962
-
1963
- // rsc/streamable-value/create-streamable-value.ts
1964
- var STREAMABLE_VALUE_INTERNAL_LOCK = Symbol("streamable.value.lock");
1965
- function createStreamableValue(initialValue) {
1966
- const isReadableStream = initialValue instanceof ReadableStream || typeof initialValue === "object" && initialValue !== null && "getReader" in initialValue && typeof initialValue.getReader === "function" && "locked" in initialValue && typeof initialValue.locked === "boolean";
1967
- if (!isReadableStream) {
1968
- return createStreamableValueImpl(initialValue);
1969
- }
1970
- const streamableValue = createStreamableValueImpl();
1971
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
1972
- (async () => {
1973
- try {
1974
- const reader = initialValue.getReader();
1975
- while (true) {
1976
- const { value, done } = await reader.read();
1977
- if (done) {
1978
- break;
1979
- }
1980
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1981
- if (typeof value === "string") {
1982
- streamableValue.append(value);
1983
- } else {
1984
- streamableValue.update(value);
1985
- }
1986
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
1987
- }
1988
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1989
- streamableValue.done();
1990
- } catch (e) {
1991
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1992
- streamableValue.error(e);
1242
+ }),
1243
+ providerOptions: (_e = message.providerOptions) != null ? _e : message.experimental_providerMetadata
1244
+ };
1993
1245
  }
1994
- })();
1995
- return streamableValue;
1996
- }
1997
- function createStreamableValueImpl(initialValue) {
1998
- let closed = false;
1999
- let locked = false;
2000
- let resolvable = createResolvablePromise();
2001
- let currentValue = initialValue;
2002
- let currentError;
2003
- let currentPromise = resolvable.promise;
2004
- let currentPatchValue;
2005
- function assertStream(method) {
2006
- if (closed) {
2007
- throw new Error(method + ": Value stream is already closed.");
1246
+ case "tool": {
1247
+ return {
1248
+ role: "tool",
1249
+ content: message.content.map((part) => {
1250
+ var _a8;
1251
+ return {
1252
+ type: "tool-result",
1253
+ toolCallId: part.toolCallId,
1254
+ toolName: part.toolName,
1255
+ result: part.result,
1256
+ content: part.experimental_content,
1257
+ isError: part.isError,
1258
+ providerOptions: (_a8 = part.providerOptions) != null ? _a8 : part.experimental_providerMetadata
1259
+ };
1260
+ }),
1261
+ providerOptions: (_f = message.providerOptions) != null ? _f : message.experimental_providerMetadata
1262
+ };
2008
1263
  }
2009
- if (locked) {
2010
- throw new Error(
2011
- method + ": Value stream is locked and cannot be updated."
2012
- );
1264
+ default: {
1265
+ const _exhaustiveCheck = role;
1266
+ throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
2013
1267
  }
2014
1268
  }
2015
- let warningTimeout;
2016
- function warnUnclosedStream() {
2017
- if (process.env.NODE_ENV === "development") {
2018
- if (warningTimeout) {
2019
- clearTimeout(warningTimeout);
2020
- }
2021
- warningTimeout = setTimeout(() => {
2022
- console.warn(
2023
- "The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
2024
- );
2025
- }, HANGING_STREAM_WARNING_TIME_MS);
2026
- }
1269
+ }
1270
+ async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
1271
+ const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
1272
+ (content) => Array.isArray(content)
1273
+ ).flat().filter(
1274
+ (part) => part.type === "image" || part.type === "file"
1275
+ ).filter(
1276
+ (part) => !(part.type === "image" && modelSupportsImageUrls === true)
1277
+ ).map((part) => part.type === "image" ? part.image : part.data).map(
1278
+ (part) => (
1279
+ // support string urls:
1280
+ typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part
1281
+ )
1282
+ ).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
1283
+ const downloadedImages = await Promise.all(
1284
+ urls.map(async (url) => ({
1285
+ url,
1286
+ data: await downloadImplementation({ url })
1287
+ }))
1288
+ );
1289
+ return Object.fromEntries(
1290
+ downloadedImages.map(({ url, data }) => [url.toString(), data])
1291
+ );
1292
+ }
1293
+ function convertPartToLanguageModelPart(part, downloadedAssets) {
1294
+ var _a7, _b, _c, _d, _e;
1295
+ if (part.type === "text") {
1296
+ return {
1297
+ type: "text",
1298
+ text: part.text,
1299
+ providerOptions: (_a7 = part.providerOptions) != null ? _a7 : part.experimental_providerMetadata
1300
+ };
1301
+ }
1302
+ let mediaType = (_b = part.mediaType) != null ? _b : part.mimeType;
1303
+ let data;
1304
+ let content;
1305
+ let normalizedData;
1306
+ const type = part.type;
1307
+ switch (type) {
1308
+ case "image":
1309
+ data = part.image;
1310
+ break;
1311
+ case "file":
1312
+ data = part.data;
1313
+ break;
1314
+ default:
1315
+ throw new Error(`Unsupported part type: ${type}`);
1316
+ }
1317
+ try {
1318
+ content = typeof data === "string" ? new URL(data) : data;
1319
+ } catch (error) {
1320
+ content = data;
2027
1321
  }
2028
- warnUnclosedStream();
2029
- function createWrapped(initialChunk) {
2030
- let init;
2031
- if (currentError !== void 0) {
2032
- init = { error: currentError };
1322
+ if (content instanceof URL) {
1323
+ if (content.protocol === "data:") {
1324
+ const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(
1325
+ content.toString()
1326
+ );
1327
+ if (dataUrlMediaType == null || base64Content == null) {
1328
+ throw new Error(`Invalid data URL format in part ${type}`);
1329
+ }
1330
+ mediaType = dataUrlMediaType;
1331
+ normalizedData = convertDataContentToUint8Array(base64Content);
2033
1332
  } else {
2034
- if (currentPatchValue && !initialChunk) {
2035
- init = { diff: currentPatchValue };
1333
+ const downloadedFile = downloadedAssets[content.toString()];
1334
+ if (downloadedFile) {
1335
+ normalizedData = downloadedFile.data;
1336
+ mediaType != null ? mediaType : mediaType = downloadedFile.mediaType;
2036
1337
  } else {
2037
- init = { curr: currentValue };
1338
+ normalizedData = content;
2038
1339
  }
2039
1340
  }
2040
- if (currentPromise) {
2041
- init.next = currentPromise;
2042
- }
2043
- if (initialChunk) {
2044
- init.type = STREAMABLE_VALUE_TYPE;
2045
- }
2046
- return init;
1341
+ } else {
1342
+ normalizedData = convertDataContentToUint8Array(content);
2047
1343
  }
2048
- function updateValueStates(value) {
2049
- currentPatchValue = void 0;
2050
- if (typeof value === "string") {
2051
- if (typeof currentValue === "string") {
2052
- if (value.startsWith(currentValue)) {
2053
- currentPatchValue = [0, value.slice(currentValue.length)];
2054
- }
1344
+ switch (type) {
1345
+ case "image": {
1346
+ if (normalizedData instanceof Uint8Array) {
1347
+ mediaType = (_c = detectMediaType({
1348
+ data: normalizedData,
1349
+ signatures: imageMediaTypeSignatures
1350
+ })) != null ? _c : mediaType;
2055
1351
  }
1352
+ return {
1353
+ type: "file",
1354
+ mediaType: mediaType != null ? mediaType : "image/*",
1355
+ // any image
1356
+ filename: void 0,
1357
+ data: normalizedData instanceof Uint8Array ? convertUint8ArrayToBase642(normalizedData) : normalizedData,
1358
+ providerOptions: (_d = part.providerOptions) != null ? _d : part.experimental_providerMetadata
1359
+ };
2056
1360
  }
2057
- currentValue = value;
2058
- }
2059
- const streamable = {
2060
- set [STREAMABLE_VALUE_INTERNAL_LOCK](state) {
2061
- locked = state;
2062
- },
2063
- get value() {
2064
- return createWrapped(true);
2065
- },
2066
- update(value) {
2067
- assertStream(".update()");
2068
- const resolvePrevious = resolvable.resolve;
2069
- resolvable = createResolvablePromise();
2070
- updateValueStates(value);
2071
- currentPromise = resolvable.promise;
2072
- resolvePrevious(createWrapped());
2073
- warnUnclosedStream();
2074
- return streamable;
2075
- },
2076
- append(value) {
2077
- assertStream(".append()");
2078
- if (typeof currentValue !== "string" && typeof currentValue !== "undefined") {
2079
- throw new Error(
2080
- `.append(): The current value is not a string. Received: ${typeof currentValue}`
2081
- );
2082
- }
2083
- if (typeof value !== "string") {
2084
- throw new Error(
2085
- `.append(): The value is not a string. Received: ${typeof value}`
2086
- );
2087
- }
2088
- const resolvePrevious = resolvable.resolve;
2089
- resolvable = createResolvablePromise();
2090
- if (typeof currentValue === "string") {
2091
- currentPatchValue = [0, value];
2092
- currentValue = currentValue + value;
2093
- } else {
2094
- currentPatchValue = void 0;
2095
- currentValue = value;
2096
- }
2097
- currentPromise = resolvable.promise;
2098
- resolvePrevious(createWrapped());
2099
- warnUnclosedStream();
2100
- return streamable;
2101
- },
2102
- error(error) {
2103
- assertStream(".error()");
2104
- if (warningTimeout) {
2105
- clearTimeout(warningTimeout);
2106
- }
2107
- closed = true;
2108
- currentError = error;
2109
- currentPromise = void 0;
2110
- resolvable.resolve({ error });
2111
- return streamable;
2112
- },
2113
- done(...args) {
2114
- assertStream(".done()");
2115
- if (warningTimeout) {
2116
- clearTimeout(warningTimeout);
2117
- }
2118
- closed = true;
2119
- currentPromise = void 0;
2120
- if (args.length) {
2121
- updateValueStates(args[0]);
2122
- resolvable.resolve(createWrapped());
2123
- return streamable;
1361
+ case "file": {
1362
+ if (mediaType == null) {
1363
+ throw new Error(`Media type is missing for file part`);
2124
1364
  }
2125
- resolvable.resolve({});
2126
- return streamable;
1365
+ return {
1366
+ type: "file",
1367
+ mediaType,
1368
+ filename: part.filename,
1369
+ data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
1370
+ providerOptions: (_e = part.providerOptions) != null ? _e : part.experimental_providerMetadata
1371
+ };
2127
1372
  }
1373
+ }
1374
+ }
1375
+
1376
+ // core/types/usage.ts
1377
+ function calculateLanguageModelUsage({
1378
+ promptTokens,
1379
+ completionTokens
1380
+ }) {
1381
+ return {
1382
+ promptTokens,
1383
+ completionTokens,
1384
+ totalTokens: promptTokens + completionTokens
2128
1385
  };
2129
- return streamable;
2130
1386
  }
1387
+
1388
+ // util/constants.ts
1389
+ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
2131
1390
  export {
2132
- createAI,
2133
- createStreamableUI,
2134
- createStreamableValue,
2135
- getAIState,
2136
- getMutableAIState,
2137
- streamUI
1391
+ HANGING_STREAM_WARNING_TIME_MS,
1392
+ calculateLanguageModelUsage,
1393
+ convertToLanguageModelPrompt,
1394
+ prepareCallSettings,
1395
+ prepareRetries,
1396
+ prepareToolsAndToolChoice,
1397
+ standardizePrompt
2138
1398
  };
2139
- //# sourceMappingURL=rsc-server.mjs.map
1399
+ //# sourceMappingURL=index.mjs.map