ai 3.0.13 → 3.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/ai-model-specification/dist/index.d.mts +704 -0
  2. package/ai-model-specification/dist/index.d.ts +704 -0
  3. package/ai-model-specification/dist/index.js +806 -0
  4. package/ai-model-specification/dist/index.js.map +1 -0
  5. package/ai-model-specification/dist/index.mjs +742 -0
  6. package/ai-model-specification/dist/index.mjs.map +1 -0
  7. package/dist/index.d.mts +683 -2
  8. package/dist/index.d.ts +683 -2
  9. package/dist/index.js +1723 -15
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +1700 -15
  12. package/dist/index.mjs.map +1 -1
  13. package/mistral/dist/index.d.mts +367 -0
  14. package/mistral/dist/index.d.ts +367 -0
  15. package/mistral/dist/index.js +936 -0
  16. package/mistral/dist/index.js.map +1 -0
  17. package/mistral/dist/index.mjs +900 -0
  18. package/mistral/dist/index.mjs.map +1 -0
  19. package/openai/dist/index.d.mts +430 -0
  20. package/openai/dist/index.d.ts +430 -0
  21. package/openai/dist/index.js +1355 -0
  22. package/openai/dist/index.js.map +1 -0
  23. package/openai/dist/index.mjs +1319 -0
  24. package/openai/dist/index.mjs.map +1 -0
  25. package/package.json +30 -4
  26. package/prompts/dist/index.d.mts +13 -1
  27. package/prompts/dist/index.d.ts +13 -1
  28. package/prompts/dist/index.js +13 -0
  29. package/prompts/dist/index.js.map +1 -1
  30. package/prompts/dist/index.mjs +12 -0
  31. package/prompts/dist/index.mjs.map +1 -1
  32. package/react/dist/index.js +35 -34
  33. package/react/dist/index.js.map +1 -1
  34. package/react/dist/index.mjs +35 -34
  35. package/react/dist/index.mjs.map +1 -1
  36. package/rsc/dist/index.d.ts +45 -8
  37. package/rsc/dist/rsc-server.d.mts +45 -8
  38. package/rsc/dist/rsc-server.mjs +67 -13
  39. package/rsc/dist/rsc-server.mjs.map +1 -1
  40. package/rsc/dist/rsc-shared.d.mts +5 -8
  41. package/rsc/dist/rsc-shared.mjs +23 -2
  42. package/rsc/dist/rsc-shared.mjs.map +1 -1
  43. package/solid/dist/index.js +29 -27
  44. package/solid/dist/index.js.map +1 -1
  45. package/solid/dist/index.mjs +29 -27
  46. package/solid/dist/index.mjs.map +1 -1
  47. package/svelte/dist/index.js +31 -29
  48. package/svelte/dist/index.js.map +1 -1
  49. package/svelte/dist/index.mjs +31 -29
  50. package/svelte/dist/index.mjs.map +1 -1
  51. package/vue/dist/index.js +29 -27
  52. package/vue/dist/index.js.map +1 -1
  53. package/vue/dist/index.mjs +29 -27
  54. package/vue/dist/index.mjs.map +1 -1
