ai 4.0.7 → 4.0.9

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.
package/dist/index.js CHANGED
@@ -48,32 +48,200 @@ __export(streams_exports, {
48
48
  UnsupportedFunctionalityError: () => import_provider13.UnsupportedFunctionalityError,
49
49
  convertToCoreMessages: () => convertToCoreMessages,
50
50
  cosineSimilarity: () => cosineSimilarity,
51
- createStreamDataTransformer: () => createStreamDataTransformer,
51
+ createDataStream: () => createDataStream,
52
+ createDataStreamResponse: () => createDataStreamResponse,
52
53
  embed: () => embed,
53
54
  embedMany: () => embedMany,
54
55
  experimental_createProviderRegistry: () => experimental_createProviderRegistry,
55
56
  experimental_customProvider: () => experimental_customProvider,
56
57
  experimental_wrapLanguageModel: () => experimental_wrapLanguageModel,
57
- formatAssistantStreamPart: () => import_ui_utils11.formatAssistantStreamPart,
58
- formatDataStreamPart: () => import_ui_utils11.formatDataStreamPart,
58
+ formatAssistantStreamPart: () => import_ui_utils14.formatAssistantStreamPart,
59
+ formatDataStreamPart: () => import_ui_utils14.formatDataStreamPart,
59
60
  generateId: () => import_provider_utils12.generateId,
60
61
  generateObject: () => generateObject,
61
62
  generateText: () => generateText,
62
- jsonSchema: () => import_ui_utils8.jsonSchema,
63
- parseAssistantStreamPart: () => import_ui_utils11.parseAssistantStreamPart,
64
- parseDataStreamPart: () => import_ui_utils11.parseDataStreamPart,
65
- processDataStream: () => import_ui_utils11.processDataStream,
66
- processTextStream: () => import_ui_utils11.processTextStream,
63
+ jsonSchema: () => import_ui_utils9.jsonSchema,
64
+ parseAssistantStreamPart: () => import_ui_utils14.parseAssistantStreamPart,
65
+ parseDataStreamPart: () => import_ui_utils14.parseDataStreamPart,
66
+ pipeDataStreamToResponse: () => pipeDataStreamToResponse,
67
+ processDataStream: () => import_ui_utils14.processDataStream,
68
+ processTextStream: () => import_ui_utils14.processTextStream,
67
69
  streamObject: () => streamObject,
68
70
  streamText: () => streamText,
69
71
  tool: () => tool
70
72
  });
71
73
  module.exports = __toCommonJS(streams_exports);
72
- var import_ui_utils11 = require("@ai-sdk/ui-utils");
74
+ var import_ui_utils14 = require("@ai-sdk/ui-utils");
73
75
  var import_provider_utils12 = require("@ai-sdk/provider-utils");
74
76
 
75
77
  // core/index.ts
