ai 4.0.8 → 4.0.10

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,202 @@ __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
+ ongoingStreamPromises.push(
123
+ result.catch((error) => {
124
+ controller.enqueue((0, import_ui_utils.formatDataStreamPart)("error", onError(error)));
125
+ })
126
+ );
127
+ }
128
+ } catch (error) {
129
+ controller.enqueue((0, import_ui_utils.formatDataStreamPart)("error", onError(error)));
130
+ }
131
+ const waitForStreams = new Promise(async (resolve) => {
132
+ while (ongoingStreamPromises.length > 0) {
133
+ await ongoingStreamPromises.shift();
134
+ }
135
+ resolve();
136
+ });
137
+ waitForStreams.finally(() => {
138
+ controller.close();
139
+ });
140
+ return stream;
141
+ }
142
+
143
+ // core/util/prepare-response-headers.ts
144
+ function prepareResponseHeaders(headers, {
145
+ contentType,
146
+ dataStreamVersion
147
+ }) {
148
+ const responseHeaders = new Headers(headers != null ? headers : {});
149
+ if (!responseHeaders.has("Content-Type")) {
150
+ responseHeaders.set("Content-Type", contentType);
151
+ }
152
+ if (dataStreamVersion !== void 0) {
153
+ responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
154
+ }
155
+ return responseHeaders;
156
+ }
157
+
158
+ // core/data-stream/create-data-stream-response.ts
159
+ function createDataStreamResponse({
160
+ status,
161
+ statusText,
162
+ headers,
163
+ execute,
164
+ onError
165
+ }) {
166
+ return new Response(
167
+ createDataStream({ execute, onError }).pipeThrough(new TextEncoderStream()),
168
+ {
169
+ status,
170
+ statusText,
171
+ headers: prepareResponseHeaders(headers, {
172
+ contentType: "text/plain; charset=utf-8",
173
+ dataStreamVersion: "v1"
174
+ })
175
+ }
176
+ );
177
+ }
178
+
179
+ // core/util/prepare-outgoing-http-headers.ts
180
+ function prepareOutgoingHttpHeaders(headers, {
181
+ contentType,
182
+ dataStreamVersion
183
+ }) {
184
+ const outgoingHeaders = {};
185
+ if (headers != null) {
186
+ for (const [key, value] of Object.entries(headers)) {
187
+ outgoingHeaders[key] = value;
188
+ }
189
+ }
190
+ if (outgoingHeaders["Content-Type"] == null) {
191
+ outgoingHeaders["Content-Type"] = contentType;
192
+ }
193
+ if (dataStreamVersion !== void 0) {
194
+ outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
195
+ }
196
+ return outgoingHeaders;
197
+ }
198
+
199
+ // core/util/write-to-server-response.ts
200
+ function writeToServerResponse({
201
+ response,
202
+ status,
203
+ statusText,
204
+ headers,
205
+ stream
206
+ }) {
207
+ response.writeHead(status != null ? status : 200, statusText, headers);
208
+ const reader = stream.getReader();
209
+ const read = async () => {
210
+ try {
211
+ while (true) {
212
+ const { done, value } = await reader.read();
213
+ if (done)
214
+ break;
215
+ response.write(value);
216
+ }
217
+ } catch (error) {
218
+ throw error;
219
+ } finally {
220
+ response.end();
221
+ }
222
+ };
223
+ read();
224
+ }
225
+
226
+ // core/data-stream/pipe-data-stream-to-response.ts
227
+ function pipeDataStreamToResponse(response, {
228
+ status,
229
+ statusText,
230
+ headers,
231
+ execute,
232
+ onError
233
+ }) {
234
+ writeToServerResponse({
235
+ response,
236
+ status,
237
+ statusText,
238
+ headers: prepareOutgoingHttpHeaders(headers, {
239
+ contentType: "text/plain; charset=utf-8",
240
+ dataStreamVersion: "v1"
241
+ }),
242
+ stream: createDataStream({ execute, onError }).pipeThrough(
243
+ new TextEncoderStream()
244
+ )
245
+ });
246
+ }
77
247
 
78
248
  // errors/invalid-argument-error.ts