package/dist/index.mjs CHANGED
@@ -1,5 +1,1675 @@
1
- // shared/utils.ts
1
+ // core/generate-object/generate-object.ts
2
+ import zodToJsonSchema from "zod-to-json-schema";
3
+
4
+ // ai-model-specification/errors/api-call-error.ts
5
+ var APICallError = class extends Error {
6
+ constructor({
7
+ message,
8
+ url,
9
+ requestBodyValues,
10
+ statusCode,
11
+ responseBody,
12
+ cause,
13
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
14
+ statusCode === 409 || // conflict
15
+ statusCode === 429 || // too many requests
16
+ statusCode >= 500),
17
+ // server error
18
+ data
19
+ }) {
20
+ super(message);
21
+ this.name = "AI_APICallError";
22
+ this.url = url;
23
+ this.requestBodyValues = requestBodyValues;
24
+ this.statusCode = statusCode;
25
+ this.responseBody = responseBody;
26
+ this.cause = cause;
27
+ this.isRetryable = isRetryable;
28
+ this.data = data;
29
+ }
30
+ static isAPICallError(error) {
31
+ return error instanceof Error && error.name === "AI_APICallError" && typeof error.url === "string" && typeof error.requestBodyValues === "object" && (error.statusCode == null || typeof error.statusCode === "number") && (error.responseBody == null || typeof error.responseBody === "string") && (error.cause == null || typeof error.cause === "object") && typeof error.isRetryable === "boolean" && (error.data == null || typeof error.data === "object");
32
+ }
33
+ toJSON() {
34
+ return {
35
+ name: this.name,
36
+ message: this.message,
37
+ url: this.url,
38
+ requestBodyValues: this.requestBodyValues,
39
+ statusCode: this.statusCode,
40
+ responseBody: this.responseBody,
41
+ cause: this.cause,
42
+ isRetryable: this.isRetryable,
43
+ data: this.data
44
+ };
45
+ }
46
+ };
47
+
48
+ // ai-model-specification/errors/invalid-argument-error.ts
49
+ var InvalidArgumentError = class extends Error {
50
+ constructor({
51
+ parameter,
52
+ value,
53
+ message
54
+ }) {
55
+ super(`Invalid argument for parameter ${parameter}: ${message}`);
56
+ this.name = "AI_InvalidArgumentError";
57
+ this.parameter = parameter;
58
+ this.value = value;
59
+ }
60
+ static isInvalidArgumentError(error) {
61
+ return error instanceof Error && error.name === "AI_InvalidArgumentError" && typeof error.parameter === "string" && typeof error.value === "string";
62
+ }
63
+ toJSON() {
64
+ return {
65
+ name: this.name,
66
+ message: this.message,
67
+ stack: this.stack,
68
+ parameter: this.parameter,
69
+ value: this.value
70
+ };
71
+ }
72
+ };
73
+
74
+ // ai-model-specification/errors/invalid-data-content-error.ts
75
+ var InvalidDataContentError = class extends Error {
76
+ constructor({
77
+ content,
78
+ message = `Invalid data content. Expected a string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
79
+ }) {
80
+ super(message);
81
+ this.name = "AI_InvalidDataContentError";
82
+ this.content = content;
83
+ }
84
+ static isInvalidDataContentError(error) {
85
+ return error instanceof Error && error.name === "AI_InvalidDataContentError" && error.content != null;
86
+ }
87
+ toJSON() {
88
+ return {
89
+ name: this.name,
90
+ message: this.message,
91
+ stack: this.stack,
92
+ content: this.content
93
+ };
94
+ }
95
+ };
96
+
97
+ // ai-model-specification/util/get-error-message.ts
98
+ function getErrorMessage(error) {
99
+ if (error == null) {
100
+ return "unknown error";
101
+ }
102
+ if (typeof error === "string") {
103
+ return error;
104
+ }
105
+ if (error instanceof Error) {
106
+ return error.message;
107
+ }
108
+ return JSON.stringify(error);
109
+ }
110
+
111
+ // ai-model-specification/util/parse-json.ts
112
+ import SecureJSON from "secure-json-parse";
113
+
114
+ // ai-model-specification/errors/json-parse-error.ts
115
+ var JSONParseError = class extends Error {
116
+ constructor({ text, cause }) {
117
+ super(
118
+ `JSON parsing failed: Text: ${text}.
119
+ Error message: ${getErrorMessage(cause)}`
120
+ );
121
+ this.name = "AI_JSONParseError";
122
+ this.cause = cause;
123
+ this.text = text;
124
+ }
125
+ static isJSONParseError(error) {
126
+ return error instanceof Error && error.name === "AI_JSONParseError" && typeof error.text === "string" && typeof error.cause === "string";
127
+ }
128
+ toJSON() {
129
+ return {
130
+ name: this.name,
131
+ message: this.message,
132
+ cause: this.cause,
133
+ stack: this.stack,
134
+ valueText: this.text
135
+ };
136
+ }
137
+ };
138
+
139
+ // ai-model-specification/errors/type-validation-error.ts
140
+ var TypeValidationError = class extends Error {
141
+ constructor({ value, cause }) {
142
+ super(
143
+ `Type validation failed: Value: ${JSON.stringify(value)}.
144
+ Error message: ${getErrorMessage(cause)}`
145
+ );
146
+ this.name = "AI_TypeValidationError";
147
+ this.cause = cause;
148
+ this.value = value;
149
+ }
150
+ static isTypeValidationError(error) {
151
+ return error instanceof Error && error.name === "AI_TypeValidationError" && typeof error.value === "string" && typeof error.cause === "string";
152
+ }
153
+ toJSON() {
154
+ return {
155
+ name: this.name,
156
+ message: this.message,
157
+ cause: this.cause,
158
+ stack: this.stack,
159
+ value: this.value
160
+ };
161
+ }
162
+ };
163
+
164
+ // ai-model-specification/util/validate-types.ts
165
+ function safeValidateTypes({
166
+ value,
167
+ schema
168
+ }) {
169
+ try {
170
+ const validationResult = schema.safeParse(value);
171
+ if (validationResult.success) {
172
+ return {
173
+ success: true,
174
+ value: validationResult.data
175
+ };
176
+ }
177
+ return {
178
+ success: false,
179
+ error: new TypeValidationError({
180
+ value,
181
+ cause: validationResult.error
182
+ })
183
+ };
184
+ } catch (error) {
185
+ return {
186
+ success: false,
187
+ error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
188
+ };
189
+ }
190
+ }
191
+
192
+ // ai-model-specification/util/parse-json.ts
193
+ function safeParseJSON({
194
+ text,
195
+ schema
196
+ }) {
197
+ try {
198
+ const value = SecureJSON.parse(text);
199
+ if (schema == null) {
200
+ return {
201
+ success: true,
202
+ value
203
+ };
204
+ }
205
+ return safeValidateTypes({ value, schema });
206
+ } catch (error) {
207
+ return {
208
+ success: false,
209
+ error: JSONParseError.isJSONParseError(error) ? error : new JSONParseError({ text, cause: error })
210
+ };
211
+ }
212
+ }
213
+
214
+ // ai-model-specification/util/uint8-utils.ts
215
+ function convertBase64ToUint8Array(base64String) {
216
+ const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
217
+ const latin1string = globalThis.atob(base64Url);
218
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
219
+ }
220
+ function convertUint8ArrayToBase64(array) {
221
+ let latin1string = "";
222
+ for (let i = 0; i < array.length; i++) {
223
+ latin1string += String.fromCodePoint(array[i]);
224
+ }
225
+ return globalThis.btoa(latin1string);
226
+ }
227
+
228
+ // ai-model-specification/errors/invalid-tool-arguments-error.ts
229
+ var InvalidToolArgumentsError = class extends Error {
230
+ constructor({
231
+ toolArgs,
232
+ toolName,
233
+ cause,
234
+ message = `Invalid arguments for tool ${toolName}: ${getErrorMessage(
235
+ cause
236
+ )}`
237
+ }) {
238
+ super(message);
239
+ this.name = "AI_InvalidToolArgumentsError";
240
+ this.toolArgs = toolArgs;
241
+ this.toolName = toolName;
242
+ this.cause = cause;
243
+ }
244
+ static isInvalidToolArgumentsError(error) {
245
+ return error instanceof Error && error.name === "AI_InvalidToolArgumentsError" && typeof error.toolName === "string" && typeof error.toolArgs === "string";
246
+ }
247
+ toJSON() {
248
+ return {
249
+ name: this.name,
250
+ message: this.message,
251
+ cause: this.cause,
252
+ stack: this.stack,
253
+ toolName: this.toolName,
254
+ toolArgs: this.toolArgs
255
+ };
256
+ }
257
+ };
258
+
259
+ // ai-model-specification/errors/no-object-generated-error.ts
260
+ var NoTextGeneratedError = class extends Error {
261
+ constructor() {
262
+ super(`No text generated.`);
263
+ this.name = "AI_NoTextGeneratedError";
264
+ }
265
+ static isNoTextGeneratedError(error) {
266
+ return error instanceof Error && error.name === "AI_NoTextGeneratedError";
267
+ }
268
+ toJSON() {
269
+ return {
270
+ name: this.name,
271
+ cause: this.cause,
272
+ message: this.message,
273
+ stack: this.stack
274
+ };
275
+ }
276
+ };
277
+
278
+ // ai-model-specification/errors/no-such-tool-error.ts
279
+ var NoSuchToolError = class extends Error {
280
+ constructor({ message, toolName }) {
281
+ super(message);
282
+ this.name = "AI_NoSuchToolError";
283
+ this.toolName = toolName;
284
+ }
285
+ static isNoSuchToolError(error) {
286
+ return error instanceof Error && error.name === "AI_NoSuchToolError" && typeof error.toolName === "string";
287
+ }
288
+ toJSON() {
289
+ return {
290
+ name: this.name,
291
+ message: this.message,
292
+ stack: this.stack,
293
+ toolName: this.toolName
294
+ };
295
+ }
296
+ };
297
+
298
+ // ai-model-specification/errors/retry-error.ts
299
+ var RetryError = class extends Error {
300
+ constructor({
301
+ message,
302
+ reason,
303
+ errors
304
+ }) {
305
+ super(message);
306
+ this.name = "AI_RetryError";
307
+ this.reason = reason;
308
+ this.errors = errors;
309
+ this.lastError = errors[errors.length - 1];
310
+ }
311
+ static isRetryError(error) {
312
+ return error instanceof Error && error.name === "AI_RetryError" && typeof error.reason === "string" && Array.isArray(error.errors);
313
+ }
314
+ toJSON() {
315
+ return {
316
+ name: this.name,
317
+ message: this.message,
318
+ reason: this.reason,
319
+ lastError: this.lastError,
320
+ errors: this.errors
321
+ };
322
+ }
323
+ };
324
+
325
+ // core/generate-text/token-usage.ts
326
+ function calculateTokenUsage(usage) {
327
+ return {
328
+ promptTokens: usage.promptTokens,
329
+ completionTokens: usage.completionTokens,
330
+ totalTokens: usage.promptTokens + usage.completionTokens
331
+ };
332
+ }
333
+
334
+ // core/prompt/data-content.ts
335
+ function convertDataContentToBase64String(content) {
336
+ if (typeof content === "string") {
337
+ return content;
338
+ }
339
+ if (content instanceof ArrayBuffer) {
340
+ return convertUint8ArrayToBase64(new Uint8Array(content));
341
+ }
342
+ return convertUint8ArrayToBase64(content);
343
+ }
344
+ function convertDataContentToUint8Array(content) {
345
+ if (content instanceof Uint8Array) {
346
+ return content;
347
+ }
348
+ if (typeof content === "string") {
349
+ return convertBase64ToUint8Array(content);
350
+ }
351
+ if (content instanceof ArrayBuffer) {
352
+ return new Uint8Array(content);
353
+ }
354
+ throw new InvalidDataContentError({ content });
355
+ }
356
+
357
+ // core/prompt/convert-to-language-model-prompt.ts
358
+ function convertToLanguageModelPrompt({
359
+ system,
360
+ prompt,
361
+ messages
362
+ }) {
363
+ if (prompt == null && messages == null) {
364
+ throw new Error("prompt or messages must be defined");
365
+ }
366
+ if (prompt != null && messages != null) {
367
+ throw new Error("prompt and messages cannot be defined at the same time");
368
+ }
369
+ const languageModelMessages = [];
370
+ if (system != null) {
371
+ languageModelMessages.push({ role: "system", content: system });
372
+ }
373
+ if (typeof prompt === "string") {
374
+ languageModelMessages.push({
375
+ role: "user",
376
+ content: [{ type: "text", text: prompt }]
377
+ });
378
+ } else {
379
+ messages = messages;
380
+ languageModelMessages.push(
381
+ ...messages.map((message) => {
382
+ switch (message.role) {
383
+ case "user": {
384
+ if (typeof message.content === "string") {
385
+ return {
386
+ role: "user",
387
+ content: [{ type: "text", text: message.content }]
388
+ };
389
+ }
390
+ return {
391
+ role: "user",
392
+ content: message.content.map(
393
+ (part) => {
394
+ switch (part.type) {
395
+ case "text": {
396
+ return part;
397
+ }
398
+ case "image": {
399
+ return {
400
+ type: "image",
401
+ image: part.image instanceof URL ? part.image : convertDataContentToUint8Array(part.image),
402
+ mimeType: part.mimeType
403
+ };
404
+ }
405
+ }
406
+ }
407
+ )
408
+ };
409
+ }
410
+ case "assistant": {
411
+ if (typeof message.content === "string") {
412
+ return {
413
+ role: "assistant",
414
+ content: [{ type: "text", text: message.content }]
415
+ };
416
+ }
417
+ return { role: "assistant", content: message.content };
418
+ }
419
+ case "tool": {
420
+ return message;
421
+ }
422
+ }
423
+ })
424
+ );
425
+ }
426
+ return languageModelMessages;
427
+ }
428
+
429
+ // core/prompt/get-input-format.ts
430
+ function getInputFormat({
431
+ prompt,
432
+ messages
433
+ }) {
434
+ if (prompt == null && messages == null) {
435
+ throw new Error("prompt or messages must be defined");
436
+ }
437
+ if (prompt != null && messages != null) {
438
+ throw new Error("prompt and messages cannot be defined at the same time");
439
+ }
440
+ return prompt != null ? "prompt" : "messages";
441
+ }
442
+
443
+ // core/prompt/prepare-call-settings.ts
444
+ function prepareCallSettings({
445
+ maxTokens,
446
+ temperature,
447
+ topP,
448
+ presencePenalty,
449
+ frequencyPenalty,
450
+ seed,
451
+ maxRetries
452
+ }) {
453
+ if (maxTokens != null) {
454
+ if (!Number.isInteger(maxTokens)) {
455
+ throw new InvalidArgumentError({
456
+ parameter: "maxTokens",
457
+ value: maxTokens,
458
+ message: "maxTokens must be an integer"
459
+ });
460
+ }
461
+ if (maxTokens < 1) {
462
+ throw new InvalidArgumentError({
463
+ parameter: "maxTokens",
464
+ value: maxTokens,
465
+ message: "maxTokens must be >= 1"
466
+ });
467
+ }
468
+ }
469
+ if (temperature != null) {
470
+ if (typeof temperature !== "number") {
471
+ throw new InvalidArgumentError({
472
+ parameter: "temperature",
473
+ value: temperature,
474
+ message: "temperature must be a number"
475
+ });
476
+ }
477
+ if (temperature < 0 || temperature > 1) {
478
+ throw new InvalidArgumentError({
479
+ parameter: "temperature",
480
+ value: temperature,
481
+ message: "temperature must be between 0 and 1 (inclusive)"
482
+ });
483
+ }
484
+ }
485
+ if (topP != null) {
486
+ if (typeof topP !== "number") {
487
+ throw new InvalidArgumentError({
488
+ parameter: "topP",
489
+ value: topP,
490
+ message: "topP must be a number"
491
+ });
492
+ }
493
+ if (topP < 0 || topP > 1) {
494
+ throw new InvalidArgumentError({
495
+ parameter: "topP",
496
+ value: topP,
497
+ message: "topP must be between 0 and 1 (inclusive)"
498
+ });
499
+ }
500
+ }
501
+ if (presencePenalty != null) {
502
+ if (typeof presencePenalty !== "number") {
503
+ throw new InvalidArgumentError({
504
+ parameter: "presencePenalty",
505
+ value: presencePenalty,
506
+ message: "presencePenalty must be a number"
507
+ });
508
+ }
509
+ if (presencePenalty < -1 || presencePenalty > 1) {
510
+ throw new InvalidArgumentError({
511
+ parameter: "presencePenalty",
512
+ value: presencePenalty,
513
+ message: "presencePenalty must be between -1 and 1 (inclusive)"
514
+ });
515
+ }
516
+ }
517
+ if (frequencyPenalty != null) {
518
+ if (typeof frequencyPenalty !== "number") {
519
+ throw new InvalidArgumentError({
520
+ parameter: "frequencyPenalty",
521
+ value: frequencyPenalty,
522
+ message: "frequencyPenalty must be a number"
523
+ });
524
+ }
525
+ if (frequencyPenalty < -1 || frequencyPenalty > 1) {
526
+ throw new InvalidArgumentError({
527
+ parameter: "frequencyPenalty",
528
+ value: frequencyPenalty,
529
+ message: "frequencyPenalty must be between -1 and 1 (inclusive)"
530
+ });
531
+ }
532
+ }
533
+ if (seed != null) {
534
+ if (!Number.isInteger(seed)) {
535
+ throw new InvalidArgumentError({
536
+ parameter: "seed",
537
+ value: seed,
538
+ message: "seed must be an integer"
539
+ });
540
+ }
541
+ }
542
+ if (maxRetries != null) {
543
+ if (!Number.isInteger(maxRetries)) {
544
+ throw new InvalidArgumentError({
545
+ parameter: "maxRetries",
546
+ value: maxRetries,
547
+ message: "maxRetries must be an integer"
548
+ });
549
+ }
550
+ if (maxRetries < 0) {
551
+ throw new InvalidArgumentError({
552
+ parameter: "maxRetries",
553
+ value: maxRetries,
554
+ message: "maxRetries must be >= 0"
555
+ });
556
+ }
557
+ }
558
+ return {
559
+ maxTokens,
560
+ temperature: temperature != null ? temperature : 0,
561
+ topP,
562
+ presencePenalty: presencePenalty != null ? presencePenalty : 0,
563
+ frequencyPenalty: frequencyPenalty != null ? frequencyPenalty : 0,
564
+ seed,
565
+ maxRetries: maxRetries != null ? maxRetries : 2
566
+ };
567
+ }
568
+
569
+ // core/util/delay.ts
570
+ async function delay(delayInMs) {
571
+ return new Promise((resolve) => setTimeout(resolve, delayInMs));
572
+ }
573
+
574
+ // core/util/retry-with-exponential-backoff.ts
575
+ var retryWithExponentialBackoff = ({
576
+ maxRetries = 2,
577
+ initialDelayInMs = 2e3,
578
+ backoffFactor = 2
579
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
580
+ maxRetries,
581
+ delayInMs: initialDelayInMs,
582
+ backoffFactor
583
+ });
584
+ async function _retryWithExponentialBackoff(f, {
585
+ maxRetries,
586
+ delayInMs,
587
+ backoffFactor
588
+ }, errors = []) {
589
+ try {
590
+ return await f();
591
+ } catch (error) {
592
+ if (error instanceof Error && error.name === "AbortError") {
593
+ throw error;
594
+ }
595
+ if (maxRetries === 0) {
596
+ throw error;
597
+ }
598
+ const errorMessage = getErrorMessage(error);
599
+ const newErrors = [...errors, error];
600
+ const tryNumber = newErrors.length;
601
+ if (tryNumber > maxRetries) {
602
+ throw new RetryError({
603
+ message: `Failed after ${tryNumber} attemps. Last error: ${errorMessage}`,
604
+ reason: "maxRetriesExceeded",
605
+ errors: newErrors
606
+ });
607
+ }
608
+ if (error instanceof Error && APICallError.isAPICallError(error) && error.isRetryable === true && tryNumber <= maxRetries) {
609
+ await delay(delayInMs);
610
+ return _retryWithExponentialBackoff(
611
+ f,
612
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
613
+ newErrors
614
+ );
615
+ }
616
+ if (tryNumber === 1) {
617
+ throw error;
618
+ }
619
+ throw new RetryError({
620
+ message: `Failed after ${tryNumber} attemps with non-retryable error: '${errorMessage}'`,
621
+ reason: "errorNotRetryable",
622
+ errors: newErrors
623
+ });
624
+ }
625
+ }
626
+
627
+ // core/generate-object/inject-json-schema-into-system.ts
628
+ var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
629
+ var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
630
+ function injectJsonSchemaIntoSystem({
631
+ system,
632
+ schema,
633
+ schemaPrefix = DEFAULT_SCHEMA_PREFIX,
634
+ schemaSuffix = DEFAULT_SCHEMA_SUFFIX
635
+ }) {
636
+ return [
637
+ system,
638
+ system != null ? "" : null,
639
+ // add a newline if system is not null
640
+ schemaPrefix,
641
+ JSON.stringify(schema),
642
+ schemaSuffix
643
+ ].filter((line) => line != null).join("\n");
644
+ }
645
+
646
+ // core/generate-object/generate-object.ts
647
+ async function experimental_generateObject({
648
+ model,
649
+ schema,
650
+ mode,
651
+ system,
652
+ prompt,
653
+ messages,
654
+ maxRetries,
655
+ abortSignal,
656
+ ...settings
657
+ }) {
658
+ var _a, _b;
659
+ const retry = retryWithExponentialBackoff({ maxRetries });
660
+ const jsonSchema = zodToJsonSchema(schema);
661
+ if (mode === "auto" || mode == null) {
662
+ mode = model.defaultObjectGenerationMode;
663
+ }
664
+ let result;
665
+ let finishReason;
666
+ let usage;
667
+ let warnings;
668
+ switch (mode) {
669
+ case "json": {
670
+ const generateResult = await retry(
671
+ () => model.doGenerate({
672
+ mode: { type: "object-json" },
673
+ ...prepareCallSettings(settings),
674
+ inputFormat: getInputFormat({ prompt, messages }),
675
+ prompt: convertToLanguageModelPrompt({
676
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
677
+ prompt,
678
+ messages
679
+ }),
680
+ abortSignal
681
+ })
682
+ );
683
+ if (generateResult.text === void 0) {
684
+ throw new NoTextGeneratedError();
685
+ }
686
+ result = generateResult.text;
687
+ finishReason = generateResult.finishReason;
688
+ usage = generateResult.usage;
689
+ warnings = generateResult.warnings;
690
+ break;
691
+ }
692
+ case "grammar": {
693
+ const generateResult = await retry(
694
+ () => model.doGenerate({
695
+ mode: { type: "object-grammar", schema: jsonSchema },
696
+ ...settings,
697
+ inputFormat: getInputFormat({ prompt, messages }),
698
+ prompt: convertToLanguageModelPrompt({
699
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
700
+ prompt,
701
+ messages
702
+ }),
703
+ abortSignal
704
+ })
705
+ );
706
+ if (generateResult.text === void 0) {
707
+ throw new NoTextGeneratedError();
708
+ }
709
+ result = generateResult.text;
710
+ finishReason = generateResult.finishReason;
711
+ usage = generateResult.usage;
712
+ warnings = generateResult.warnings;
713
+ break;
714
+ }
715
+ case "tool": {
716
+ const generateResult = await retry(
717
+ () => model.doGenerate({
718
+ mode: {
719
+ type: "object-tool",
720
+ tool: {
721
+ type: "function",
722
+ name: "json",
723
+ description: "Respond with a JSON object.",
724
+ parameters: jsonSchema
725
+ }
726
+ },
727
+ ...settings,
728
+ inputFormat: getInputFormat({ prompt, messages }),
729
+ prompt: convertToLanguageModelPrompt({ system, prompt, messages }),
730
+ abortSignal
731
+ })
732
+ );
733
+ const functionArgs = (_b = (_a = generateResult.toolCalls) == null ? void 0 : _a[0]) == null ? void 0 : _b.args;
734
+ if (functionArgs === void 0) {
735
+ throw new NoTextGeneratedError();
736
+ }
737
+ result = functionArgs;
738
+ finishReason = generateResult.finishReason;
739
+ usage = generateResult.usage;
740
+ warnings = generateResult.warnings;
741
+ break;
742
+ }
743
+ case void 0: {
744
+ throw new Error("Model does not have a default object generation mode.");
745
+ }
746
+ default: {
747
+ const _exhaustiveCheck = mode;
748
+ throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);
749
+ }
750
+ }
751
+ const parseResult = safeParseJSON({ text: result, schema });
752
+ if (!parseResult.success) {
753
+ throw parseResult.error;
754
+ }
755
+ return new GenerateObjectResult({
756
+ object: parseResult.value,
757
+ finishReason,
758
+ usage: calculateTokenUsage(usage),
759
+ warnings
760
+ });
761
+ }
762
+ var GenerateObjectResult = class {
763
+ constructor(options) {
764
+ this.object = options.object;
765
+ this.finishReason = options.finishReason;
766
+ this.usage = options.usage;
767
+ this.warnings = options.warnings;
768
+ }
769
+ };
770
+
771
+ // core/generate-object/stream-object.ts
772
+ import zodToJsonSchema2 from "zod-to-json-schema";
773
+
774
+ // core/util/async-iterable-stream.ts
775
+ function createAsyncIterableStream(source, transformer) {
776
+ const transformedStream = source.pipeThrough(
777
+ new TransformStream(transformer)
778
+ );
779
+ transformedStream[Symbol.asyncIterator] = () => {
780
+ const reader = transformedStream.getReader();
781
+ return {
782
+ async next() {
783
+ const { done, value } = await reader.read();
784
+ return done ? { done: true, value: void 0 } : { done: false, value };
785
+ }
786
+ };
787
+ };
788
+ return transformedStream;
789
+ }
790
+
791
+ // core/util/is-deep-equal-data.ts
792
+ function isDeepEqualData(obj1, obj2) {
793
+ if (obj1 === obj2)
794
+ return true;
795
+ if (obj1 == null || obj2 == null)
796
+ return false;
797
+ if (typeof obj1 !== "object" && typeof obj2 !== "object")
798
+ return obj1 === obj2;
799
+ if (obj1.constructor !== obj2.constructor)
800
+ return false;
801
+ if (obj1 instanceof Date && obj2 instanceof Date) {
802
+ return obj1.getTime() === obj2.getTime();
803
+ }
804
+ if (Array.isArray(obj1)) {
805
+ if (obj1.length !== obj2.length)
806
+ return false;
807
+ for (let i = 0; i < obj1.length; i++) {
808
+ if (!isDeepEqualData(obj1[i], obj2[i]))
809
+ return false;
810
+ }
811
+ return true;
812
+ }
813
+ const keys1 = Object.keys(obj1);
814
+ const keys2 = Object.keys(obj2);
815
+ if (keys1.length !== keys2.length)
816
+ return false;
817
+ for (const key of keys1) {
818
+ if (!keys2.includes(key))
819
+ return false;
820
+ if (!isDeepEqualData(obj1[key], obj2[key]))
821
+ return false;
822
+ }
823
+ return true;
824
+ }
825
+
826
+ // core/util/parse-partial-json.ts
827
+ import SecureJSON2 from "secure-json-parse";
828
+
829
+ // core/util/fix-json.ts
830
+ function fixJson(input) {
831
+ const stack = ["ROOT"];
832
+ let lastValidIndex = -1;
833
+ let literalStart = null;
834
+ function processValueStart(char, i, swapState) {
835
+ {
836
+ switch (char) {
837
+ case '"': {
838
+ lastValidIndex = i;
839
+ stack.pop();
840
+ stack.push(swapState);
841
+ stack.push("INSIDE_STRING");
842
+ break;
843
+ }
844
+ case "f":
845
+ case "t":
846
+ case "n": {
847
+ lastValidIndex = i;
848
+ literalStart = i;
849
+ stack.pop();
850
+ stack.push(swapState);
851
+ stack.push("INSIDE_LITERAL");
852
+ break;
853
+ }
854
+ case "-": {
855
+ stack.pop();
856
+ stack.push(swapState);
857
+ stack.push("INSIDE_NUMBER");
858
+ break;
859
+ }
860
+ case "0":
861
+ case "1":
862
+ case "2":
863
+ case "3":
864
+ case "4":
865
+ case "5":
866
+ case "6":
867
+ case "7":
868
+ case "8":
869
+ case "9": {
870
+ lastValidIndex = i;
871
+ stack.pop();
872
+ stack.push(swapState);
873
+ stack.push("INSIDE_NUMBER");
874
+ break;
875
+ }
876
+ case "{": {
877
+ lastValidIndex = i;
878
+ stack.pop();
879
+ stack.push(swapState);
880
+ stack.push("INSIDE_OBJECT_START");
881
+ break;
882
+ }
883
+ case "[": {
884
+ lastValidIndex = i;
885
+ stack.pop();
886
+ stack.push(swapState);
887
+ stack.push("INSIDE_ARRAY_START");
888
+ break;
889
+ }
890
+ }
891
+ }
892
+ }
893
+ function processAfterObjectValue(char, i) {
894
+ switch (char) {
895
+ case ",": {
896
+ stack.pop();
897
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
898
+ break;
899
+ }
900
+ case "}": {
901
+ lastValidIndex = i;
902
+ stack.pop();
903
+ break;
904
+ }
905
+ }
906
+ }
907
+ function processAfterArrayValue(char, i) {
908
+ switch (char) {
909
+ case ",": {
910
+ stack.pop();
911
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
912
+ break;
913
+ }
914
+ case "]": {
915
+ lastValidIndex = i;
916
+ stack.pop();
917
+ break;
918
+ }
919
+ }
920
+ }
921
+ for (let i = 0; i < input.length; i++) {
922
+ const char = input[i];
923
+ const currentState = stack[stack.length - 1];
924
+ switch (currentState) {
925
+ case "ROOT":
926
+ processValueStart(char, i, "FINISH");
927
+ break;
928
+ case "INSIDE_OBJECT_START": {
929
+ switch (char) {
930
+ case '"': {
931
+ stack.pop();
932
+ stack.push("INSIDE_OBJECT_KEY");
933
+ break;
934
+ }
935
+ case "}": {
936
+ stack.pop();
937
+ break;
938
+ }
939
+ }
940
+ break;
941
+ }
942
+ case "INSIDE_OBJECT_AFTER_COMMA": {
943
+ switch (char) {
944
+ case '"': {
945
+ stack.pop();
946
+ stack.push("INSIDE_OBJECT_KEY");
947
+ break;
948
+ }
949
+ }
950
+ break;
951
+ }
952
+ case "INSIDE_OBJECT_KEY": {
953
+ switch (char) {
954
+ case '"': {
955
+ stack.pop();
956
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
957
+ break;
958
+ }
959
+ }
960
+ break;
961
+ }
962
+ case "INSIDE_OBJECT_AFTER_KEY": {
963
+ switch (char) {
964
+ case ":": {
965
+ stack.pop();
966
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
967
+ break;
968
+ }
969
+ }
970
+ break;
971
+ }
972
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
973
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
974
+ break;
975
+ }
976
+ case "INSIDE_OBJECT_AFTER_VALUE": {
977
+ processAfterObjectValue(char, i);
978
+ break;
979
+ }
980
+ case "INSIDE_STRING": {
981
+ switch (char) {
982
+ case '"': {
983
+ stack.pop();
984
+ lastValidIndex = i;
985
+ break;
986
+ }
987
+ case "\\": {
988
+ stack.push("INSIDE_STRING_ESCAPE");
989
+ break;
990
+ }
991
+ default: {
992
+ lastValidIndex = i;
993
+ }
994
+ }
995
+ break;
996
+ }
997
+ case "INSIDE_ARRAY_START": {
998
+ switch (char) {
999
+ case "]": {
1000
+ lastValidIndex = i;
1001
+ stack.pop();
1002
+ break;
1003
+ }
1004
+ default: {
1005
+ lastValidIndex = i;
1006
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1007
+ break;
1008
+ }
1009
+ }
1010
+ break;
1011
+ }
1012
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1013
+ switch (char) {
1014
+ case ",": {
1015
+ stack.pop();
1016
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
1017
+ break;
1018
+ }
1019
+ case "]": {
1020
+ lastValidIndex = i;
1021
+ stack.pop();
1022
+ break;
1023
+ }
1024
+ default: {
1025
+ lastValidIndex = i;
1026
+ break;
1027
+ }
1028
+ }
1029
+ break;
1030
+ }
1031
+ case "INSIDE_ARRAY_AFTER_COMMA": {
1032
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1033
+ break;
1034
+ }
1035
+ case "INSIDE_STRING_ESCAPE": {
1036
+ stack.pop();
1037
+ lastValidIndex = i;
1038
+ break;
1039
+ }
1040
+ case "INSIDE_NUMBER": {
1041
+ switch (char) {
1042
+ case "0":
1043
+ case "1":
1044
+ case "2":
1045
+ case "3":
1046
+ case "4":
1047
+ case "5":
1048
+ case "6":
1049
+ case "7":
1050
+ case "8":
1051
+ case "9": {
1052
+ lastValidIndex = i;
1053
+ break;
1054
+ }
1055
+ case "e":
1056
+ case "E":
1057
+ case "-":
1058
+ case ".": {
1059
+ break;
1060
+ }
1061
+ case ",": {
1062
+ stack.pop();
1063
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1064
+ processAfterArrayValue(char, i);
1065
+ }
1066
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1067
+ processAfterObjectValue(char, i);
1068
+ }
1069
+ break;
1070
+ }
1071
+ case "}": {
1072
+ stack.pop();
1073
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1074
+ processAfterObjectValue(char, i);
1075
+ }
1076
+ break;
1077
+ }
1078
+ case "]": {
1079
+ stack.pop();
1080
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1081
+ processAfterArrayValue(char, i);
1082
+ }
1083
+ break;
1084
+ }
1085
+ default: {
1086
+ stack.pop();
1087
+ break;
1088
+ }
1089
+ }
1090
+ break;
1091
+ }
1092
+ case "INSIDE_LITERAL": {
1093
+ const partialLiteral = input.substring(literalStart, i + 1);
1094
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
1095
+ stack.pop();
1096
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1097
+ processAfterObjectValue(char, i);
1098
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1099
+ processAfterArrayValue(char, i);
1100
+ }
1101
+ } else {
1102
+ lastValidIndex = i;
1103
+ }
1104
+ break;
1105
+ }
1106
+ }
1107
+ }
1108
+ let result = input.slice(0, lastValidIndex + 1);
1109
+ for (let i = stack.length - 1; i >= 0; i--) {
1110
+ const state = stack[i];
1111
+ switch (state) {
1112
+ case "INSIDE_STRING": {
1113
+ result += '"';
1114
+ break;
1115
+ }
1116
+ case "INSIDE_OBJECT_KEY":
1117
+ case "INSIDE_OBJECT_AFTER_KEY":
1118
+ case "INSIDE_OBJECT_AFTER_COMMA":
1119
+ case "INSIDE_OBJECT_START":
1120
+ case "INSIDE_OBJECT_BEFORE_VALUE":
1121
+ case "INSIDE_OBJECT_AFTER_VALUE": {
1122
+ result += "}";
1123
+ break;
1124
+ }
1125
+ case "INSIDE_ARRAY_START":
1126
+ case "INSIDE_ARRAY_AFTER_COMMA":
1127
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1128
+ result += "]";
1129
+ break;
1130
+ }
1131
+ case "INSIDE_LITERAL": {
1132
+ const partialLiteral = input.substring(literalStart, input.length);
1133
+ if ("true".startsWith(partialLiteral)) {
1134
+ result += "true".slice(partialLiteral.length);
1135
+ } else if ("false".startsWith(partialLiteral)) {
1136
+ result += "false".slice(partialLiteral.length);
1137
+ } else if ("null".startsWith(partialLiteral)) {
1138
+ result += "null".slice(partialLiteral.length);
1139
+ }
1140
+ }
1141
+ }
1142
+ }
1143
+ return result;
1144
+ }
1145
+
1146
+ // core/util/parse-partial-json.ts
1147
+ function parsePartialJson(jsonText) {
1148
+ if (jsonText == null) {
1149
+ return void 0;
1150
+ }
1151
+ try {
1152
+ return SecureJSON2.parse(jsonText);
1153
+ } catch (ignored) {
1154
+ try {
1155
+ const fixedJsonText = fixJson(jsonText);
1156
+ return SecureJSON2.parse(fixedJsonText);
1157
+ } catch (ignored2) {
1158
+ }
1159
+ }
1160
+ return void 0;
1161
+ }
1162
+
1163
+ // core/generate-object/stream-object.ts
1164
+ async function experimental_streamObject({
1165
+ model,
1166
+ schema,
1167
+ mode,
1168
+ system,
1169
+ prompt,
1170
+ messages,
1171
+ maxRetries,
1172
+ abortSignal,
1173
+ ...settings
1174
+ }) {
1175
+ const retry = retryWithExponentialBackoff({ maxRetries });
1176
+ const jsonSchema = zodToJsonSchema2(schema);
1177
+ if (mode === "auto" || mode == null) {
1178
+ mode = model.defaultObjectGenerationMode;
1179
+ }
1180
+ let callOptions;
1181
+ let transformer;
1182
+ switch (mode) {
1183
+ case "json": {
1184
+ callOptions = {
1185
+ mode: { type: "object-json" },
1186
+ ...prepareCallSettings(settings),
1187
+ inputFormat: getInputFormat({ prompt, messages }),
1188
+ prompt: convertToLanguageModelPrompt({
1189
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
1190
+ prompt,
1191
+ messages
1192
+ }),
1193
+ abortSignal
1194
+ };
1195
+ transformer = {
1196
+ transform: (chunk, controller) => {
1197
+ switch (chunk.type) {
1198
+ case "text-delta":
1199
+ controller.enqueue(chunk.textDelta);
1200
+ break;
1201
+ case "error":
1202
+ controller.enqueue(chunk);
1203
+ break;
1204
+ }
1205
+ }
1206
+ };
1207
+ break;
1208
+ }
1209
+ case "grammar": {
1210
+ callOptions = {
1211
+ mode: { type: "object-grammar", schema: jsonSchema },
1212
+ ...settings,
1213
+ inputFormat: getInputFormat({ prompt, messages }),
1214
+ prompt: convertToLanguageModelPrompt({
1215
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
1216
+ prompt,
1217
+ messages
1218
+ }),
1219
+ abortSignal
1220
+ };
1221
+ transformer = {
1222
+ transform: (chunk, controller) => {
1223
+ switch (chunk.type) {
1224
+ case "text-delta":
1225
+ controller.enqueue(chunk.textDelta);
1226
+ break;
1227
+ case "error":
1228
+ controller.enqueue(chunk);
1229
+ break;
1230
+ }
1231
+ }
1232
+ };
1233
+ break;
1234
+ }
1235
+ case "tool": {
1236
+ callOptions = {
1237
+ mode: {
1238
+ type: "object-tool",
1239
+ tool: {
1240
+ type: "function",
1241
+ name: "json",
1242
+ description: "Respond with a JSON object.",
1243
+ parameters: jsonSchema
1244
+ }
1245
+ },
1246
+ ...settings,
1247
+ inputFormat: getInputFormat({ prompt, messages }),
1248
+ prompt: convertToLanguageModelPrompt({ system, prompt, messages }),
1249
+ abortSignal
1250
+ };
1251
+ transformer = {
1252
+ transform(chunk, controller) {
1253
+ switch (chunk.type) {
1254
+ case "tool-call-delta":
1255
+ controller.enqueue(chunk.argsTextDelta);
1256
+ break;
1257
+ case "error":
1258
+ controller.enqueue(chunk);
1259
+ break;
1260
+ }
1261
+ }
1262
+ };
1263
+ break;
1264
+ }
1265
+ case void 0: {
1266
+ throw new Error("Model does not have a default object generation mode.");
1267
+ }
1268
+ default: {
1269
+ const _exhaustiveCheck = mode;
1270
+ throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);
1271
+ }
1272
+ }
1273
+ const result = await retry(() => model.doStream(callOptions));
1274
+ return new StreamObjectResult({
1275
+ stream: result.stream.pipeThrough(new TransformStream(transformer)),
1276
+ warnings: result.warnings
1277
+ });
1278
+ }
1279
+ var StreamObjectResult = class {
1280
+ constructor({
1281
+ stream,
1282
+ warnings
1283
+ }) {
1284
+ this.originalStream = stream;
1285
+ this.warnings = warnings;
1286
+ }
1287
+ get partialObjectStream() {
1288
+ let accumulatedText = "";
1289
+ let latestObject = void 0;
1290
+ return createAsyncIterableStream(this.originalStream, {
1291
+ transform(chunk, controller) {
1292
+ if (typeof chunk === "string") {
1293
+ accumulatedText += chunk;
1294
+ const currentObject = parsePartialJson(
1295
+ accumulatedText
1296
+ );
1297
+ if (!isDeepEqualData(latestObject, currentObject)) {
1298
+ latestObject = currentObject;
1299
+ controller.enqueue(currentObject);
1300
+ }
1301
+ }
1302
+ if (typeof chunk === "object" && chunk.type === "error") {
1303
+ throw chunk.error;
1304
+ }
1305
+ }
1306
+ });
1307
+ }
1308
+ };
1309
+
1310
+ // core/generate-text/generate-text.ts
1311
+ import zodToJsonSchema3 from "zod-to-json-schema";
1312
+
1313
+ // core/generate-text/tool-call.ts
1314
+ function parseToolCall({
1315
+ toolCall,
1316
+ tools
1317
+ }) {
1318
+ const toolName = toolCall.toolName;
1319
+ if (tools == null) {
1320
+ throw new NoSuchToolError({
1321
+ message: `Tool ${toolCall.toolName} not found (no tools provided).`,
1322
+ toolName: toolCall.toolName
1323
+ });
1324
+ }
1325
+ const tool2 = tools[toolName];
1326
+ if (tool2 == null) {
1327
+ throw new NoSuchToolError({
1328
+ message: `Tool ${toolCall.toolName} not found.`,
1329
+ toolName: toolCall.toolName
1330
+ });
1331
+ }
1332
+ const parseResult = safeParseJSON({
1333
+ text: toolCall.args,
1334
+ schema: tool2.parameters
1335
+ });
1336
+ if (parseResult.success === false) {
1337
+ throw new InvalidToolArgumentsError({
1338
+ toolName,
1339
+ toolArgs: toolCall.args,
1340
+ cause: parseResult.error
1341
+ });
1342
+ }
1343
+ return {
1344
+ toolCallId: toolCall.toolCallId,
1345
+ toolName,
1346
+ args: parseResult.value
1347
+ };
1348
+ }
1349
+
1350
+ // core/generate-text/generate-text.ts
1351
+ async function experimental_generateText({
1352
+ model,
1353
+ tools,
1354
+ system,
1355
+ prompt,
1356
+ messages,
1357
+ maxRetries,
1358
+ abortSignal,
1359
+ ...settings
1360
+ }) {
1361
+ var _a, _b;
1362
+ const retry = retryWithExponentialBackoff({ maxRetries });
1363
+ const modelResponse = await retry(
1364
+ () => model.doGenerate({
1365
+ mode: {
1366
+ type: "regular",
1367
+ tools: tools == null ? void 0 : Object.entries(tools).map(([name, tool2]) => ({
1368
+ type: "function",
1369
+ name,
1370
+ description: tool2.description,
1371
+ parameters: zodToJsonSchema3(tool2.parameters)
1372
+ }))
1373
+ },
1374
+ ...prepareCallSettings(settings),
1375
+ inputFormat: getInputFormat({ prompt, messages }),
1376
+ prompt: convertToLanguageModelPrompt({
1377
+ system,
1378
+ prompt,
1379
+ messages
1380
+ }),
1381
+ abortSignal
1382
+ })
1383
+ );
1384
+ const toolCalls = [];
1385
+ for (const modelToolCall of (_a = modelResponse.toolCalls) != null ? _a : []) {
1386
+ toolCalls.push(parseToolCall({ toolCall: modelToolCall, tools }));
1387
+ }
1388
+ const toolResults = tools == null ? [] : await executeTools({ toolCalls, tools });
1389
+ return new GenerateTextResult({
1390
+ // Always return a string so that the caller doesn't have to check for undefined.
1391
+ // If they need to check if the model did not return any text,
1392
+ // they can check the length of the string:
1393
+ text: (_b = modelResponse.text) != null ? _b : "",
1394
+ toolCalls,
1395
+ toolResults,
1396
+ finishReason: modelResponse.finishReason,
1397
+ usage: calculateTokenUsage(modelResponse.usage),
1398
+ warnings: modelResponse.warnings
1399
+ });
1400
+ }
1401
+ async function executeTools({
1402
+ toolCalls,
1403
+ tools
1404
+ }) {
1405
+ const toolResults = await Promise.all(
1406
+ toolCalls.map(async (toolCall) => {
1407
+ const tool2 = tools[toolCall.toolName];
1408
+ if ((tool2 == null ? void 0 : tool2.execute) == null) {
1409
+ return void 0;
1410
+ }
1411
+ const result = await tool2.execute(toolCall.args);
1412
+ return {
1413
+ toolCallId: toolCall.toolCallId,
1414
+ toolName: toolCall.toolName,
1415
+ args: toolCall.args,
1416
+ result
1417
+ };
1418
+ })
1419
+ );
1420
+ return toolResults.filter(
1421
+ (result) => result != null
1422
+ );
1423
+ }
1424
+ var GenerateTextResult = class {
1425
+ constructor(options) {
1426
+ this.text = options.text;
1427
+ this.toolCalls = options.toolCalls;
1428
+ this.toolResults = options.toolResults;
1429
+ this.finishReason = options.finishReason;
1430
+ this.usage = options.usage;
1431
+ this.warnings = options.warnings;
1432
+ }
1433
+ };
1434
+
1435
+ // core/generate-text/stream-text.ts
1436
+ import zodToJsonSchema4 from "zod-to-json-schema";
1437
+
1438
+ // shared/generate-id.ts
2
1439
  import { customAlphabet } from "nanoid/non-secure";
1440
+ var generateId = customAlphabet(
1441
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
1442
+ 7
1443
+ );
1444
+
1445
+ // core/generate-text/run-tools-transformation.ts
1446
+ function runToolsTransformation({
1447
+ tools,
1448
+ generatorStream
1449
+ }) {
1450
+ let canClose = false;
1451
+ const outstandingToolCalls = /* @__PURE__ */ new Set();
1452
+ let toolResultsStreamController = null;
1453
+ const toolResultsStream = new ReadableStream({
1454
+ start(controller) {
1455
+ toolResultsStreamController = controller;
1456
+ }
1457
+ });
1458
+ const forwardStream = new TransformStream({
1459
+ transform(chunk, controller) {
1460
+ const chunkType = chunk.type;
1461
+ switch (chunkType) {
1462
+ case "text-delta":
1463
+ case "error": {
1464
+ controller.enqueue(chunk);
1465
+ break;
1466
+ }
1467
+ case "tool-call": {
1468
+ const toolName = chunk.toolName;
1469
+ if (tools == null) {
1470
+ toolResultsStreamController.enqueue({
1471
+ type: "error",
1472
+ error: new NoSuchToolError({
1473
+ message: `Tool ${chunk.toolName} not found (no tools provided).`,
1474
+ toolName: chunk.toolName
1475
+ })
1476
+ });
1477
+ break;
1478
+ }
1479
+ const tool2 = tools[toolName];
1480
+ if (tool2 == null) {
1481
+ toolResultsStreamController.enqueue({
1482
+ type: "error",
1483
+ error: new NoSuchToolError({
1484
+ message: `Tool ${chunk.toolName} not found.`,
1485
+ toolName: chunk.toolName
1486
+ })
1487
+ });
1488
+ break;
1489
+ }
1490
+ try {
1491
+ const toolCall = parseToolCall({
1492
+ toolCall: chunk,
1493
+ tools
1494
+ });
1495
+ controller.enqueue({
1496
+ type: "tool-call",
1497
+ ...toolCall
1498
+ });
1499
+ if (tool2.execute != null) {
1500
+ const toolExecutionId = generateId();
1501
+ outstandingToolCalls.add(toolExecutionId);
1502
+ tool2.execute(toolCall.args).then(
1503
+ (result) => {
1504
+ toolResultsStreamController.enqueue({
1505
+ type: "tool-result",
1506
+ ...toolCall,
1507
+ result
1508
+ });
1509
+ outstandingToolCalls.delete(toolExecutionId);
1510
+ if (canClose && outstandingToolCalls.size === 0) {
1511
+ toolResultsStreamController.close();
1512
+ }
1513
+ },
1514
+ (error) => {
1515
+ toolResultsStreamController.enqueue({
1516
+ type: "error",
1517
+ error
1518
+ });
1519
+ outstandingToolCalls.delete(toolExecutionId);
1520
+ if (canClose && outstandingToolCalls.size === 0) {
1521
+ toolResultsStreamController.close();
1522
+ }
1523
+ }
1524
+ );
1525
+ }
1526
+ } catch (error) {
1527
+ toolResultsStreamController.enqueue({
1528
+ type: "error",
1529
+ error
1530
+ });
1531
+ }
1532
+ break;
1533
+ }
1534
+ case "finish": {
1535
+ controller.enqueue({
1536
+ type: "finish",
1537
+ finishReason: chunk.finishReason,
1538
+ usage: {
1539
+ promptTokens: chunk.usage.promptTokens,
1540
+ completionTokens: chunk.usage.completionTokens,
1541
+ totalTokens: chunk.usage.promptTokens + chunk.usage.completionTokens
1542
+ }
1543
+ });
1544
+ break;
1545
+ }
1546
+ case "tool-call-delta": {
1547
+ break;
1548
+ }
1549
+ default: {
1550
+ const _exhaustiveCheck = chunkType;
1551
+ throw new Error(`Unhandled chunk type: ${_exhaustiveCheck}`);
1552
+ }
1553
+ }
1554
+ },
1555
+ flush() {
1556
+ canClose = true;
1557
+ if (outstandingToolCalls.size === 0) {
1558
+ toolResultsStreamController.close();
1559
+ }
1560
+ }
1561
+ });
1562
+ return new ReadableStream({
1563
+ async start(controller) {
1564
+ generatorStream.pipeThrough(forwardStream).pipeTo(
1565
+ new WritableStream({
1566
+ write(chunk) {
1567
+ controller.enqueue(chunk);
1568
+ },
1569
+ close() {
1570
+ }
1571
+ })
1572
+ );
1573
+ toolResultsStream.pipeTo(
1574
+ new WritableStream({
1575
+ write(chunk) {
1576
+ controller.enqueue(chunk);
1577
+ },
1578
+ close() {
1579
+ controller.close();
1580
+ }
1581
+ })
1582
+ );
1583
+ }
1584
+ });
1585
+ }
1586
+
1587
+ // core/generate-text/stream-text.ts
1588
+ async function experimental_streamText({
1589
+ model,
1590
+ tools,
1591
+ system,
1592
+ prompt,
1593
+ messages,
1594
+ maxRetries,
1595
+ abortSignal,
1596
+ ...settings
1597
+ }) {
1598
+ const retry = retryWithExponentialBackoff({ maxRetries });
1599
+ const { stream, warnings } = await retry(
1600
+ () => model.doStream({
1601
+ mode: {
1602
+ type: "regular",
1603
+ tools: tools == null ? void 0 : Object.entries(tools).map(([name, tool2]) => ({
1604
+ type: "function",
1605
+ name,
1606
+ description: tool2.description,
1607
+ parameters: zodToJsonSchema4(tool2.parameters)
1608
+ }))
1609
+ },
1610
+ ...prepareCallSettings(settings),
1611
+ inputFormat: getInputFormat({ prompt, messages }),
1612
+ prompt: convertToLanguageModelPrompt({
1613
+ system,
1614
+ prompt,
1615
+ messages
1616
+ }),
1617
+ abortSignal
1618
+ })
1619
+ );
1620
+ return new StreamTextResult({
1621
+ stream: runToolsTransformation({
1622
+ tools,
1623
+ generatorStream: stream
1624
+ }),
1625
+ warnings
1626
+ });
1627
+ }
1628
+ var StreamTextResult = class {
1629
+ constructor({
1630
+ stream,
1631
+ warnings
1632
+ }) {
1633
+ this.originalStream = stream;
1634
+ this.warnings = warnings;
1635
+ }
1636
+ get textStream() {
1637
+ return createAsyncIterableStream(this.originalStream, {
1638
+ transform(chunk, controller) {
1639
+ if (chunk.type === "text-delta") {
1640
+ if (chunk.textDelta.length > 0) {
1641
+ controller.enqueue(chunk.textDelta);
1642
+ }
1643
+ } else if (chunk.type === "error") {
1644
+ throw chunk.error;
1645
+ }
1646
+ }
1647
+ });
1648
+ }
1649
+ get fullStream() {
1650
+ return createAsyncIterableStream(this.originalStream, {
1651
+ transform(chunk, controller) {
1652
+ if (chunk.type === "text-delta") {
1653
+ if (chunk.textDelta.length > 0) {
1654
+ controller.enqueue(chunk);
1655
+ }
1656
+ } else {
1657
+ controller.enqueue(chunk);
1658
+ }
1659
+ }
1660
+ });
1661
+ }
1662
+ toAIStream(callbacks) {
1663
+ return readableFromAsyncIterable(this.textStream).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(
1664
+ createStreamDataTransformer(callbacks == null ? void 0 : callbacks.experimental_streamData)
1665
+ );
1666
+ }
1667
+ };
1668
+
1669
+ // core/tool/tool.ts
1670
+ function tool(tool2) {
1671
+ return tool2;
1672
+ }
3
1673
 
4
1674
  // shared/stream-parts.ts
5
1675
  var textStreamPart = {
@@ -182,10 +1852,6 @@ function formatStreamPart(type, value) {
182
1852
  }
183
1853
 
184
1854
  // shared/utils.ts
185
- var nanoid = customAlphabet(
186
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
187
- 7
188
- );
189
1855
  function createChunkDecoder(complex) {
190
1856
  const decoder = new TextDecoder();
191
1857
  if (!complex) {
@@ -587,6 +2253,12 @@ async function* asDeltaIterable(response, extractTextDeltaFromChunk) {
587
2253
  }
588
2254
  }
589
2255
  }
2256
+ function AWSBedrockAnthropicMessagesStream(response, callbacks) {
2257
+ return AWSBedrockStream(response, callbacks, (chunk) => {
2258
+ var _a;
2259
+ return (_a = chunk.delta) == null ? void 0 : _a.text;
2260
+ });
2261
+ }
590
2262
  function AWSBedrockAnthropicStream(response, callbacks) {
591
2263
  return AWSBedrockStream(response, callbacks, (chunk) => chunk.completion);
592
2264
  }
@@ -1060,13 +2732,13 @@ function createFunctionCallTransformer(callbacks) {
1060
2732
  const toolCalls = {
1061
2733
  tools: []
1062
2734
  };
1063
- for (const tool of payload.tool_calls) {
2735
+ for (const tool2 of payload.tool_calls) {
1064
2736
  toolCalls.tools.push({
1065
- id: tool.id,
2737
+ id: tool2.id,
1066
2738
  type: "function",
1067
2739
  func: {
1068
- name: tool.function.name,
1069
- arguments: JSON.parse(tool.function.arguments)
2740
+ name: tool2.function.name,
2741
+ arguments: JSON.parse(tool2.function.arguments)
1070
2742
  }
1071
2743
  });
1072
2744
  }
@@ -1237,7 +2909,7 @@ async function parseComplexResponse({
1237
2909
  abortControllerRef,
1238
2910
  update,
1239
2911
  onFinish,
1240
- generateId = nanoid,
2912
+ generateId: generateId2 = generateId,
1241
2913
  getCurrentDate = () => /* @__PURE__ */ new Date()
1242
2914
  }) {
1243
2915
  const createdAt = getCurrentDate();
@@ -1256,7 +2928,7 @@ async function parseComplexResponse({
1256
2928
  };
1257
2929
  } else {
1258
2930
  prefixMap["text"] = {
1259
- id: generateId(),
2931
+ id: generateId2(),
1260
2932
  role: "assistant",
1261
2933
  content: value,
1262
2934
  createdAt
@@ -1266,7 +2938,7 @@ async function parseComplexResponse({
1266
2938
  let functionCallMessage = null;
1267
2939
  if (type === "function_call") {
1268
2940
  prefixMap["function_call"] = {
1269
- id: generateId(),
2941
+ id: generateId2(),
1270
2942
  role: "assistant",
1271
2943
  content: "",
1272
2944
  function_call: value.function_call,
@@ -1278,7 +2950,7 @@ async function parseComplexResponse({
1278
2950
  let toolCallMessage = null;
1279
2951
  if (type === "tool_calls") {
1280
2952
  prefixMap["tool_calls"] = {
1281
- id: generateId(),
2953
+ id: generateId2(),
1282
2954
  role: "assistant",
1283
2955
  content: "",
1284
2956
  tool_calls: value.tool_calls,
@@ -1368,7 +3040,7 @@ var experimental_StreamingReactResponse = class {
1368
3040
  });
1369
3041
  lastPayload = payload;
1370
3042
  },
1371
- generateId: (_a = options.generateId) != null ? _a : nanoid,
3043
+ generateId: (_a = options.generateId) != null ? _a : generateId,
1372
3044
  onFinish: () => {
1373
3045
  if (lastPayload !== void 0) {
1374
3046
  resolveFunc({
@@ -1450,6 +3122,7 @@ function streamToResponse(res, response, init) {
1450
3122
  }
1451
3123
  export {
1452
3124
  AIStream,
3125
+ AWSBedrockAnthropicMessagesStream,
1453
3126
  AWSBedrockAnthropicStream,
1454
3127
  AWSBedrockCohereStream,
1455
3128
  AWSBedrockLlama2Stream,
@@ -1457,6 +3130,8 @@ export {
1457
3130
  AnthropicStream,
1458
3131
  COMPLEX_HEADER,
1459
3132
  CohereStream,
3133
+ GenerateObjectResult,
3134
+ GenerateTextResult,
1460
3135
  GoogleGenerativeAIStream,
1461
3136
  HuggingFaceStream,
1462
3137
  InkeepStream,
@@ -1464,7 +3139,11 @@ export {
1464
3139
  MistralStream,
1465
3140
  OpenAIStream,
1466
3141
  ReplicateStream,
3142
+ StreamObjectResult,
3143
+ StreamTextResult,
1467
3144
  StreamingTextResponse,
3145
+ convertDataContentToBase64String,
3146
+ convertDataContentToUint8Array,
1468
3147
  createCallbacksTransformer,
1469
3148
  createChunkDecoder,
1470
3149
  createEventStreamTransformer,
@@ -1472,10 +3151,16 @@ export {
1472
3151
  experimental_AssistantResponse,
1473
3152
  experimental_StreamData,
1474
3153
  experimental_StreamingReactResponse,
3154
+ experimental_generateObject,
3155
+ experimental_generateText,
3156
+ experimental_streamObject,
3157
+ experimental_streamText,
3158
+ generateId,
1475
3159
  isStreamStringEqualToType,
1476
- nanoid,
3160
+ generateId as nanoid,
1477
3161
  readableFromAsyncIterable,
1478
3162
  streamToResponse,
3163
+ tool,
1479
3164
  trimStartOfStreamHelper
1480
3165
  };
1481
3166
  //# sourceMappingURL=index.mjs.map