76
- var import_ui_utils8 = require("@ai-sdk/ui-utils");
78
+ var import_ui_utils9 = require("@ai-sdk/ui-utils");
79
+
80
+ // core/data-stream/create-data-stream.ts
81
+ var import_ui_utils = require("@ai-sdk/ui-utils");
82
+ function createDataStream({
83
+ execute,
84
+ onError = () => "An error occurred."
85
+ // mask error messages for safety by default
86
+ }) {
87
+ let controller;
88
+ const ongoingStreamPromises = [];
89
+ const stream = new ReadableStream({
90
+ start(controllerArg) {
91
+ controller = controllerArg;
92
+ }
93
+ });
94
+ try {
95
+ const result = execute({
96
+ writeData(data) {
97
+ controller.enqueue((0, import_ui_utils.formatDataStreamPart)("data", [data]));
98
+ },
99
+ writeMessageAnnotation(annotation) {
100
+ controller.enqueue(
101
+ (0, import_ui_utils.formatDataStreamPart)("message_annotations", [annotation])
102
+ );
103
+ },
104
+ merge(streamArg) {
105
+ ongoingStreamPromises.push(
106
+ (async () => {
107
+ const reader = streamArg.getReader();
108
+ while (true) {
109
+ const { done, value } = await reader.read();
110
+ if (done)
111
+ break;
112
+ controller.enqueue(value);
113
+ }
114
+ })().catch((error) => {
115
+ controller.enqueue((0, import_ui_utils.formatDataStreamPart)("error", onError(error)));
116
+ })
117
+ );
118
+ },
119
+ onError
120
+ });
121
+ if (result) {
122
+ result.catch((error) => {
123
+ controller.enqueue((0, import_ui_utils.formatDataStreamPart)("error", onError(error)));
124
+ });
125
+ }
126
+ } catch (error) {
127
+ controller.enqueue((0, import_ui_utils.formatDataStreamPart)("error", onError(error)));
128
+ }
129
+ const waitForStreams = new Promise(async (resolve) => {
130
+ while (ongoingStreamPromises.length > 0) {
131
+ await ongoingStreamPromises.shift();
132
+ }
133
+ resolve();
134
+ });
135
+ waitForStreams.finally(() => {
136
+ controller.close();
137
+ });
138
+ return stream;
139
+ }
140
+
141
+ // core/util/prepare-response-headers.ts
142
+ function prepareResponseHeaders(headers, {
143
+ contentType,
144
+ dataStreamVersion
145
+ }) {
146
+ const responseHeaders = new Headers(headers != null ? headers : {});
147
+ if (!responseHeaders.has("Content-Type")) {
148
+ responseHeaders.set("Content-Type", contentType);
149
+ }
150
+ if (dataStreamVersion !== void 0) {
151
+ responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
152
+ }
153
+ return responseHeaders;
154
+ }
155
+
156
+ // core/data-stream/create-data-stream-response.ts
157
+ function createDataStreamResponse({
158
+ status,
159
+ statusText,
160
+ headers,
161
+ execute,
162
+ onError
163
+ }) {
164
+ return new Response(
165
+ createDataStream({ execute, onError }).pipeThrough(new TextEncoderStream()),
166
+ {
167
+ status,
168
+ statusText,
169
+ headers: prepareResponseHeaders(headers, {
170
+ contentType: "text/plain; charset=utf-8",
171
+ dataStreamVersion: "v1"
172
+ })
173
+ }
174
+ );
175
+ }
176
+
177
+ // core/util/prepare-outgoing-http-headers.ts
178
+ function prepareOutgoingHttpHeaders(headers, {
179
+ contentType,
180
+ dataStreamVersion
181
+ }) {
182
+ const outgoingHeaders = {};
183
+ if (headers != null) {
184
+ for (const [key, value] of Object.entries(headers)) {
185
+ outgoingHeaders[key] = value;
186
+ }
187
+ }
188
+ if (outgoingHeaders["Content-Type"] == null) {
189
+ outgoingHeaders["Content-Type"] = contentType;
190
+ }
191
+ if (dataStreamVersion !== void 0) {
192
+ outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
193
+ }
194
+ return outgoingHeaders;
195
+ }
196
+
197
+ // core/util/write-to-server-response.ts
198
+ function writeToServerResponse({
199
+ response,
200
+ status,
201
+ statusText,
202
+ headers,
203
+ stream
204
+ }) {
205
+ response.writeHead(status != null ? status : 200, statusText, headers);
206
+ const reader = stream.getReader();
207
+ const read = async () => {
208
+ try {
209
+ while (true) {
210
+ const { done, value } = await reader.read();
211
+ if (done)
212
+ break;
213
+ response.write(value);
214
+ }
215
+ } catch (error) {
216
+ throw error;
217
+ } finally {
218
+ response.end();
219
+ }
220
+ };
221
+ read();
222
+ }
223
+
224
+ // core/data-stream/pipe-data-stream-to-response.ts
225
+ function pipeDataStreamToResponse(response, {
226
+ status,
227
+ statusText,
228
+ headers,
229
+ execute,
230
+ onError
231
+ }) {
232
+ writeToServerResponse({
233
+ response,
234
+ status,
235
+ statusText,
236
+ headers: prepareOutgoingHttpHeaders(headers, {
237
+ contentType: "text/plain; charset=utf-8",
238
+ dataStreamVersion: "v1"
239
+ }),
240
+ stream: createDataStream({ execute, onError }).pipeThrough(
241
+ new TextEncoderStream()
242
+ )
243
+ });
244
+ }
77
245
 
78
246
  // errors/invalid-argument-error.ts
79
247
  var import_provider = require("@ai-sdk/provider");
@@ -1566,21 +1734,6 @@ function calculateLanguageModelUsage({
1566
1734
  };
1567
1735
  }
1568
1736
 
1569
- // core/util/prepare-response-headers.ts
1570
- function prepareResponseHeaders(headers, {
1571
- contentType,
1572
- dataStreamVersion
1573
- }) {
1574
- const responseHeaders = new Headers(headers != null ? headers : {});
1575
- if (!responseHeaders.has("Content-Type")) {
1576
- responseHeaders.set("Content-Type", contentType);
1577
- }
1578
- if (dataStreamVersion !== void 0) {
1579
- responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
1580
- }
1581
- return responseHeaders;
1582
- }
1583
-
1584
1737
  // core/generate-object/inject-json-instruction.ts
1585
1738
  var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
1586
1739
  var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
@@ -1622,7 +1775,7 @@ _a7 = symbol7;
1622
1775
  // core/generate-object/output-strategy.ts
1623
1776
  var import_provider10 = require("@ai-sdk/provider");
1624
1777
  var import_provider_utils4 = require("@ai-sdk/provider-utils");
1625
- var import_ui_utils = require("@ai-sdk/ui-utils");
1778
+ var import_ui_utils2 = require("@ai-sdk/ui-utils");
1626
1779
 
1627
1780
  // core/util/async-iterable-stream.ts
