@zenning/ai 5.0.41-patched

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1021 @@
1
+ // internal/index.ts
2
+ import { convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
+
4
+ // src/prompt/convert-to-language-model-prompt.ts
5
+ import {
6
+ isUrlSupported
7
+ } from "@ai-sdk/provider-utils";
8
+
9
+ // src/util/detect-media-type.ts
10
+ import { convertBase64ToUint8Array } from "@ai-sdk/provider-utils";
11
+ var imageMediaTypeSignatures = [
12
+ {
13
+ mediaType: "image/gif",
14
+ bytesPrefix: [71, 73, 70],
15
+ base64Prefix: "R0lG"
16
+ },
17
+ {
18
+ mediaType: "image/png",
19
+ bytesPrefix: [137, 80, 78, 71],
20
+ base64Prefix: "iVBORw"
21
+ },
22
+ {
23
+ mediaType: "image/jpeg",
24
+ bytesPrefix: [255, 216],
25
+ base64Prefix: "/9j/"
26
+ },
27
+ {
28
+ mediaType: "image/webp",
29
+ bytesPrefix: [82, 73, 70, 70],
30
+ base64Prefix: "UklGRg"
31
+ },
32
+ {
33
+ mediaType: "image/bmp",
34
+ bytesPrefix: [66, 77],
35
+ base64Prefix: "Qk"
36
+ },
37
+ {
38
+ mediaType: "image/tiff",
39
+ bytesPrefix: [73, 73, 42, 0],
40
+ base64Prefix: "SUkqAA"
41
+ },
42
+ {
43
+ mediaType: "image/tiff",
44
+ bytesPrefix: [77, 77, 0, 42],
45
+ base64Prefix: "TU0AKg"
46
+ },
47
+ {
48
+ mediaType: "image/avif",
49
+ bytesPrefix: [
50
+ 0,
51
+ 0,
52
+ 0,
53
+ 32,
54
+ 102,
55
+ 116,
56
+ 121,
57
+ 112,
58
+ 97,
59
+ 118,
60
+ 105,
61
+ 102
62
+ ],
63
+ base64Prefix: "AAAAIGZ0eXBhdmlm"
64
+ },
65
+ {
66
+ mediaType: "image/heic",
67
+ bytesPrefix: [
68
+ 0,
69
+ 0,
70
+ 0,
71
+ 32,
72
+ 102,
73
+ 116,
74
+ 121,
75
+ 112,
76
+ 104,
77
+ 101,
78
+ 105,
79
+ 99
80
+ ],
81
+ base64Prefix: "AAAAIGZ0eXBoZWlj"
82
+ }
83
+ ];
84
+ var stripID3 = (data) => {
85
+ const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data;
86
+ const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
87
+ return bytes.slice(id3Size + 10);
88
+ };
89
+ function stripID3TagsIfPresent(data) {
90
+ const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && // 'I'
91
+ data[1] === 68 && // 'D'
92
+ data[2] === 51;
93
+ return hasId3 ? stripID3(data) : data;
94
+ }
95
+ function detectMediaType({
96
+ data,
97
+ signatures
98
+ }) {
99
+ const processedData = stripID3TagsIfPresent(data);
100
+ for (const signature of signatures) {
101
+ if (typeof processedData === "string" ? processedData.startsWith(signature.base64Prefix) : processedData.length >= signature.bytesPrefix.length && signature.bytesPrefix.every(
102
+ (byte, index) => processedData[index] === byte
103
+ )) {
104
+ return signature.mediaType;
105
+ }
106
+ }
107
+ return void 0;
108
+ }
109
+
110
+ // src/util/download/download-error.ts
111
+ import { AISDKError } from "@ai-sdk/provider";
112
+ var name = "AI_DownloadError";
113
+ var marker = `vercel.ai.error.${name}`;
114
+ var symbol = Symbol.for(marker);
115
+ var _a;
116
+ var DownloadError = class extends AISDKError {
117
+ constructor({
118
+ url,
119
+ statusCode,
120
+ statusText,
121
+ cause,
122
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
123
+ }) {
124
+ super({ name, message, cause });
125
+ this[_a] = true;
126
+ this.url = url;
127
+ this.statusCode = statusCode;
128
+ this.statusText = statusText;
129
+ }
130
+ static isInstance(error) {
131
+ return AISDKError.hasMarker(error, marker);
132
+ }
133
+ };
134
+ _a = symbol;
135
+
136
+ // src/util/download/download.ts
137
+ var download = async ({ url }) => {
138
+ var _a5;
139
+ const urlText = url.toString();
140
+ try {
141
+ const response = await fetch(urlText);
142
+ if (!response.ok) {
143
+ throw new DownloadError({
144
+ url: urlText,
145
+ statusCode: response.status,
146
+ statusText: response.statusText
147
+ });
148
+ }
149
+ return {
150
+ data: new Uint8Array(await response.arrayBuffer()),
151
+ mediaType: (_a5 = response.headers.get("content-type")) != null ? _a5 : void 0
152
+ };
153
+ } catch (error) {
154
+ if (DownloadError.isInstance(error)) {
155
+ throw error;
156
+ }
157
+ throw new DownloadError({ url: urlText, cause: error });
158
+ }
159
+ };
160
+
161
+ // src/util/download/download-function.ts
162
+ var createDefaultDownloadFunction = (download2 = download) => (requestedDownloads) => Promise.all(
163
+ requestedDownloads.map(
164
+ async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : download2(requestedDownload)
165
+ )
166
+ );
167
+
168
+ // src/prompt/data-content.ts
169
+ import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
170
+ import {
171
+ convertBase64ToUint8Array as convertBase64ToUint8Array2,
172
+ convertUint8ArrayToBase64
173
+ } from "@ai-sdk/provider-utils";
174
+ import { z } from "zod/v4";
175
+
176
+ // src/prompt/split-data-url.ts
177
+ function splitDataUrl(dataUrl) {
178
+ try {
179
+ const [header, base64Content] = dataUrl.split(",");
180
+ return {
181
+ mediaType: header.split(";")[0].split(":")[1],
182
+ base64Content
183
+ };
184
+ } catch (error) {
185
+ return {
186
+ mediaType: void 0,
187
+ base64Content: void 0
188
+ };
189
+ }
190
+ }
191
+
192
+ // src/prompt/data-content.ts
193
+ var dataContentSchema = z.union([
194
+ z.string(),
195
+ z.instanceof(Uint8Array),
196
+ z.instanceof(ArrayBuffer),
197
+ z.custom(
198
+ // Buffer might not be available in some environments such as CloudFlare:
199
+ (value) => {
200
+ var _a5, _b;
201
+ return (_b = (_a5 = globalThis.Buffer) == null ? void 0 : _a5.isBuffer(value)) != null ? _b : false;
202
+ },
203
+ { message: "Must be a Buffer" }
204
+ )
205
+ ]);
206
+ function convertToLanguageModelV2DataContent(content) {
207
+ if (content instanceof Uint8Array) {
208
+ return { data: content, mediaType: void 0 };
209
+ }
210
+ if (content instanceof ArrayBuffer) {
211
+ return { data: new Uint8Array(content), mediaType: void 0 };
212
+ }
213
+ if (typeof content === "string") {
214
+ try {
215
+ content = new URL(content);
216
+ } catch (error) {
217
+ }
218
+ }
219
+ if (content instanceof URL && content.protocol === "data:") {
220
+ const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(
221
+ content.toString()
222
+ );
223
+ if (dataUrlMediaType == null || base64Content == null) {
224
+ throw new AISDKError2({
225
+ name: "InvalidDataContentError",
226
+ message: `Invalid data URL format in content ${content.toString()}`
227
+ });
228
+ }
229
+ return { data: base64Content, mediaType: dataUrlMediaType };
230
+ }
231
+ return { data: content, mediaType: void 0 };
232
+ }
233
+
234
+ // src/prompt/invalid-message-role-error.ts
235
+ import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
236
+ var name2 = "AI_InvalidMessageRoleError";
237
+ var marker2 = `vercel.ai.error.${name2}`;
238
+ var symbol2 = Symbol.for(marker2);
239
+ var _a2;
240
+ var InvalidMessageRoleError = class extends AISDKError3 {
241
+ constructor({
242
+ role,
243
+ message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
244
+ }) {
245
+ super({ name: name2, message });
246
+ this[_a2] = true;
247
+ this.role = role;
248
+ }
249
+ static isInstance(error) {
250
+ return AISDKError3.hasMarker(error, marker2);
251
+ }
252
+ };
253
+ _a2 = symbol2;
254
+
255
+ // src/prompt/convert-to-language-model-prompt.ts
256
+ async function convertToLanguageModelPrompt({
257
+ prompt,
258
+ supportedUrls,
259
+ download: download2 = createDefaultDownloadFunction()
260
+ }) {
261
+ const downloadedAssets = await downloadAssets(
262
+ prompt.messages,
263
+ download2,
264
+ supportedUrls
265
+ );
266
+ return [
267
+ ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
268
+ ...prompt.messages.map(
269
+ (message) => convertToLanguageModelMessage({ message, downloadedAssets })
270
+ )
271
+ ];
272
+ }
273
+ function convertToLanguageModelMessage({
274
+ message,
275
+ downloadedAssets
276
+ }) {
277
+ const role = message.role;
278
+ switch (role) {
279
+ case "system": {
280
+ return {
281
+ role: "system",
282
+ content: message.content,
283
+ providerOptions: message.providerOptions
284
+ };
285
+ }
286
+ case "user": {
287
+ if (typeof message.content === "string") {
288
+ return {
289
+ role: "user",
290
+ content: [{ type: "text", text: message.content }],
291
+ providerOptions: message.providerOptions
292
+ };
293
+ }
294
+ return {
295
+ role: "user",
296
+ content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
297
+ providerOptions: message.providerOptions
298
+ };
299
+ }
300
+ case "assistant": {
301
+ if (typeof message.content === "string") {
302
+ return {
303
+ role: "assistant",
304
+ content: [{ type: "text", text: message.content }],
305
+ providerOptions: message.providerOptions
306
+ };
307
+ }
308
+ return {
309
+ role: "assistant",
310
+ content: message.content.filter(
311
+ // remove empty text parts:
312
+ (part) => part.type !== "text" || part.text !== ""
313
+ ).map((part) => {
314
+ const providerOptions = part.providerOptions;
315
+ switch (part.type) {
316
+ case "file": {
317
+ const { data, mediaType } = convertToLanguageModelV2DataContent(
318
+ part.data
319
+ );
320
+ return {
321
+ type: "file",
322
+ data,
323
+ filename: part.filename,
324
+ mediaType: mediaType != null ? mediaType : part.mediaType,
325
+ providerOptions
326
+ };
327
+ }
328
+ case "reasoning": {
329
+ return {
330
+ type: "reasoning",
331
+ text: part.text,
332
+ providerOptions
333
+ };
334
+ }
335
+ case "text": {
336
+ return {
337
+ type: "text",
338
+ text: part.text,
339
+ providerOptions
340
+ };
341
+ }
342
+ case "tool-call": {
343
+ return {
344
+ type: "tool-call",
345
+ toolCallId: part.toolCallId,
346
+ toolName: part.toolName,
347
+ input: part.input,
348
+ providerExecuted: part.providerExecuted,
349
+ providerOptions
350
+ };
351
+ }
352
+ case "tool-result": {
353
+ return {
354
+ type: "tool-result",
355
+ toolCallId: part.toolCallId,
356
+ toolName: part.toolName,
357
+ output: part.output,
358
+ providerOptions
359
+ };
360
+ }
361
+ }
362
+ }),
363
+ providerOptions: message.providerOptions
364
+ };
365
+ }
366
+ case "tool": {
367
+ return {
368
+ role: "tool",
369
+ content: message.content.map((part) => ({
370
+ type: "tool-result",
371
+ toolCallId: part.toolCallId,
372
+ toolName: part.toolName,
373
+ output: part.output,
374
+ providerOptions: part.providerOptions
375
+ })),
376
+ providerOptions: message.providerOptions
377
+ };
378
+ }
379
+ default: {
380
+ const _exhaustiveCheck = role;
381
+ throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
382
+ }
383
+ }
384
+ }
385
+ async function downloadAssets(messages, download2, supportedUrls) {
386
+ const plannedDownloads = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
387
+ (content) => Array.isArray(content)
388
+ ).flat().filter(
389
+ (part) => part.type === "image" || part.type === "file"
390
+ ).map((part) => {
391
+ var _a5;
392
+ const mediaType = (_a5 = part.mediaType) != null ? _a5 : part.type === "image" ? "image/*" : void 0;
393
+ let data = part.type === "image" ? part.image : part.data;
394
+ if (typeof data === "string") {
395
+ try {
396
+ data = new URL(data);
397
+ } catch (ignored) {
398
+ }
399
+ }
400
+ return { mediaType, data };
401
+ }).filter(
402
+ (part) => part.data instanceof URL
403
+ ).map((part) => ({
404
+ url: part.data,
405
+ isUrlSupportedByModel: part.mediaType != null && isUrlSupported({
406
+ url: part.data.toString(),
407
+ mediaType: part.mediaType,
408
+ supportedUrls
409
+ })
410
+ }));
411
+ const downloadedFiles = await download2(plannedDownloads);
412
+ return Object.fromEntries(
413
+ downloadedFiles.filter(
414
+ (downloadedFile) => (downloadedFile == null ? void 0 : downloadedFile.data) != null
415
+ ).map(({ data, mediaType }, index) => [
416
+ plannedDownloads[index].url.toString(),
417
+ { data, mediaType }
418
+ ])
419
+ );
420
+ }
421
+ function convertPartToLanguageModelPart(part, downloadedAssets) {
422
+ var _a5;
423
+ if (part.type === "text") {
424
+ return {
425
+ type: "text",
426
+ text: part.text,
427
+ providerOptions: part.providerOptions
428
+ };
429
+ }
430
+ let originalData;
431
+ const type = part.type;
432
+ switch (type) {
433
+ case "image":
434
+ originalData = part.image;
435
+ break;
436
+ case "file":
437
+ originalData = part.data;
438
+ break;
439
+ default:
440
+ throw new Error(`Unsupported part type: ${type}`);
441
+ }
442
+ const { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV2DataContent(originalData);
443
+ let mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;
444
+ let data = convertedData;
445
+ if (data instanceof URL) {
446
+ const downloadedFile = downloadedAssets[data.toString()];
447
+ if (downloadedFile) {
448
+ data = downloadedFile.data;
449
+ mediaType != null ? mediaType : mediaType = downloadedFile.mediaType;
450
+ }
451
+ }
452
+ switch (type) {
453
+ case "image": {
454
+ if (data instanceof Uint8Array || typeof data === "string") {
455
+ mediaType = (_a5 = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _a5 : mediaType;
456
+ }
457
+ return {
458
+ type: "file",
459
+ mediaType: mediaType != null ? mediaType : "image/*",
460
+ // any image
461
+ filename: void 0,
462
+ data,
463
+ providerOptions: part.providerOptions
464
+ };
465
+ }
466
+ case "file": {
467
+ if (mediaType == null) {
468
+ throw new Error(`Media type is missing for file part`);
469
+ }
470
+ return {
471
+ type: "file",
472
+ mediaType,
473
+ filename: part.filename,
474
+ data,
475
+ providerOptions: part.providerOptions
476
+ };
477
+ }
478
+ }
479
+ }
480
+
481
+ // src/prompt/prepare-tools-and-tool-choice.ts
482
+ import { asSchema } from "@ai-sdk/provider-utils";
483
+
484
+ // src/util/is-non-empty-object.ts
485
+ function isNonEmptyObject(object) {
486
+ return object != null && Object.keys(object).length > 0;
487
+ }
488
+
489
+ // src/prompt/prepare-tools-and-tool-choice.ts
490
+ function prepareToolsAndToolChoice({
491
+ tools,
492
+ toolChoice,
493
+ activeTools
494
+ }) {
495
+ if (!isNonEmptyObject(tools)) {
496
+ return {
497
+ tools: void 0,
498
+ toolChoice: void 0
499
+ };
500
+ }
501
+ const filteredTools = activeTools != null ? Object.entries(tools).filter(
502
+ ([name5]) => activeTools.includes(name5)
503
+ ) : Object.entries(tools);
504
+ return {
505
+ tools: filteredTools.map(([name5, tool]) => {
506
+ const toolType = tool.type;
507
+ switch (toolType) {
508
+ case void 0:
509
+ case "dynamic":
510
+ case "function":
511
+ return {
512
+ type: "function",
513
+ name: name5,
514
+ description: tool.description,
515
+ inputSchema: asSchema(tool.inputSchema).jsonSchema,
516
+ providerOptions: tool.providerOptions
517
+ };
518
+ case "provider-defined":
519
+ return {
520
+ type: "provider-defined",
521
+ name: name5,
522
+ id: tool.id,
523
+ args: tool.args
524
+ };
525
+ default: {
526
+ const exhaustiveCheck = toolType;
527
+ throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
528
+ }
529
+ }
530
+ }),
531
+ toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
532
+ };
533
+ }
534
+
535
+ // src/prompt/standardize-prompt.ts
536
+ import { InvalidPromptError } from "@ai-sdk/provider";
537
+ import { safeValidateTypes } from "@ai-sdk/provider-utils";
538
+ import { z as z6 } from "zod/v4";
539
+
540
+ // src/prompt/message.ts
541
+ import { z as z5 } from "zod/v4";
542
+
543
+ // src/types/provider-metadata.ts
544
+ import { z as z3 } from "zod/v4";
545
+
546
+ // src/types/json-value.ts
547
+ import { z as z2 } from "zod/v4";
548
+ var jsonValueSchema = z2.lazy(
549
+ () => z2.union([
550
+ z2.null(),
551
+ z2.string(),
552
+ z2.number(),
553
+ z2.boolean(),
554
+ z2.record(z2.string(), jsonValueSchema),
555
+ z2.array(jsonValueSchema)
556
+ ])
557
+ );
558
+
559
+ // src/types/provider-metadata.ts
560
+ var providerMetadataSchema = z3.record(
561
+ z3.string(),
562
+ z3.record(z3.string(), jsonValueSchema)
563
+ );
564
+
565
+ // src/prompt/content-part.ts
566
+ import { z as z4 } from "zod/v4";
567
+ var textPartSchema = z4.object({
568
+ type: z4.literal("text"),
569
+ text: z4.string(),
570
+ providerOptions: providerMetadataSchema.optional()
571
+ });
572
+ var imagePartSchema = z4.object({
573
+ type: z4.literal("image"),
574
+ image: z4.union([dataContentSchema, z4.instanceof(URL)]),
575
+ mediaType: z4.string().optional(),
576
+ providerOptions: providerMetadataSchema.optional()
577
+ });
578
+ var filePartSchema = z4.object({
579
+ type: z4.literal("file"),
580
+ data: z4.union([dataContentSchema, z4.instanceof(URL)]),
581
+ filename: z4.string().optional(),
582
+ mediaType: z4.string(),
583
+ providerOptions: providerMetadataSchema.optional()
584
+ });
585
+ var reasoningPartSchema = z4.object({
586
+ type: z4.literal("reasoning"),
587
+ text: z4.string(),
588
+ providerOptions: providerMetadataSchema.optional()
589
+ });
590
+ var toolCallPartSchema = z4.object({
591
+ type: z4.literal("tool-call"),
592
+ toolCallId: z4.string(),
593
+ toolName: z4.string(),
594
+ input: z4.unknown(),
595
+ providerOptions: providerMetadataSchema.optional(),
596
+ providerExecuted: z4.boolean().optional()
597
+ });
598
+ var outputSchema = z4.discriminatedUnion("type", [
599
+ z4.object({
600
+ type: z4.literal("text"),
601
+ value: z4.string()
602
+ }),
603
+ z4.object({
604
+ type: z4.literal("json"),
605
+ value: jsonValueSchema
606
+ }),
607
+ z4.object({
608
+ type: z4.literal("error-text"),
609
+ value: z4.string()
610
+ }),
611
+ z4.object({
612
+ type: z4.literal("error-json"),
613
+ value: jsonValueSchema
614
+ }),
615
+ z4.object({
616
+ type: z4.literal("content"),
617
+ value: z4.array(
618
+ z4.union([
619
+ z4.object({
620
+ type: z4.literal("text"),
621
+ text: z4.string()
622
+ }),
623
+ z4.object({
624
+ type: z4.literal("media"),
625
+ data: z4.string(),
626
+ mediaType: z4.string()
627
+ })
628
+ ])
629
+ )
630
+ })
631
+ ]);
632
+ var toolResultPartSchema = z4.object({
633
+ type: z4.literal("tool-result"),
634
+ toolCallId: z4.string(),
635
+ toolName: z4.string(),
636
+ output: outputSchema,
637
+ providerOptions: providerMetadataSchema.optional()
638
+ });
639
+
640
+ // src/prompt/message.ts
641
+ var systemModelMessageSchema = z5.object(
642
+ {
643
+ role: z5.literal("system"),
644
+ content: z5.string(),
645
+ providerOptions: providerMetadataSchema.optional()
646
+ }
647
+ );
648
+ var userModelMessageSchema = z5.object({
649
+ role: z5.literal("user"),
650
+ content: z5.union([
651
+ z5.string(),
652
+ z5.array(z5.union([textPartSchema, imagePartSchema, filePartSchema]))
653
+ ]),
654
+ providerOptions: providerMetadataSchema.optional()
655
+ });
656
+ var assistantModelMessageSchema = z5.object({
657
+ role: z5.literal("assistant"),
658
+ content: z5.union([
659
+ z5.string(),
660
+ z5.array(
661
+ z5.union([
662
+ textPartSchema,
663
+ filePartSchema,
664
+ reasoningPartSchema,
665
+ toolCallPartSchema,
666
+ toolResultPartSchema
667
+ ])
668
+ )
669
+ ]),
670
+ providerOptions: providerMetadataSchema.optional()
671
+ });
672
+ var toolModelMessageSchema = z5.object({
673
+ role: z5.literal("tool"),
674
+ content: z5.array(toolResultPartSchema),
675
+ providerOptions: providerMetadataSchema.optional()
676
+ });
677
+ var modelMessageSchema = z5.union([
678
+ systemModelMessageSchema,
679
+ userModelMessageSchema,
680
+ assistantModelMessageSchema,
681
+ toolModelMessageSchema
682
+ ]);
683
+
684
+ // src/prompt/standardize-prompt.ts
685
+ async function standardizePrompt(prompt) {
686
+ if (prompt.prompt == null && prompt.messages == null) {
687
+ throw new InvalidPromptError({
688
+ prompt,
689
+ message: "prompt or messages must be defined"
690
+ });
691
+ }
692
+ if (prompt.prompt != null && prompt.messages != null) {
693
+ throw new InvalidPromptError({
694
+ prompt,
695
+ message: "prompt and messages cannot be defined at the same time"
696
+ });
697
+ }
698
+ if (prompt.system != null && typeof prompt.system !== "string") {
699
+ throw new InvalidPromptError({
700
+ prompt,
701
+ message: "system must be a string"
702
+ });
703
+ }
704
+ let messages;
705
+ if (prompt.prompt != null && typeof prompt.prompt === "string") {
706
+ messages = [{ role: "user", content: prompt.prompt }];
707
+ } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {
708
+ messages = prompt.prompt;
709
+ } else if (prompt.messages != null) {
710
+ messages = prompt.messages;
711
+ } else {
712
+ throw new InvalidPromptError({
713
+ prompt,
714
+ message: "prompt or messages must be defined"
715
+ });
716
+ }
717
+ if (messages.length === 0) {
718
+ throw new InvalidPromptError({
719
+ prompt,
720
+ message: "messages must not be empty"
721
+ });
722
+ }
723
+ const validationResult = await safeValidateTypes({
724
+ value: messages,
725
+ schema: z6.array(modelMessageSchema)
726
+ });
727
+ if (!validationResult.success) {
728
+ throw new InvalidPromptError({
729
+ prompt,
730
+ message: "The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",
731
+ cause: validationResult.error
732
+ });
733
+ }
734
+ return {
735
+ messages,
736
+ system: prompt.system
737
+ };
738
+ }
739
+
740
+ // src/error/invalid-argument-error.ts
741
+ import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
742
+ var name3 = "AI_InvalidArgumentError";
743
+ var marker3 = `vercel.ai.error.${name3}`;
744
+ var symbol3 = Symbol.for(marker3);
745
+ var _a3;
746
+ var InvalidArgumentError = class extends AISDKError4 {
747
+ constructor({
748
+ parameter,
749
+ value,
750
+ message
751
+ }) {
752
+ super({
753
+ name: name3,
754
+ message: `Invalid argument for parameter ${parameter}: ${message}`
755
+ });
756
+ this[_a3] = true;
757
+ this.parameter = parameter;
758
+ this.value = value;
759
+ }
760
+ static isInstance(error) {
761
+ return AISDKError4.hasMarker(error, marker3);
762
+ }
763
+ };
764
+ _a3 = symbol3;
765
+
766
+ // src/prompt/prepare-call-settings.ts
767
+ function prepareCallSettings({
768
+ maxOutputTokens,
769
+ temperature,
770
+ topP,
771
+ topK,
772
+ presencePenalty,
773
+ frequencyPenalty,
774
+ seed,
775
+ stopSequences
776
+ }) {
777
+ if (maxOutputTokens != null) {
778
+ if (!Number.isInteger(maxOutputTokens)) {
779
+ throw new InvalidArgumentError({
780
+ parameter: "maxOutputTokens",
781
+ value: maxOutputTokens,
782
+ message: "maxOutputTokens must be an integer"
783
+ });
784
+ }
785
+ if (maxOutputTokens < 1) {
786
+ throw new InvalidArgumentError({
787
+ parameter: "maxOutputTokens",
788
+ value: maxOutputTokens,
789
+ message: "maxOutputTokens must be >= 1"
790
+ });
791
+ }
792
+ }
793
+ if (temperature != null) {
794
+ if (typeof temperature !== "number") {
795
+ throw new InvalidArgumentError({
796
+ parameter: "temperature",
797
+ value: temperature,
798
+ message: "temperature must be a number"
799
+ });
800
+ }
801
+ }
802
+ if (topP != null) {
803
+ if (typeof topP !== "number") {
804
+ throw new InvalidArgumentError({
805
+ parameter: "topP",
806
+ value: topP,
807
+ message: "topP must be a number"
808
+ });
809
+ }
810
+ }
811
+ if (topK != null) {
812
+ if (typeof topK !== "number") {
813
+ throw new InvalidArgumentError({
814
+ parameter: "topK",
815
+ value: topK,
816
+ message: "topK must be a number"
817
+ });
818
+ }
819
+ }
820
+ if (presencePenalty != null) {
821
+ if (typeof presencePenalty !== "number") {
822
+ throw new InvalidArgumentError({
823
+ parameter: "presencePenalty",
824
+ value: presencePenalty,
825
+ message: "presencePenalty must be a number"
826
+ });
827
+ }
828
+ }
829
+ if (frequencyPenalty != null) {
830
+ if (typeof frequencyPenalty !== "number") {
831
+ throw new InvalidArgumentError({
832
+ parameter: "frequencyPenalty",
833
+ value: frequencyPenalty,
834
+ message: "frequencyPenalty must be a number"
835
+ });
836
+ }
837
+ }
838
+ if (seed != null) {
839
+ if (!Number.isInteger(seed)) {
840
+ throw new InvalidArgumentError({
841
+ parameter: "seed",
842
+ value: seed,
843
+ message: "seed must be an integer"
844
+ });
845
+ }
846
+ }
847
+ return {
848
+ maxOutputTokens,
849
+ temperature,
850
+ topP,
851
+ topK,
852
+ presencePenalty,
853
+ frequencyPenalty,
854
+ stopSequences,
855
+ seed
856
+ };
857
+ }
858
+
859
+ // src/util/retry-with-exponential-backoff.ts
860
+ import { APICallError } from "@ai-sdk/provider";
861
+ import { delay, getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
862
+
863
+ // src/util/retry-error.ts
864
+ import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
865
+ var name4 = "AI_RetryError";
866
+ var marker4 = `vercel.ai.error.${name4}`;
867
+ var symbol4 = Symbol.for(marker4);
868
+ var _a4;
869
+ var RetryError = class extends AISDKError5 {
870
+ constructor({
871
+ message,
872
+ reason,
873
+ errors
874
+ }) {
875
+ super({ name: name4, message });
876
+ this[_a4] = true;
877
+ this.reason = reason;
878
+ this.errors = errors;
879
+ this.lastError = errors[errors.length - 1];
880
+ }
881
+ static isInstance(error) {
882
+ return AISDKError5.hasMarker(error, marker4);
883
+ }
884
+ };
885
+ _a4 = symbol4;
886
+
887
+ // src/util/retry-with-exponential-backoff.ts
888
+ function getRetryDelayInMs({
889
+ error,
890
+ exponentialBackoffDelay
891
+ }) {
892
+ const headers = error.responseHeaders;
893
+ if (!headers)
894
+ return exponentialBackoffDelay;
895
+ let ms;
896
+ const retryAfterMs = headers["retry-after-ms"];
897
+ if (retryAfterMs) {
898
+ const timeoutMs = parseFloat(retryAfterMs);
899
+ if (!Number.isNaN(timeoutMs)) {
900
+ ms = timeoutMs;
901
+ }
902
+ }
903
+ const retryAfter = headers["retry-after"];
904
+ if (retryAfter && ms === void 0) {
905
+ const timeoutSeconds = parseFloat(retryAfter);
906
+ if (!Number.isNaN(timeoutSeconds)) {
907
+ ms = timeoutSeconds * 1e3;
908
+ } else {
909
+ ms = Date.parse(retryAfter) - Date.now();
910
+ }
911
+ }
912
+ if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) {
913
+ return ms;
914
+ }
915
+ return exponentialBackoffDelay;
916
+ }
917
+ var retryWithExponentialBackoffRespectingRetryHeaders = ({
918
+ maxRetries = 2,
919
+ initialDelayInMs = 2e3,
920
+ backoffFactor = 2,
921
+ abortSignal
922
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
923
+ maxRetries,
924
+ delayInMs: initialDelayInMs,
925
+ backoffFactor,
926
+ abortSignal
927
+ });
928
+ async function _retryWithExponentialBackoff(f, {
929
+ maxRetries,
930
+ delayInMs,
931
+ backoffFactor,
932
+ abortSignal
933
+ }, errors = []) {
934
+ try {
935
+ return await f();
936
+ } catch (error) {
937
+ if (isAbortError(error)) {
938
+ throw error;
939
+ }
940
+ if (maxRetries === 0) {
941
+ throw error;
942
+ }
943
+ const errorMessage = getErrorMessage(error);
944
+ const newErrors = [...errors, error];
945
+ const tryNumber = newErrors.length;
946
+ if (tryNumber > maxRetries) {
947
+ throw new RetryError({
948
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
949
+ reason: "maxRetriesExceeded",
950
+ errors: newErrors
951
+ });
952
+ }
953
+ if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
954
+ await delay(
955
+ getRetryDelayInMs({
956
+ error,
957
+ exponentialBackoffDelay: delayInMs
958
+ }),
959
+ { abortSignal }
960
+ );
961
+ return _retryWithExponentialBackoff(
962
+ f,
963
+ {
964
+ maxRetries,
965
+ delayInMs: backoffFactor * delayInMs,
966
+ backoffFactor,
967
+ abortSignal
968
+ },
969
+ newErrors
970
+ );
971
+ }
972
+ if (tryNumber === 1) {
973
+ throw error;
974
+ }
975
+ throw new RetryError({
976
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
977
+ reason: "errorNotRetryable",
978
+ errors: newErrors
979
+ });
980
+ }
981
+ }
982
+
983
+ // src/util/prepare-retries.ts
984
+ function prepareRetries({
985
+ maxRetries,
986
+ abortSignal
987
+ }) {
988
+ if (maxRetries != null) {
989
+ if (!Number.isInteger(maxRetries)) {
990
+ throw new InvalidArgumentError({
991
+ parameter: "maxRetries",
992
+ value: maxRetries,
993
+ message: "maxRetries must be an integer"
994
+ });
995
+ }
996
+ if (maxRetries < 0) {
997
+ throw new InvalidArgumentError({
998
+ parameter: "maxRetries",
999
+ value: maxRetries,
1000
+ message: "maxRetries must be >= 0"
1001
+ });
1002
+ }
1003
+ }
1004
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
1005
+ return {
1006
+ maxRetries: maxRetriesResult,
1007
+ retry: retryWithExponentialBackoffRespectingRetryHeaders({
1008
+ maxRetries: maxRetriesResult,
1009
+ abortSignal
1010
+ })
1011
+ };
1012
+ }
1013
+ export {
1014
+ convertAsyncIteratorToReadableStream,
1015
+ convertToLanguageModelPrompt,
1016
+ prepareCallSettings,
1017
+ prepareRetries,
1018
+ prepareToolsAndToolChoice,
1019
+ standardizePrompt
1020
+ };
1021
+ //# sourceMappingURL=index.mjs.map