79
249
  var import_provider = require("@ai-sdk/provider");
@@ -1566,21 +1736,6 @@ function calculateLanguageModelUsage({
1566
1736
  };
1567
1737
  }
1568
1738
 
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
1739
  // core/generate-object/inject-json-instruction.ts
1585
1740
  var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
1586
1741
  var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
@@ -1622,7 +1777,7 @@ _a7 = symbol7;
1622
1777
  // core/generate-object/output-strategy.ts
1623
1778
  var import_provider10 = require("@ai-sdk/provider");
1624
1779
  var import_provider_utils4 = require("@ai-sdk/provider-utils");
1625
- var import_ui_utils = require("@ai-sdk/ui-utils");
1780
+ var import_ui_utils2 = require("@ai-sdk/ui-utils");
1626
1781
 
1627
1782
  // core/util/async-iterable-stream.ts
1628
1783
  function createAsyncIterableStream(source, transformer) {
@@ -1839,9 +1994,9 @@ function getOutputStrategy({
1839
1994
  }) {
1840
1995
  switch (output) {
1841
1996
  case "object":
1842
- return objectOutputStrategy((0, import_ui_utils.asSchema)(schema));
1997
+ return objectOutputStrategy((0, import_ui_utils2.asSchema)(schema));
1843
1998
  case "array":
1844
- return arrayOutputStrategy((0, import_ui_utils.asSchema)(schema));
1999
+ return arrayOutputStrategy((0, import_ui_utils2.asSchema)(schema));
1845
2000
  case "enum":
1846
2001
  return enumOutputStrategy(enumValues);
1847
2002
  case "no-schema":
@@ -2348,7 +2503,7 @@ var DefaultGenerateObjectResult = class {
2348
2503
 
2349
2504
  // core/generate-object/stream-object.ts
2350
2505
  var import_provider_utils6 = require("@ai-sdk/provider-utils");
2351
- var import_ui_utils2 = require("@ai-sdk/ui-utils");
2506
+ var import_ui_utils3 = require("@ai-sdk/ui-utils");
2352
2507
 
2353
2508
  // util/delayed-promise.ts
2354
2509
  var DelayedPromise = class {
@@ -2476,53 +2631,6 @@ function now() {
2476
2631
  return (_b = (_a11 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a11.now()) != null ? _b : Date.now();
2477
2632
  }
2478
2633
 
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
2634
  // core/generate-object/stream-object.ts
2527
2635
  var originalGenerateId2 = (0, import_provider_utils6.createIdGenerator)({ prefix: "aiobj", size: 24 });
2528
2636
  function streamObject({
@@ -2823,8 +2931,8 @@ var DefaultStreamObjectResult = class {
2823
2931
  if (typeof chunk === "string") {
2824
2932
  accumulatedText += chunk;
2825
2933
  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)) {
2934
+ const { value: currentObjectJson, state: parseState } = (0, import_ui_utils3.parsePartialJson)(accumulatedText);
2935
+ if (currentObjectJson !== void 0 && !(0, import_ui_utils3.isDeepEqualData)(latestObjectJson, currentObjectJson)) {
2828
2936
  const validationResult = outputStrategy.validatePartialResult({
2829
2937
  value: currentObjectJson,
2830
2938
  textDelta,
@@ -2832,7 +2940,7 @@ var DefaultStreamObjectResult = class {
2832
2940
  isFirstDelta,
2833
2941
  isFinalDelta: parseState === "successful-parse"
2834
2942
  });
2835
- if (validationResult.success && !(0, import_ui_utils2.isDeepEqualData)(
2943
+ if (validationResult.success && !(0, import_ui_utils3.isDeepEqualData)(
2836
2944
  latestObject,
2837
2945
  validationResult.value.partial
2838
2946
  )) {
@@ -3118,7 +3226,7 @@ var NoSuchToolError = class extends import_provider12.AISDKError {
3118
3226
  _a9 = symbol9;
3119
3227
 
3120
3228
  // core/prompt/prepare-tools-and-tool-choice.ts
3121
- var import_ui_utils3 = require("@ai-sdk/ui-utils");
3229
+ var import_ui_utils4 = require("@ai-sdk/ui-utils");
3122
3230
 
3123
3231
  // core/util/is-non-empty-object.ts
3124
3232
  function isNonEmptyObject(object2) {
@@ -3150,7 +3258,7 @@ function prepareToolsAndToolChoice({
3150
3258
  type: "function",
3151
3259
  name: name11,
3152
3260
  description: tool2.description,
3153
- parameters: (0, import_ui_utils3.asSchema)(tool2.parameters).jsonSchema
3261
+ parameters: (0, import_ui_utils4.asSchema)(tool2.parameters).jsonSchema
3154
3262
  };
3155
3263
  case "provider-defined":
3156
3264
  return {
@@ -3184,7 +3292,7 @@ function removeTextAfterLastWhitespace(text2) {
3184
3292
 
3185
3293
  // core/generate-text/parse-tool-call.ts
3186
3294
  var import_provider_utils7 = require("@ai-sdk/provider-utils");
3187
- var import_ui_utils4 = require("@ai-sdk/ui-utils");
3295
+ var import_ui_utils5 = require("@ai-sdk/ui-utils");
3188
3296
  function parseToolCall({
3189
3297
  toolCall,
3190
3298
  tools
@@ -3200,7 +3308,7 @@ function parseToolCall({
3200
3308
  availableTools: Object.keys(tools)
3201
3309
  });
3202
3310
  }
3203
- const schema = (0, import_ui_utils4.asSchema)(tool2.parameters);
3311
+ const schema = (0, import_ui_utils5.asSchema)(tool2.parameters);
3204
3312
  const parseResult = toolCall.args.trim() === "" ? (0, import_provider_utils7.safeValidateTypes)({ value: {}, schema }) : (0, import_provider_utils7.safeParseJSON)({ text: toolCall.args, schema });
3205
3313
  if (parseResult.success === false) {
3206
3314
  throw new InvalidToolArgumentsError({
@@ -3639,7 +3747,7 @@ var DefaultGenerateTextResult = class {
3639
3747
 
3640
3748
  // core/generate-text/stream-text.ts
3641
3749
  var import_provider_utils9 = require("@ai-sdk/provider-utils");
3642
- var import_ui_utils6 = require("@ai-sdk/ui-utils");
3750
+ var import_ui_utils7 = require("@ai-sdk/ui-utils");
3643
3751
 
3644
3752
  // core/util/merge-streams.ts
3645
3753
  function mergeStreams(stream1, stream2) {
@@ -3730,7 +3838,7 @@ function mergeStreams(stream1, stream2) {
3730
3838
  }
3731
3839
 
3732
3840
  // core/generate-text/run-tools-transformation.ts
3733
- var import_ui_utils5 = require("@ai-sdk/ui-utils");
3841
+ var import_ui_utils6 = require("@ai-sdk/ui-utils");
3734
3842
  function runToolsTransformation({
3735
3843
  tools,
3736
3844
  generatorStream,
@@ -3814,7 +3922,7 @@ function runToolsTransformation({
3814
3922
  });
3815
3923
  controller.enqueue(toolCall);
3816
3924
  if (tool2.execute != null) {
3817
- const toolExecutionId = (0, import_ui_utils5.generateId)();
3925
+ const toolExecutionId = (0, import_ui_utils6.generateId)();
3818
3926
  outstandingToolResults.add(toolExecutionId);
3819
3927
  recordSpan({
3820
3928
  name: "ai.toolCall",
@@ -4578,12 +4686,12 @@ var DefaultStreamTextResult = class {
4578
4686
  const chunkType = chunk.type;
4579
4687
  switch (chunkType) {
4580
4688
  case "text-delta": {
4581
- controller.enqueue((0, import_ui_utils6.formatDataStreamPart)("text", chunk.textDelta));
4689
+ controller.enqueue((0, import_ui_utils7.formatDataStreamPart)("text", chunk.textDelta));
4582
4690
  break;
4583
4691
  }
4584
4692
  case "tool-call-streaming-start": {
4585
4693
  controller.enqueue(
4586
- (0, import_ui_utils6.formatDataStreamPart)("tool_call_streaming_start", {
4694
+ (0, import_ui_utils7.formatDataStreamPart)("tool_call_streaming_start", {
4587
4695
  toolCallId: chunk.toolCallId,
4588
4696
  toolName: chunk.toolName
4589
4697
  })
@@ -4592,7 +4700,7 @@ var DefaultStreamTextResult = class {
4592
4700
  }
4593
4701
  case "tool-call-delta": {
4594
4702
  controller.enqueue(
4595
- (0, import_ui_utils6.formatDataStreamPart)("tool_call_delta", {
4703
+ (0, import_ui_utils7.formatDataStreamPart)("tool_call_delta", {
4596
4704
  toolCallId: chunk.toolCallId,
4597
4705
  argsTextDelta: chunk.argsTextDelta
4598
4706
  })
@@ -4601,7 +4709,7 @@ var DefaultStreamTextResult = class {
4601
4709
  }
4602
4710
  case "tool-call": {
4603
4711
  controller.enqueue(
4604
- (0, import_ui_utils6.formatDataStreamPart)("tool_call", {
4712
+ (0, import_ui_utils7.formatDataStreamPart)("tool_call", {
4605
4713
  toolCallId: chunk.toolCallId,
4606
4714
  toolName: chunk.toolName,
4607
4715
  args: chunk.args
@@ -4611,7 +4719,7 @@ var DefaultStreamTextResult = class {
4611
4719
  }
4612
4720
  case "tool-result": {
4613
4721
  controller.enqueue(
4614
- (0, import_ui_utils6.formatDataStreamPart)("tool_result", {
4722
+ (0, import_ui_utils7.formatDataStreamPart)("tool_result", {
4615
4723
  toolCallId: chunk.toolCallId,
4616
4724
  result: chunk.result
4617
4725
  })
@@ -4620,13 +4728,13 @@ var DefaultStreamTextResult = class {
4620
4728
  }
4621
4729
  case "error": {
4622
4730
  controller.enqueue(
4623
- (0, import_ui_utils6.formatDataStreamPart)("error", getErrorMessage3(chunk.error))
4731
+ (0, import_ui_utils7.formatDataStreamPart)("error", getErrorMessage3(chunk.error))
4624
4732
  );
4625
4733
  break;
4626
4734
  }
4627
4735
  case "step-finish": {
4628
4736
  controller.enqueue(
4629
- (0, import_ui_utils6.formatDataStreamPart)("finish_step", {
4737
+ (0, import_ui_utils7.formatDataStreamPart)("finish_step", {
4630
4738
  finishReason: chunk.finishReason,
4631
4739
  usage: sendUsage ? {
4632
4740
  promptTokens: chunk.usage.promptTokens,
@@ -4639,7 +4747,7 @@ var DefaultStreamTextResult = class {
4639
4747
  }
4640
4748
  case "finish": {
4641
4749
  controller.enqueue(
4642
- (0, import_ui_utils6.formatDataStreamPart)("finish_message", {
4750
+ (0, import_ui_utils7.formatDataStreamPart)("finish_message", {
4643
4751
  finishReason: chunk.finishReason,
4644
4752
  usage: sendUsage ? {
4645
4753
  promptTokens: chunk.usage.promptTokens,
@@ -4656,7 +4764,7 @@ var DefaultStreamTextResult = class {
4656
4764
  }
4657
4765
  }
4658
4766
  });
4659
- return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer).pipeThrough(new TextEncoderStream());
4767
+ return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer);
4660
4768
  }
4661
4769
  pipeDataStreamToResponse(response, {
4662
4770
  status,
@@ -4688,13 +4796,21 @@ var DefaultStreamTextResult = class {
4688
4796
  stream: this.textStream.pipeThrough(new TextEncoderStream())
4689
4797
  });
4690
4798
  }
4799
+ // TODO breaking change 5.0: remove pipeThrough(new TextEncoderStream())
4691
4800
  toDataStream(options) {
4692
4801
  const stream = this.toDataStreamInternal({
4693
4802
  getErrorMessage: options == null ? void 0 : options.getErrorMessage,
4694
4803
  sendUsage: options == null ? void 0 : options.sendUsage
4695
- });
4804
+ }).pipeThrough(new TextEncoderStream());
4696
4805
  return (options == null ? void 0 : options.data) ? mergeStreams(options == null ? void 0 : options.data.stream, stream) : stream;
4697
4806
  }
4807
+ mergeIntoDataStream(writer) {
4808
+ writer.merge(
4809
+ this.toDataStreamInternal({
4810
+ getErrorMessage: writer.onError
4811
+ })
4812
+ );
4813
+ }
4698
4814
  toDataStreamResponse({
4699
4815
  headers,
4700
4816
  status,
@@ -4733,7 +4849,7 @@ __export(output_exports, {
4733
4849
  text: () => text
4734
4850
  });
4735
4851
  var import_provider_utils10 = require("@ai-sdk/provider-utils");
4736
- var import_ui_utils7 = require("@ai-sdk/ui-utils");
4852
+ var import_ui_utils8 = require("@ai-sdk/ui-utils");
4737
4853
  var text = () => ({
4738
4854
  type: "text",
4739
4855
  responseFormat: () => ({ type: "text" }),
@@ -4747,7 +4863,7 @@ var text = () => ({
4747
4863
  var object = ({
4748
4864
  schema: inputSchema
4749
4865
  }) => {
4750
- const schema = (0, import_ui_utils7.asSchema)(inputSchema);
4866
+ const schema = (0, import_ui_utils8.asSchema)(inputSchema);
4751
4867
  return {
4752
4868
  type: "object",
4753
4869
  responseFormat: ({ model }) => ({
@@ -4948,7 +5064,7 @@ function magnitude(vector) {
4948
5064
  }
4949
5065
 
4950
5066
  // streams/assistant-response.ts
4951
- var import_ui_utils9 = require("@ai-sdk/ui-utils");
5067
+ var import_ui_utils10 = require("@ai-sdk/ui-utils");
4952
5068
  function AssistantResponse({ threadId, messageId }, process2) {
4953
5069
  const stream = new ReadableStream({
4954
5070
  async start(controller) {
@@ -4957,20 +5073,20 @@ function AssistantResponse({ threadId, messageId }, process2) {
4957
5073
  const sendMessage = (message) => {
4958
5074
  controller.enqueue(
4959
5075
  textEncoder.encode(
4960
- (0, import_ui_utils9.formatAssistantStreamPart)("assistant_message", message)
5076
+ (0, import_ui_utils10.formatAssistantStreamPart)("assistant_message", message)
4961
5077
  )
4962
5078
  );
4963
5079
  };
4964
5080
  const sendDataMessage = (message) => {
4965
5081
  controller.enqueue(
4966
5082
  textEncoder.encode(
4967
- (0, import_ui_utils9.formatAssistantStreamPart)("data_message", message)
5083
+ (0, import_ui_utils10.formatAssistantStreamPart)("data_message", message)
4968
5084
  )
4969
5085
  );
4970
5086
  };
4971
5087
  const sendError = (errorMessage) => {
4972
5088
  controller.enqueue(
4973
- textEncoder.encode((0, import_ui_utils9.formatAssistantStreamPart)("error", errorMessage))
5089
+ textEncoder.encode((0, import_ui_utils10.formatAssistantStreamPart)("error", errorMessage))
4974
5090
  );
4975
5091
  };
4976
5092
  const forwardStream = async (stream2) => {
@@ -4981,7 +5097,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
4981
5097
  case "thread.message.created": {
4982
5098
  controller.enqueue(
4983
5099
  textEncoder.encode(
4984
- (0, import_ui_utils9.formatAssistantStreamPart)("assistant_message", {
5100
+ (0, import_ui_utils10.formatAssistantStreamPart)("assistant_message", {
4985
5101
  id: value.data.id,
4986
5102
  role: "assistant",
4987
5103
  content: [{ type: "text", text: { value: "" } }]
@@ -4995,7 +5111,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
4995
5111
  if ((content == null ? void 0 : content.type) === "text" && ((_b = content.text) == null ? void 0 : _b.value) != null) {
4996
5112
  controller.enqueue(
4997
5113
  textEncoder.encode(
4998
- (0, import_ui_utils9.formatAssistantStreamPart)("text", content.text.value)
5114
+ (0, import_ui_utils10.formatAssistantStreamPart)("text", content.text.value)
4999
5115
  )
5000
5116
  );
5001
5117
  }
@@ -5012,7 +5128,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5012
5128
  };
5013
5129
  controller.enqueue(
5014
5130
  textEncoder.encode(
5015
- (0, import_ui_utils9.formatAssistantStreamPart)("assistant_control_data", {
5131
+ (0, import_ui_utils10.formatAssistantStreamPart)("assistant_control_data", {
5016
5132
  threadId,
5017
5133
  messageId
5018
5134
  })
@@ -5046,9 +5162,11 @@ function AssistantResponse({ threadId, messageId }, process2) {
5046
5162
  // streams/langchain-adapter.ts
5047
5163
  var langchain_adapter_exports = {};
5048
5164
  __export(langchain_adapter_exports, {
5165
+ mergeIntoDataStream: () => mergeIntoDataStream,
5049
5166
  toDataStream: () => toDataStream,
5050
5167
  toDataStreamResponse: () => toDataStreamResponse
5051
5168
  });
5169
+ var import_ui_utils11 = require("@ai-sdk/ui-utils");
5052
5170
 
5053
5171
  // streams/stream-callbacks.ts
5054
5172
  function createCallbacksTransformer(callbacks = {}) {
@@ -5079,87 +5197,8 @@ function createCallbacksTransformer(callbacks = {}) {
5079
5197
  });
5080
5198
  }
5081
5199
 
5082
- // streams/stream-data.ts
5083
- var import_ui_utils10 = require("@ai-sdk/ui-utils");
5084
-
5085
- // util/constants.ts
5086
- var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
5087
-
5088
- // streams/stream-data.ts
5089
- var StreamData = class {
5090
- constructor() {
5091
- this.encoder = new TextEncoder();
5092
- this.controller = null;
5093
- this.isClosed = false;
5094
- this.warningTimeout = null;
5095
- const self = this;
5096
- this.stream = new ReadableStream({
5097
- start: async (controller) => {
5098
- self.controller = controller;
5099
- if (process.env.NODE_ENV === "development") {
5100
- self.warningTimeout = setTimeout(() => {
5101
- console.warn(
5102
- "The data stream is hanging. Did you forget to close it with `data.close()`?"
5103
- );
5104
- }, HANGING_STREAM_WARNING_TIME_MS);
5105
- }
5106
- },
5107
- pull: (controller) => {
5108
- },
5109
- cancel: (reason) => {
5110
- this.isClosed = true;
5111
- }
5112
- });
5113
- }
5114
- async close() {
5115
- if (this.isClosed) {
5116
- throw new Error("Data Stream has already been closed.");
5117
- }
5118
- if (!this.controller) {
5119
- throw new Error("Stream controller is not initialized.");
5120
- }
5121
- this.controller.close();
5122
- this.isClosed = true;
5123
- if (this.warningTimeout) {
5124
- clearTimeout(this.warningTimeout);
5125
- }
5126
- }
5127
- append(value) {
5128
- if (this.isClosed) {
5129
- throw new Error("Data Stream has already been closed.");
5130
- }
5131
- if (!this.controller) {
5132
- throw new Error("Stream controller is not initialized.");
5133
- }
5134
- this.controller.enqueue(
5135
- this.encoder.encode((0, import_ui_utils10.formatDataStreamPart)("data", [value]))
5136
- );
5137
- }
5138
- appendMessageAnnotation(value) {
5139
- if (this.isClosed) {
5140
- throw new Error("Data Stream has already been closed.");
5141
- }
5142
- if (!this.controller) {
5143
- throw new Error("Stream controller is not initialized.");
5144
- }
5145
- this.controller.enqueue(
5146
- this.encoder.encode((0, import_ui_utils10.formatDataStreamPart)("message_annotations", [value]))
5147
- );
5148
- }
5149
- };
5150
- function createStreamDataTransformer() {
5151
- const encoder = new TextEncoder();
5152
- const decoder = new TextDecoder();
5153
- return new TransformStream({
5154
- transform: async (chunk, controller) => {
5155
- const message = decoder.decode(chunk);
5156
- controller.enqueue(encoder.encode((0, import_ui_utils10.formatDataStreamPart)("text", message)));
5157
- }
5158
- });
5159
- }
5160
-
5161
5200
  // streams/langchain-adapter.ts
5162
- function toDataStream(stream, callbacks) {
5201
+ function toDataStreamInternal(stream, callbacks) {
5163
5202
  return stream.pipeThrough(
5164
5203
  new TransformStream({
5165
5204
  transform: async (value, controller) => {
@@ -5180,11 +5219,25 @@ function toDataStream(stream, callbacks) {
5180
5219
  forwardAIMessageChunk(value, controller);
5181
5220
  }
5182
5221
  })
5183
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5222
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
5223
+ new TransformStream({
5224
+ transform: async (chunk, controller) => {
5225
+ controller.enqueue((0, import_ui_utils11.formatDataStreamPart)("text", chunk));
5226
+ }
5227
+ })
5228
+ );
5229
+ }
5230
+ function toDataStream(stream, callbacks) {
5231
+ return toDataStreamInternal(stream, callbacks).pipeThrough(
5232
+ new TextEncoderStream()
5233
+ );
5184
5234
  }
5185
5235
  function toDataStreamResponse(stream, options) {
5186
5236
  var _a11;
5187
- const dataStream = toDataStream(stream, options == null ? void 0 : options.callbacks);
5237
+ const dataStream = toDataStreamInternal(
5238
+ stream,
5239
+ options == null ? void 0 : options.callbacks
5240
+ ).pipeThrough(new TextEncoderStream());
5188
5241
  const data = options == null ? void 0 : options.data;
5189
5242
  const init = options == null ? void 0 : options.init;
5190
5243
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
@@ -5197,6 +5250,9 @@ function toDataStreamResponse(stream, options) {
5197
5250
  })
5198
5251
  });
5199
5252
  }
5253
+ function mergeIntoDataStream(stream, options) {
5254
+ options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
5255
+ }
5200
5256
  function forwardAIMessageChunk(chunk, controller) {
5201
5257
  if (typeof chunk.content === "string") {
5202
5258
  controller.enqueue(chunk.content);
@@ -5213,11 +5269,13 @@ function forwardAIMessageChunk(chunk, controller) {
5213
5269
  // streams/llamaindex-adapter.ts
5214
5270
  var llamaindex_adapter_exports = {};
5215
5271
  __export(llamaindex_adapter_exports, {
5272
+ mergeIntoDataStream: () => mergeIntoDataStream2,
5216
5273
  toDataStream: () => toDataStream2,
5217
5274
  toDataStreamResponse: () => toDataStreamResponse2
5218
5275
  });
5219
5276
  var import_provider_utils11 = require("@ai-sdk/provider-utils");
5220
- function toDataStream2(stream, callbacks) {
5277
+ var import_ui_utils12 = require("@ai-sdk/ui-utils");
5278
+ function toDataStreamInternal2(stream, callbacks) {
5221
5279
  const trimStart = trimStartOfStream();
5222
5280
  return (0, import_provider_utils11.convertAsyncIteratorToReadableStream)(stream[Symbol.asyncIterator]()).pipeThrough(
5223
5281
  new TransformStream({
@@ -5225,12 +5283,25 @@ function toDataStream2(stream, callbacks) {
5225
5283
  controller.enqueue(trimStart(message.delta));
5226
5284
  }
5227
5285
  })
5228
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5286
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
5287
+ new TransformStream({
5288
+ transform: async (chunk, controller) => {
5289
+ controller.enqueue((0, import_ui_utils12.formatDataStreamPart)("text", chunk));
5290
+ }
5291
+ })
5292
+ );
5293
+ }
5294
+ function toDataStream2(stream, callbacks) {
5295
+ return toDataStreamInternal2(stream, callbacks).pipeThrough(
5296
+ new TextEncoderStream()
5297
+ );
5229
5298
  }
5230
5299
  function toDataStreamResponse2(stream, options = {}) {
5231
5300
  var _a11;
5232
5301
  const { init, data, callbacks } = options;
5233
- const dataStream = toDataStream2(stream, callbacks);
5302
+ const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
5303
+ new TextEncoderStream()
5304
+ );
5234
5305
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
5235
5306
  return new Response(responseStream, {
5236
5307
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
@@ -5241,6 +5312,9 @@ function toDataStreamResponse2(stream, options = {}) {
5241
5312
  })
5242
5313
  });
5243
5314
  }
5315
+ function mergeIntoDataStream2(stream, options) {
5316
+ options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
5317
+ }
5244
5318
  function trimStartOfStream() {
5245
5319
  let isStreamStart = true;
5246
5320
  return (text2) => {
@@ -5252,6 +5326,75 @@ function trimStartOfStream() {
5252
5326
  return text2;
5253
5327
  };
5254
5328
  }
5329
+
5330
+ // streams/stream-data.ts
5331
+ var import_ui_utils13 = require("@ai-sdk/ui-utils");
5332
+
5333
+ // util/constants.ts
5334
+ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
5335
+
5336
+ // streams/stream-data.ts
5337
+ var StreamData = class {
5338
+ constructor() {
5339
+ this.encoder = new TextEncoder();
5340
+ this.controller = null;
5341
+ this.isClosed = false;
5342
+ this.warningTimeout = null;
5343
+ const self = this;
5344
+ this.stream = new ReadableStream({
5345
+ start: async (controller) => {
5346
+ self.controller = controller;
5347
+ if (process.env.NODE_ENV === "development") {
5348
+ self.warningTimeout = setTimeout(() => {
5349
+ console.warn(
5350
+ "The data stream is hanging. Did you forget to close it with `data.close()`?"
5351
+ );
5352
+ }, HANGING_STREAM_WARNING_TIME_MS);
5353
+ }
5354
+ },
5355
+ pull: (controller) => {
5356
+ },
5357
+ cancel: (reason) => {
5358
+ this.isClosed = true;
5359
+ }
5360
+ });
5361
+ }
5362
+ async close() {
5363
+ if (this.isClosed) {
5364
+ throw new Error("Data Stream has already been closed.");
5365
+ }
5366
+ if (!this.controller) {
5367
+ throw new Error("Stream controller is not initialized.");
5368
+ }
5369
+ this.controller.close();
5370
+ this.isClosed = true;
5371
+ if (this.warningTimeout) {
5372
+ clearTimeout(this.warningTimeout);
5373
+ }
5374
+ }
5375
+ append(value) {
5376
+ if (this.isClosed) {
5377
+ throw new Error("Data Stream has already been closed.");
5378
+ }
5379
+ if (!this.controller) {
5380
+ throw new Error("Stream controller is not initialized.");
5381
+ }
5382
+ this.controller.enqueue(
5383
+ this.encoder.encode((0, import_ui_utils13.formatDataStreamPart)("data", [value]))
5384
+ );
5385
+ }
5386
+ appendMessageAnnotation(value) {
5387
+ if (this.isClosed) {
5388
+ throw new Error("Data Stream has already been closed.");
5389
+ }
5390
+ if (!this.controller) {
5391
+ throw new Error("Stream controller is not initialized.");
5392
+ }
5393
+ this.controller.enqueue(
5394
+ this.encoder.encode((0, import_ui_utils13.formatDataStreamPart)("message_annotations", [value]))
5395
+ );
5396
+ }
5397
+ };
5255
5398
  // Annotate the CommonJS export names for ESM import in node:
5256
5399
  0 && (module.exports = {
5257
5400
  AISDKError,
@@ -5282,7 +5425,8 @@ function trimStartOfStream() {
5282
5425
  UnsupportedFunctionalityError,
5283
5426
  convertToCoreMessages,
5284
5427
  cosineSimilarity,
5285
- createStreamDataTransformer,
5428
+ createDataStream,
5429
+ createDataStreamResponse,
5286
5430
  embed,
5287
5431
  embedMany,
5288
5432
  experimental_createProviderRegistry,
@@ -5296,6 +5440,7 @@ function trimStartOfStream() {
5296
5440
  jsonSchema,
5297
5441
  parseAssistantStreamPart,
5298
5442
  parseDataStreamPart,
5443
+ pipeDataStreamToResponse,
5299
5444
  processDataStream,
5300
5445
  processTextStream,
5301
5446
  streamObject,