ai 3.1.0-canary.4 → 3.1.1

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