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