ai 3.1.0-canary.3 → 3.1.0

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