1628
1781
  function createAsyncIterableStream(source, transformer) {
@@ -1839,9 +1992,9 @@ function getOutputStrategy({
1839
1992
  }) {
1840
1993
  switch (output) {
1841
1994
  case "object":
1842
- return objectOutputStrategy((0, import_ui_utils.asSchema)(schema));
1995
+ return objectOutputStrategy((0, import_ui_utils2.asSchema)(schema));
1843
1996
  case "array":
1844
- return arrayOutputStrategy((0, import_ui_utils.asSchema)(schema));
1997
+ return arrayOutputStrategy((0, import_ui_utils2.asSchema)(schema));
1845
1998
  case "enum":
1846
1999
  return enumOutputStrategy(enumValues);
1847
2000
  case "no-schema":
@@ -2348,7 +2501,7 @@ var DefaultGenerateObjectResult = class {
2348
2501
 
2349
2502
  // core/generate-object/stream-object.ts
2350
2503
  var import_provider_utils6 = require("@ai-sdk/provider-utils");
2351
- var import_ui_utils2 = require("@ai-sdk/ui-utils");
2504
+ var import_ui_utils3 = require("@ai-sdk/ui-utils");
2352
2505
 
2353
2506
  // util/delayed-promise.ts
2354
2507
  var DelayedPromise = class {
@@ -2476,53 +2629,6 @@ function now() {
2476
2629
  return (_b = (_a11 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a11.now()) != null ? _b : Date.now();
2477
2630
  }
2478
2631
 
2479
- // core/util/prepare-outgoing-http-headers.ts
2480
- function prepareOutgoingHttpHeaders(headers, {
2481
- contentType,
2482
- dataStreamVersion
2483
- }) {
2484
- const outgoingHeaders = {};
2485
- if (headers != null) {
2486
- for (const [key, value] of Object.entries(headers)) {
2487
- outgoingHeaders[key] = value;
2488
- }
2489
- }
2490
- if (outgoingHeaders["Content-Type"] == null) {
2491
- outgoingHeaders["Content-Type"] = contentType;
2492
- }
2493
- if (dataStreamVersion !== void 0) {
2494
- outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
2495
- }
2496
- return outgoingHeaders;
2497
- }
2498
-
2499
- // core/util/write-to-server-response.ts
2500
- function writeToServerResponse({
2501
- response,
2502
- status,
2503
- statusText,
2504
- headers,
2505
- stream
2506
- }) {
2507
- response.writeHead(status != null ? status : 200, statusText, headers);
2508
- const reader = stream.getReader();
2509
- const read = async () => {
2510
- try {
2511
- while (true) {
2512
- const { done, value } = await reader.read();
2513
- if (done)
2514
- break;
2515
- response.write(value);
2516
- }
2517
- } catch (error) {
2518
- throw error;
2519
- } finally {
2520
- response.end();
2521
- }
2522
- };
2523
- read();
2524
- }
2525
-
2526
2632
  // core/generate-object/stream-object.ts
2527
2633
  var originalGenerateId2 = (0, import_provider_utils6.createIdGenerator)({ prefix: "aiobj", size: 24 });
2528
2634
  function streamObject({
@@ -2823,8 +2929,8 @@ var DefaultStreamObjectResult = class {
2823
2929
  if (typeof chunk === "string") {
2824
2930
  accumulatedText += chunk;
2825
2931
  textDelta += chunk;
2826
- const { value: currentObjectJson, state: parseState } = (0, import_ui_utils2.parsePartialJson)(accumulatedText);
2827
- if (currentObjectJson !== void 0 && !(0, import_ui_utils2.isDeepEqualData)(latestObjectJson, currentObjectJson)) {
2932
+ const { value: currentObjectJson, state: parseState } = (0, import_ui_utils3.parsePartialJson)(accumulatedText);
2933
+ if (currentObjectJson !== void 0 && !(0, import_ui_utils3.isDeepEqualData)(latestObjectJson, currentObjectJson)) {
2828
2934
  const validationResult = outputStrategy.validatePartialResult({
2829
2935
  value: currentObjectJson,
2830
2936
  textDelta,
@@ -2832,7 +2938,7 @@ var DefaultStreamObjectResult = class {
2832
2938
  isFirstDelta,
2833
2939
  isFinalDelta: parseState === "successful-parse"
2834
2940
  });
2835
- if (validationResult.success && !(0, import_ui_utils2.isDeepEqualData)(
2941
+ if (validationResult.success && !(0, import_ui_utils3.isDeepEqualData)(
2836
2942
  latestObject,
2837
2943
  validationResult.value.partial
2838
2944
  )) {
@@ -3118,7 +3224,7 @@ var NoSuchToolError = class extends import_provider12.AISDKError {
3118
3224
  _a9 = symbol9;
3119
3225
 
3120
3226
  // core/prompt/prepare-tools-and-tool-choice.ts
3121
- var import_ui_utils3 = require("@ai-sdk/ui-utils");
3227
+ var import_ui_utils4 = require("@ai-sdk/ui-utils");
3122
3228
 
3123
3229
  // core/util/is-non-empty-object.ts
3124
3230
  function isNonEmptyObject(object2) {
@@ -3150,7 +3256,7 @@ function prepareToolsAndToolChoice({
3150
3256
  type: "function",
3151
3257
  name: name11,
3152
3258
  description: tool2.description,
3153
- parameters: (0, import_ui_utils3.asSchema)(tool2.parameters).jsonSchema
3259
+ parameters: (0, import_ui_utils4.asSchema)(tool2.parameters).jsonSchema
3154
3260
  };
3155
3261
  case "provider-defined":
3156
3262
  return {
@@ -3184,7 +3290,7 @@ function removeTextAfterLastWhitespace(text2) {
3184
3290
 
3185
3291
  // core/generate-text/parse-tool-call.ts
3186
3292
  var import_provider_utils7 = require("@ai-sdk/provider-utils");
3187
- var import_ui_utils4 = require("@ai-sdk/ui-utils");
3293
+ var import_ui_utils5 = require("@ai-sdk/ui-utils");
3188
3294
  function parseToolCall({
3189
3295
  toolCall,
3190
3296
  tools
@@ -3200,7 +3306,7 @@ function parseToolCall({
3200
3306
  availableTools: Object.keys(tools)
3201
3307
  });
3202
3308
  }
3203
- const schema = (0, import_ui_utils4.asSchema)(tool2.parameters);
3309
+ const schema = (0, import_ui_utils5.asSchema)(tool2.parameters);
3204
3310
  const parseResult = toolCall.args.trim() === "" ? (0, import_provider_utils7.safeValidateTypes)({ value: {}, schema }) : (0, import_provider_utils7.safeParseJSON)({ text: toolCall.args, schema });
3205
3311
  if (parseResult.success === false) {
3206
3312
  throw new InvalidToolArgumentsError({
@@ -3564,8 +3670,8 @@ async function executeTools({
3564
3670
  abortSignal
3565
3671
  }) {
3566
3672
  const toolResults = await Promise.all(
3567
- toolCalls.map(async (toolCall) => {
3568
- const tool2 = tools[toolCall.toolName];
3673
+ toolCalls.map(async ({ toolCallId, toolName, args }) => {
3674
+ const tool2 = tools[toolName];
3569
3675
  if ((tool2 == null ? void 0 : tool2.execute) == null) {
3570
3676
  return void 0;
3571
3677
  }
@@ -3578,16 +3684,17 @@ async function executeTools({
3578
3684
  operationId: "ai.toolCall",
3579
3685
  telemetry
3580
3686
  }),
3581
- "ai.toolCall.name": toolCall.toolName,
3582
- "ai.toolCall.id": toolCall.toolCallId,
3687
+ "ai.toolCall.name": toolName,
3688
+ "ai.toolCall.id": toolCallId,
3583
3689
  "ai.toolCall.args": {
3584
- output: () => JSON.stringify(toolCall.args)
3690
+ output: () => JSON.stringify(args)
3585
3691
  }
3586
3692
  }
3587
3693
  }),
3588
3694
  tracer,
3589
3695
  fn: async (span) => {
3590
- const result2 = await tool2.execute(toolCall.args, {
3696
+ const result2 = await tool2.execute(args, {
3697
+ toolCallId,
3591
3698
  messages,
3592
3699
  abortSignal
3593
3700
  });
@@ -3608,9 +3715,9 @@ async function executeTools({
3608
3715
  }
3609
3716
  });
3610
3717
  return {
3611
- toolCallId: toolCall.toolCallId,
3612
- toolName: toolCall.toolName,
3613
- args: toolCall.args,
3718
+ toolCallId,
3719
+ toolName,
3720
+ args,
3614
3721
  result
3615
3722
  };
3616
3723
  })
@@ -3638,7 +3745,7 @@ var DefaultGenerateTextResult = class {
3638
3745
 
3639
3746
  // core/generate-text/stream-text.ts
3640
3747
  var import_provider_utils9 = require("@ai-sdk/provider-utils");
3641
- var import_ui_utils6 = require("@ai-sdk/ui-utils");
3748
+ var import_ui_utils7 = require("@ai-sdk/ui-utils");
3642
3749
 
3643
3750
  // core/util/merge-streams.ts
3644
3751
  function mergeStreams(stream1, stream2) {
@@ -3729,7 +3836,7 @@ function mergeStreams(stream1, stream2) {
3729
3836
  }
3730
3837
 
3731
3838
  // core/generate-text/run-tools-transformation.ts
3732
- var import_ui_utils5 = require("@ai-sdk/ui-utils");
3839
+ var import_ui_utils6 = require("@ai-sdk/ui-utils");
3733
3840
  function runToolsTransformation({
3734
3841
  tools,
3735
3842
  generatorStream,
@@ -3813,7 +3920,7 @@ function runToolsTransformation({
3813
3920
  });
3814
3921
  controller.enqueue(toolCall);
3815
3922
  if (tool2.execute != null) {
3816
- const toolExecutionId = (0, import_ui_utils5.generateId)();
3923
+ const toolExecutionId = (0, import_ui_utils6.generateId)();
3817
3924
  outstandingToolResults.add(toolExecutionId);
3818
3925
  recordSpan({
3819
3926
  name: "ai.toolCall",
@@ -3833,6 +3940,7 @@ function runToolsTransformation({
3833
3940
  }),
3834
3941
  tracer,
3835
3942
  fn: async (span) => tool2.execute(toolCall.args, {
3943
+ toolCallId: toolCall.toolCallId,
3836
3944
  messages,
3837
3945
  abortSignal
3838
3946
  }).then(
@@ -4576,12 +4684,12 @@ var DefaultStreamTextResult = class {
4576
4684
  const chunkType = chunk.type;
4577
4685
  switch (chunkType) {
4578
4686
  case "text-delta": {
4579
- controller.enqueue((0, import_ui_utils6.formatDataStreamPart)("text", chunk.textDelta));
4687
+ controller.enqueue((0, import_ui_utils7.formatDataStreamPart)("text", chunk.textDelta));
4580
4688
  break;
4581
4689
  }
4582
4690
  case "tool-call-streaming-start": {
4583
4691
  controller.enqueue(
4584
- (0, import_ui_utils6.formatDataStreamPart)("tool_call_streaming_start", {
4692
+ (0, import_ui_utils7.formatDataStreamPart)("tool_call_streaming_start", {
4585
4693
  toolCallId: chunk.toolCallId,
4586
4694
  toolName: chunk.toolName
4587
4695
  })
@@ -4590,7 +4698,7 @@ var DefaultStreamTextResult = class {
4590
4698
  }
4591
4699
  case "tool-call-delta": {
4592
4700
  controller.enqueue(
4593
- (0, import_ui_utils6.formatDataStreamPart)("tool_call_delta", {
4701
+ (0, import_ui_utils7.formatDataStreamPart)("tool_call_delta", {
4594
4702
  toolCallId: chunk.toolCallId,
4595
4703
  argsTextDelta: chunk.argsTextDelta
4596
4704
  })
@@ -4599,7 +4707,7 @@ var DefaultStreamTextResult = class {
4599
4707
  }
4600
4708
  case "tool-call": {
4601
4709
  controller.enqueue(
4602
- (0, import_ui_utils6.formatDataStreamPart)("tool_call", {
4710
+ (0, import_ui_utils7.formatDataStreamPart)("tool_call", {
4603
4711
  toolCallId: chunk.toolCallId,
4604
4712
  toolName: chunk.toolName,
4605
4713
  args: chunk.args
@@ -4609,7 +4717,7 @@ var DefaultStreamTextResult = class {
4609
4717
  }
4610
4718
  case "tool-result": {
4611
4719
  controller.enqueue(
4612
- (0, import_ui_utils6.formatDataStreamPart)("tool_result", {
4720
+ (0, import_ui_utils7.formatDataStreamPart)("tool_result", {
4613
4721
  toolCallId: chunk.toolCallId,
4614
4722
  result: chunk.result
4615
4723
  })
@@ -4618,13 +4726,13 @@ var DefaultStreamTextResult = class {
4618
4726
  }
4619
4727
  case "error": {
4620
4728
  controller.enqueue(
4621
- (0, import_ui_utils6.formatDataStreamPart)("error", getErrorMessage3(chunk.error))
4729
+ (0, import_ui_utils7.formatDataStreamPart)("error", getErrorMessage3(chunk.error))
4622
4730
  );
4623
4731
  break;
4624
4732
  }
4625
4733
  case "step-finish": {
4626
4734
  controller.enqueue(
4627
- (0, import_ui_utils6.formatDataStreamPart)("finish_step", {
4735
+ (0, import_ui_utils7.formatDataStreamPart)("finish_step", {
4628
4736
  finishReason: chunk.finishReason,
4629
4737
  usage: sendUsage ? {
4630
4738
  promptTokens: chunk.usage.promptTokens,
@@ -4637,7 +4745,7 @@ var DefaultStreamTextResult = class {
4637
4745
  }
4638
4746
  case "finish": {
4639
4747
  controller.enqueue(
4640
- (0, import_ui_utils6.formatDataStreamPart)("finish_message", {
4748
+ (0, import_ui_utils7.formatDataStreamPart)("finish_message", {
4641
4749
  finishReason: chunk.finishReason,
4642
4750
  usage: sendUsage ? {
4643
4751
  promptTokens: chunk.usage.promptTokens,
@@ -4654,7 +4762,7 @@ var DefaultStreamTextResult = class {
4654
4762
  }
4655
4763
  }
4656
4764
  });
4657
- return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer).pipeThrough(new TextEncoderStream());
4765
+ return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer);
4658
4766
  }
4659
4767
  pipeDataStreamToResponse(response, {
4660
4768
  status,
@@ -4686,13 +4794,21 @@ var DefaultStreamTextResult = class {
4686
4794
  stream: this.textStream.pipeThrough(new TextEncoderStream())
4687
4795
  });
4688
4796
  }
4797
+ // TODO breaking change 5.0: remove pipeThrough(new TextEncoderStream())
4689
4798
  toDataStream(options) {
4690
4799
  const stream = this.toDataStreamInternal({
4691
4800
  getErrorMessage: options == null ? void 0 : options.getErrorMessage,
4692
4801
  sendUsage: options == null ? void 0 : options.sendUsage
4693
- });
4802
+ }).pipeThrough(new TextEncoderStream());
4694
4803
  return (options == null ? void 0 : options.data) ? mergeStreams(options == null ? void 0 : options.data.stream, stream) : stream;
4695
4804
  }
4805
+ mergeIntoDataStream(writer) {
4806
+ writer.merge(
4807
+ this.toDataStreamInternal({
4808
+ getErrorMessage: writer.onError
4809
+ })
4810
+ );
4811
+ }
4696
4812
  toDataStreamResponse({
4697
4813
  headers,
4698
4814
  status,
@@ -4731,7 +4847,7 @@ __export(output_exports, {
4731
4847
  text: () => text
4732
4848
  });
4733
4849
  var import_provider_utils10 = require("@ai-sdk/provider-utils");
4734
- var import_ui_utils7 = require("@ai-sdk/ui-utils");
4850
+ var import_ui_utils8 = require("@ai-sdk/ui-utils");
4735
4851
  var text = () => ({
4736
4852
  type: "text",
4737
4853
  responseFormat: () => ({ type: "text" }),
@@ -4745,7 +4861,7 @@ var text = () => ({
4745
4861
  var object = ({
4746
4862
  schema: inputSchema
4747
4863
  }) => {
4748
- const schema = (0, import_ui_utils7.asSchema)(inputSchema);
4864
+ const schema = (0, import_ui_utils8.asSchema)(inputSchema);
4749
4865
  return {
4750
4866
  type: "object",
4751
4867
  responseFormat: ({ model }) => ({
@@ -4946,7 +5062,7 @@ function magnitude(vector) {
4946
5062
  }
4947
5063
 
4948
5064
  // streams/assistant-response.ts
4949
- var import_ui_utils9 = require("@ai-sdk/ui-utils");
5065
+ var import_ui_utils10 = require("@ai-sdk/ui-utils");
4950
5066
  function AssistantResponse({ threadId, messageId }, process2) {
4951
5067
  const stream = new ReadableStream({
4952
5068
  async start(controller) {
@@ -4955,20 +5071,20 @@ function AssistantResponse({ threadId, messageId }, process2) {
4955
5071
  const sendMessage = (message) => {
4956
5072
  controller.enqueue(
4957
5073
  textEncoder.encode(
4958
- (0, import_ui_utils9.formatAssistantStreamPart)("assistant_message", message)
5074
+ (0, import_ui_utils10.formatAssistantStreamPart)("assistant_message", message)
4959
5075
  )
4960
5076
  );
4961
5077
  };
4962
5078
  const sendDataMessage = (message) => {
4963
5079
  controller.enqueue(
4964
5080
  textEncoder.encode(
4965
- (0, import_ui_utils9.formatAssistantStreamPart)("data_message", message)
5081
+ (0, import_ui_utils10.formatAssistantStreamPart)("data_message", message)
4966
5082
  )
4967
5083
  );
4968
5084
  };
4969
5085
  const sendError = (errorMessage) => {
4970
5086
  controller.enqueue(
4971
- textEncoder.encode((0, import_ui_utils9.formatAssistantStreamPart)("error", errorMessage))
5087
+ textEncoder.encode((0, import_ui_utils10.formatAssistantStreamPart)("error", errorMessage))
4972
5088
  );
4973
5089
  };
4974
5090
  const forwardStream = async (stream2) => {
@@ -4979,7 +5095,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
4979
5095
  case "thread.message.created": {
4980
5096
  controller.enqueue(
4981
5097
  textEncoder.encode(
4982
- (0, import_ui_utils9.formatAssistantStreamPart)("assistant_message", {
5098
+ (0, import_ui_utils10.formatAssistantStreamPart)("assistant_message", {
4983
5099
  id: value.data.id,
4984
5100
  role: "assistant",
4985
5101
  content: [{ type: "text", text: { value: "" } }]
@@ -4993,7 +5109,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
4993
5109
  if ((content == null ? void 0 : content.type) === "text" && ((_b = content.text) == null ? void 0 : _b.value) != null) {
4994
5110
  controller.enqueue(
4995
5111
  textEncoder.encode(
4996
- (0, import_ui_utils9.formatAssistantStreamPart)("text", content.text.value)
5112
+ (0, import_ui_utils10.formatAssistantStreamPart)("text", content.text.value)
4997
5113
  )
4998
5114
  );
4999
5115
  }
@@ -5010,7 +5126,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5010
5126
  };
5011
5127
  controller.enqueue(
5012
5128
  textEncoder.encode(
5013
- (0, import_ui_utils9.formatAssistantStreamPart)("assistant_control_data", {
5129
+ (0, import_ui_utils10.formatAssistantStreamPart)("assistant_control_data", {
5014
5130
  threadId,
5015
5131
  messageId
5016
5132
  })
@@ -5044,9 +5160,11 @@ function AssistantResponse({ threadId, messageId }, process2) {
5044
5160
  // streams/langchain-adapter.ts
5045
5161
  var langchain_adapter_exports = {};
5046
5162
  __export(langchain_adapter_exports, {
5163
+ mergeIntoDataStream: () => mergeIntoDataStream,
5047
5164
  toDataStream: () => toDataStream,
5048
5165
  toDataStreamResponse: () => toDataStreamResponse
5049
5166
  });
5167
+ var import_ui_utils11 = require("@ai-sdk/ui-utils");
5050
5168
 
5051
5169
  // streams/stream-callbacks.ts
5052
5170
  function createCallbacksTransformer(callbacks = {}) {
@@ -5077,87 +5195,8 @@ function createCallbacksTransformer(callbacks = {}) {
5077
5195
  });
5078
5196
  }
5079
5197
 
5080
- // streams/stream-data.ts
5081
- var import_ui_utils10 = require("@ai-sdk/ui-utils");
5082
-
5083
- // util/constants.ts
5084
- var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
5085
-
5086
- // streams/stream-data.ts
5087
- var StreamData = class {
5088
- constructor() {
5089
- this.encoder = new TextEncoder();
5090
- this.controller = null;
5091
- this.isClosed = false;
5092
- this.warningTimeout = null;
5093
- const self = this;
5094
- this.stream = new ReadableStream({
5095
- start: async (controller) => {
5096
- self.controller = controller;
5097
- if (process.env.NODE_ENV === "development") {
5098
- self.warningTimeout = setTimeout(() => {
5099
- console.warn(
5100
- "The data stream is hanging. Did you forget to close it with `data.close()`?"
5101
- );
5102
- }, HANGING_STREAM_WARNING_TIME_MS);
5103
- }
5104
- },
5105
- pull: (controller) => {
5106
- },
5107
- cancel: (reason) => {
5108
- this.isClosed = true;
5109
- }
5110
- });
5111
- }
5112
- async close() {
5113
- if (this.isClosed) {
5114
- throw new Error("Data Stream has already been closed.");
5115
- }
5116
- if (!this.controller) {
5117
- throw new Error("Stream controller is not initialized.");
5118
- }
5119
- this.controller.close();
5120
- this.isClosed = true;
5121
- if (this.warningTimeout) {
5122
- clearTimeout(this.warningTimeout);
5123
- }
5124
- }
5125
- append(value) {
5126
- if (this.isClosed) {
5127
- throw new Error("Data Stream has already been closed.");
5128
- }
5129
- if (!this.controller) {
5130
- throw new Error("Stream controller is not initialized.");
5131
- }
5132
- this.controller.enqueue(
5133
- this.encoder.encode((0, import_ui_utils10.formatDataStreamPart)("data", [value]))
5134
- );
5135
- }
5136
- appendMessageAnnotation(value) {
5137
- if (this.isClosed) {
5138
- throw new Error("Data Stream has already been closed.");
5139
- }
5140
- if (!this.controller) {
5141
- throw new Error("Stream controller is not initialized.");
5142
- }
5143
- this.controller.enqueue(
5144
- this.encoder.encode((0, import_ui_utils10.formatDataStreamPart)("message_annotations", [value]))
5145
- );
5146
- }
5147
- };
5148
- function createStreamDataTransformer() {
5149
- const encoder = new TextEncoder();
5150
- const decoder = new TextDecoder();
5151
- return new TransformStream({
5152
- transform: async (chunk, controller) => {
5153
- const message = decoder.decode(chunk);
5154
- controller.enqueue(encoder.encode((0, import_ui_utils10.formatDataStreamPart)("text", message)));
5155
- }
5156
- });
5157
- }
5158
-
5159
5198
  // streams/langchain-adapter.ts
5160
- function toDataStream(stream, callbacks) {
5199
+ function toDataStreamInternal(stream, callbacks) {
5161
5200
  return stream.pipeThrough(
5162
5201
  new TransformStream({
5163
5202
  transform: async (value, controller) => {
@@ -5178,11 +5217,25 @@ function toDataStream(stream, callbacks) {
5178
5217
  forwardAIMessageChunk(value, controller);
5179
5218
  }
5180
5219
  })
5181
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5220
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
5221
+ new TransformStream({
5222
+ transform: async (chunk, controller) => {
5223
+ controller.enqueue((0, import_ui_utils11.formatDataStreamPart)("text", chunk));
5224
+ }
5225
+ })
5226
+ );
5227
+ }
5228
+ function toDataStream(stream, callbacks) {
5229
+ return toDataStreamInternal(stream, callbacks).pipeThrough(
5230
+ new TextEncoderStream()
5231
+ );
5182
5232
  }
5183
5233
  function toDataStreamResponse(stream, options) {
5184
5234
  var _a11;
5185
- const dataStream = toDataStream(stream, options == null ? void 0 : options.callbacks);
5235
+ const dataStream = toDataStreamInternal(
5236
+ stream,
5237
+ options == null ? void 0 : options.callbacks
5238
+ ).pipeThrough(new TextEncoderStream());
5186
5239
  const data = options == null ? void 0 : options.data;
5187
5240
  const init = options == null ? void 0 : options.init;
5188
5241
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
@@ -5195,6 +5248,9 @@ function toDataStreamResponse(stream, options) {
5195
5248
  })
5196
5249
  });
5197
5250
  }
5251
+ function mergeIntoDataStream(stream, options) {
5252
+ options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
5253
+ }
5198
5254
  function forwardAIMessageChunk(chunk, controller) {
5199
5255
  if (typeof chunk.content === "string") {
5200
5256
  controller.enqueue(chunk.content);
@@ -5211,11 +5267,13 @@ function forwardAIMessageChunk(chunk, controller) {
5211
5267
  // streams/llamaindex-adapter.ts
5212
5268
  var llamaindex_adapter_exports = {};
5213
5269
  __export(llamaindex_adapter_exports, {
5270
+ mergeIntoDataStream: () => mergeIntoDataStream2,
5214
5271
  toDataStream: () => toDataStream2,
5215
5272
  toDataStreamResponse: () => toDataStreamResponse2
5216
5273
  });
5217
5274
  var import_provider_utils11 = require("@ai-sdk/provider-utils");
5218
- function toDataStream2(stream, callbacks) {
5275
+ var import_ui_utils12 = require("@ai-sdk/ui-utils");
5276
+ function toDataStreamInternal2(stream, callbacks) {
5219
5277
  const trimStart = trimStartOfStream();
5220
5278
  return (0, import_provider_utils11.convertAsyncIteratorToReadableStream)(stream[Symbol.asyncIterator]()).pipeThrough(
5221
5279
  new TransformStream({
@@ -5223,12 +5281,25 @@ function toDataStream2(stream, callbacks) {
5223
5281
  controller.enqueue(trimStart(message.delta));
5224
5282
  }
5225
5283
  })
5226
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5284
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
5285
+ new TransformStream({
5286
+ transform: async (chunk, controller) => {
5287
+ controller.enqueue((0, import_ui_utils12.formatDataStreamPart)("text", chunk));
5288
+ }
5289
+ })
5290
+ );
5291
+ }
5292
+ function toDataStream2(stream, callbacks) {
5293
+ return toDataStreamInternal2(stream, callbacks).pipeThrough(
5294
+ new TextEncoderStream()
5295
+ );
5227
5296
  }
5228
5297
  function toDataStreamResponse2(stream, options = {}) {
5229
5298
  var _a11;
5230
5299
  const { init, data, callbacks } = options;
5231
- const dataStream = toDataStream2(stream, callbacks);
5300
+ const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
5301
+ new TextEncoderStream()
5302
+ );
5232
5303
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
5233
5304
  return new Response(responseStream, {
5234
5305
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
@@ -5239,6 +5310,9 @@ function toDataStreamResponse2(stream, options = {}) {
5239
5310
  })
5240
5311
  });
5241
5312
  }
5313
+ function mergeIntoDataStream2(stream, options) {
5314
+ options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
5315
+ }
5242
5316
  function trimStartOfStream() {
5243
5317
  let isStreamStart = true;
5244
5318
  return (text2) => {
@@ -5250,6 +5324,75 @@ function trimStartOfStream() {
5250
5324
  return text2;
5251
5325
  };
5252
5326
  }
5327
+
5328
+ // streams/stream-data.ts
5329
+ var import_ui_utils13 = require("@ai-sdk/ui-utils");
5330
+
5331
+ // util/constants.ts
5332
+ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
5333
+
5334
+ // streams/stream-data.ts
5335
+ var StreamData = class {
5336
+ constructor() {
5337
+ this.encoder = new TextEncoder();
5338
+ this.controller = null;
5339
+ this.isClosed = false;
5340
+ this.warningTimeout = null;
5341
+ const self = this;
5342
+ this.stream = new ReadableStream({
5343
+ start: async (controller) => {
5344
+ self.controller = controller;
5345
+ if (process.env.NODE_ENV === "development") {
5346
+ self.warningTimeout = setTimeout(() => {
5347
+ console.warn(
5348
+ "The data stream is hanging. Did you forget to close it with `data.close()`?"
5349
+ );
5350
+ }, HANGING_STREAM_WARNING_TIME_MS);
5351
+ }
5352
+ },
5353
+ pull: (controller) => {
5354
+ },
5355
+ cancel: (reason) => {
5356
+ this.isClosed = true;
5357
+ }
5358
+ });
5359
+ }
5360
+ async close() {
5361
+ if (this.isClosed) {
5362
+ throw new Error("Data Stream has already been closed.");
5363
+ }
5364
+ if (!this.controller) {
5365
+ throw new Error("Stream controller is not initialized.");
5366
+ }
5367
+ this.controller.close();
5368
+ this.isClosed = true;
5369
+ if (this.warningTimeout) {
5370
+ clearTimeout(this.warningTimeout);
5371
+ }
5372
+ }
5373
+ append(value) {
5374
+ if (this.isClosed) {
5375
+ throw new Error("Data Stream has already been closed.");
5376
+ }
5377
+ if (!this.controller) {
5378
+ throw new Error("Stream controller is not initialized.");
5379
+ }
5380
+ this.controller.enqueue(
5381
+ this.encoder.encode((0, import_ui_utils13.formatDataStreamPart)("data", [value]))
5382
+ );
5383
+ }
5384
+ appendMessageAnnotation(value) {
5385
+ if (this.isClosed) {
5386
+ throw new Error("Data Stream has already been closed.");
5387
+ }
5388
+ if (!this.controller) {
5389
+ throw new Error("Stream controller is not initialized.");
5390
+ }
5391
+ this.controller.enqueue(
5392
+ this.encoder.encode((0, import_ui_utils13.formatDataStreamPart)("message_annotations", [value]))
5393
+ );
5394
+ }
5395
+ };
5253
5396
  // Annotate the CommonJS export names for ESM import in node:
5254
5397
  0 && (module.exports = {
5255
5398
  AISDKError,
@@ -5280,7 +5423,8 @@ function trimStartOfStream() {
5280
5423
  UnsupportedFunctionalityError,
5281
5424
  convertToCoreMessages,
5282
5425
  cosineSimilarity,
5283
- createStreamDataTransformer,
5426
+ createDataStream,
5427
+ createDataStreamResponse,
5284
5428
  embed,
5285
5429
  embedMany,
5286
5430
  experimental_createProviderRegistry,
@@ -5294,6 +5438,7 @@ function trimStartOfStream() {
5294
5438
  jsonSchema,
5295
5439
  parseAssistantStreamPart,
5296
5440
  parseDataStreamPart,
5441
+ pipeDataStreamToResponse,
5297
5442
  processDataStream,
5298
5443
  processTextStream,
5299
5444
  streamObject,