ai 4.0.0-canary.1 → 4.0.0-canary.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
@@ -21,7 +21,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var streams_exports = {};
22
22
  __export(streams_exports, {
23
23
  AISDKError: () => import_provider13.AISDKError,
24
- AIStream: () => AIStream,
25
24
  APICallError: () => import_provider13.APICallError,
26
25
  AssistantResponse: () => AssistantResponse,
27
26
  DownloadError: () => DownloadError,
@@ -43,48 +42,35 @@ __export(streams_exports, {
43
42
  NoSuchProviderError: () => NoSuchProviderError,
44
43
  NoSuchToolError: () => NoSuchToolError,
45
44
  RetryError: () => RetryError,
46
- StreamData: () => StreamData2,
47
- StreamingTextResponse: () => StreamingTextResponse,
45
+ StreamData: () => StreamData,
48
46
  TypeValidationError: () => import_provider13.TypeValidationError,
49
47
  UnsupportedFunctionalityError: () => import_provider13.UnsupportedFunctionalityError,
50
48
  convertToCoreMessages: () => convertToCoreMessages,
51
49
  cosineSimilarity: () => cosineSimilarity,
52
- createCallbacksTransformer: () => createCallbacksTransformer,
53
- createEventStreamTransformer: () => createEventStreamTransformer,
54
50
  createStreamDataTransformer: () => createStreamDataTransformer,
55
51
  embed: () => embed,
56
52
  embedMany: () => embedMany,
57
- experimental_AssistantResponse: () => experimental_AssistantResponse,
58
- experimental_StreamData: () => experimental_StreamData,
59
- experimental_createModelRegistry: () => experimental_createModelRegistry,
60
53
  experimental_createProviderRegistry: () => experimental_createProviderRegistry,
61
54
  experimental_customProvider: () => experimental_customProvider,
62
- experimental_generateObject: () => experimental_generateObject,
63
- experimental_generateText: () => experimental_generateText,
64
- experimental_streamObject: () => experimental_streamObject,
65
- experimental_streamText: () => experimental_streamText,
66
55
  experimental_wrapLanguageModel: () => experimental_wrapLanguageModel,
67
- formatStreamPart: () => import_ui_utils9.formatStreamPart,
68
- generateId: () => generateId2,
56
+ formatStreamPart: () => import_ui_utils10.formatStreamPart,
57
+ generateId: () => import_provider_utils11.generateId,
69
58
  generateObject: () => generateObject,
70
59
  generateText: () => generateText,
71
- jsonSchema: () => import_ui_utils6.jsonSchema,
72
- parseStreamPart: () => import_ui_utils9.parseStreamPart,
73
- processDataProtocolResponse: () => import_ui_utils9.processDataProtocolResponse,
74
- readDataStream: () => import_ui_utils9.readDataStream,
75
- readableFromAsyncIterable: () => readableFromAsyncIterable,
60
+ jsonSchema: () => import_ui_utils7.jsonSchema,
61
+ parseStreamPart: () => import_ui_utils10.parseStreamPart,
62
+ processDataProtocolResponse: () => import_ui_utils10.processDataProtocolResponse,
63
+ readDataStream: () => import_ui_utils10.readDataStream,
76
64
  streamObject: () => streamObject,
77
65
  streamText: () => streamText,
78
- streamToResponse: () => streamToResponse,
79
- tool: () => tool,
80
- trimStartOfStreamHelper: () => trimStartOfStreamHelper
66
+ tool: () => tool
81
67
  });
82
68
  module.exports = __toCommonJS(streams_exports);
83
- var import_ui_utils9 = require("@ai-sdk/ui-utils");
84
- var import_provider_utils10 = require("@ai-sdk/provider-utils");
69
+ var import_ui_utils10 = require("@ai-sdk/ui-utils");
70
+ var import_provider_utils11 = require("@ai-sdk/provider-utils");
85
71
 
86
72
  // core/index.ts
87
- var import_ui_utils6 = require("@ai-sdk/ui-utils");
73
+ var import_ui_utils7 = require("@ai-sdk/ui-utils");
88
74
 
89
75
  // util/retry-with-exponential-backoff.ts
90
76
  var import_provider2 = require("@ai-sdk/provider");
@@ -116,24 +102,6 @@ var RetryError = class extends import_provider.AISDKError {
116
102
  static isInstance(error) {
117
103
  return import_provider.AISDKError.hasMarker(error, marker);
118
104
  }
119
- /**
120
- * @deprecated use `isInstance` instead
121
- */
122
- static isRetryError(error) {
123
- return error instanceof Error && error.name === name && typeof error.reason === "string" && Array.isArray(error.errors);
124
- }
125
- /**
126
- * @deprecated Do not use this method. It will be removed in the next major version.
127
- */
128
- toJSON() {
129
- return {
130
- name: this.name,
131
- message: this.message,
132
- reason: this.reason,
133
- lastError: this.lastError,
134
- errors: this.errors
135
- };
136
- }
137
105
  };
138
106
  _a = symbol;
139
107
 
@@ -171,7 +139,7 @@ async function _retryWithExponentialBackoff(f, {
171
139
  errors: newErrors
172
140
  });
173
141
  }
174
- if (error instanceof Error && import_provider2.APICallError.isAPICallError(error) && error.isRetryable === true && tryNumber <= maxRetries) {
142
+ if (error instanceof Error && import_provider2.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
175
143
  await delay(delayInMs);
176
144
  return _retryWithExponentialBackoff(
177
145
  f,
@@ -686,25 +654,6 @@ var DownloadError = class extends import_provider3.AISDKError {
686
654
  static isInstance(error) {
687
655
  return import_provider3.AISDKError.hasMarker(error, marker2);
688
656
  }
689
- /**
690
- * @deprecated use `isInstance` instead
691
- */
692
- static isDownloadError(error) {
693
- return error instanceof Error && error.name === name2 && typeof error.url === "string" && (error.statusCode == null || typeof error.statusCode === "number") && (error.statusText == null || typeof error.statusText === "string");
694
- }
695
- /**
696
- * @deprecated Do not use this method. It will be removed in the next major version.
697
- */
698
- toJSON() {
699
- return {
700
- name: this.name,
701
- message: this.message,
702
- url: this.url,
703
- statusCode: this.statusCode,
704
- statusText: this.statusText,
705
- cause: this.cause
706
- };
707
- }
708
657
  };
709
658
  _a2 = symbol2;
710
659
 
@@ -774,24 +723,6 @@ var InvalidDataContentError = class extends import_provider4.AISDKError {
774
723
  static isInstance(error) {
775
724
  return import_provider4.AISDKError.hasMarker(error, marker3);
776
725
  }
777
- /**
778
- * @deprecated use `isInstance` instead
779
- */
780
- static isInvalidDataContentError(error) {
781
- return error instanceof Error && error.name === name3 && error.content != null;
782
- }
783
- /**
784
- * @deprecated Do not use this method. It will be removed in the next major version.
785
- */
786
- toJSON() {
787
- return {
788
- name: this.name,
789
- message: this.message,
790
- stack: this.stack,
791
- cause: this.cause,
792
- content: this.content
793
- };
794
- }
795
726
  };
796
727
  _a3 = symbol3;
797
728
 
@@ -865,23 +796,6 @@ var InvalidMessageRoleError = class extends import_provider5.AISDKError {
865
796
  static isInstance(error) {
866
797
  return import_provider5.AISDKError.hasMarker(error, marker4);
867
798
  }
868
- /**
869
- * @deprecated use `isInstance` instead
870
- */
871
- static isInvalidMessageRoleError(error) {
872
- return error instanceof Error && error.name === name4 && typeof error.role === "string";
873
- }
874
- /**
875
- * @deprecated Do not use this method. It will be removed in the next major version.
876
- */
877
- toJSON() {
878
- return {
879
- name: this.name,
880
- message: this.message,
881
- stack: this.stack,
882
- role: this.role
883
- };
884
- }
885
799
  };
886
800
  _a4 = symbol4;
887
801
 
@@ -1109,21 +1023,6 @@ var InvalidArgumentError = class extends import_provider6.AISDKError {
1109
1023
  static isInstance(error) {
1110
1024
  return import_provider6.AISDKError.hasMarker(error, marker5);
1111
1025
  }
1112
- /**
1113
- * @deprecated use `isInstance` instead
1114
- */
1115
- static isInvalidArgumentError(error) {
1116
- return error instanceof Error && error.name === name5 && typeof error.parameter === "string" && typeof error.value === "string";
1117
- }
1118
- toJSON() {
1119
- return {
1120
- name: this.name,
1121
- message: this.message,
1122
- stack: this.stack,
1123
- parameter: this.parameter,
1124
- value: this.value
1125
- };
1126
- }
1127
1026
  };
1128
1027
  _a5 = symbol5;
1129
1028
 
@@ -1556,9 +1455,7 @@ function convertToCoreMessages(messages, options) {
1556
1455
  });
1557
1456
  break;
1558
1457
  }
1559
- case "function":
1560
- case "data":
1561
- case "tool": {
1458
+ case "data": {
1562
1459
  break;
1563
1460
  }
1564
1461
  default: {
@@ -1646,28 +1543,30 @@ function standardizePrompt({
1646
1543
  }
1647
1544
 
1648
1545
  // core/types/usage.ts
1649
- function calculateLanguageModelUsage(usage) {
1546
+ function calculateLanguageModelUsage({
1547
+ promptTokens,
1548
+ completionTokens
1549
+ }) {
1650
1550
  return {
1651
- promptTokens: usage.promptTokens,
1652
- completionTokens: usage.completionTokens,
1653
- totalTokens: usage.promptTokens + usage.completionTokens
1551
+ promptTokens,
1552
+ completionTokens,
1553
+ totalTokens: promptTokens + completionTokens
1654
1554
  };
1655
1555
  }
1656
1556
 
1657
1557
  // core/util/prepare-response-headers.ts
1658
- function prepareResponseHeaders(init, {
1558
+ function prepareResponseHeaders(headers, {
1659
1559
  contentType,
1660
1560
  dataStreamVersion
1661
1561
  }) {
1662
- var _a11;
1663
- const headers = new Headers((_a11 = init == null ? void 0 : init.headers) != null ? _a11 : {});
1664
- if (!headers.has("Content-Type")) {
1665
- headers.set("Content-Type", contentType);
1562
+ const responseHeaders = new Headers(headers != null ? headers : {});
1563
+ if (!responseHeaders.has("Content-Type")) {
1564
+ responseHeaders.set("Content-Type", contentType);
1666
1565
  }
1667
1566
  if (dataStreamVersion !== void 0) {
1668
- headers.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
1567
+ responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
1669
1568
  }
1670
- return headers;
1569
+ return responseHeaders;
1671
1570
  }
1672
1571
 
1673
1572
  // core/generate-object/inject-json-instruction.ts
@@ -1705,23 +1604,6 @@ var NoObjectGeneratedError = class extends import_provider9.AISDKError {
1705
1604
  static isInstance(error) {
1706
1605
  return import_provider9.AISDKError.hasMarker(error, marker7);
1707
1606
  }
1708
- /**
1709
- * @deprecated Use isInstance instead.
1710
- */
1711
- static isNoObjectGeneratedError(error) {
1712
- return error instanceof Error && error.name === name7;
1713
- }
1714
- /**
1715
- * @deprecated Do not use this method. It will be removed in the next major version.
1716
- */
1717
- toJSON() {
1718
- return {
1719
- name: this.name,
1720
- cause: this.cause,
1721
- message: this.message,
1722
- stack: this.stack
1723
- };
1724
- }
1725
1607
  };
1726
1608
  _a7 = symbol7;
1727
1609
 
@@ -2253,9 +2135,6 @@ async function generateObject({
2253
2135
  "ai.response.timestamp": responseData.timestamp.toISOString(),
2254
2136
  "ai.usage.promptTokens": result2.usage.promptTokens,
2255
2137
  "ai.usage.completionTokens": result2.usage.completionTokens,
2256
- // deprecated:
2257
- "ai.finishReason": result2.finishReason,
2258
- "ai.result.object": { output: () => result2.text },
2259
2138
  // standardized gen-ai llm span attributes:
2260
2139
  "gen_ai.response.finish_reasons": [result2.finishReason],
2261
2140
  "gen_ai.response.id": responseData.id,
@@ -2360,9 +2239,6 @@ async function generateObject({
2360
2239
  "ai.response.timestamp": responseData.timestamp.toISOString(),
2361
2240
  "ai.usage.promptTokens": result2.usage.promptTokens,
2362
2241
  "ai.usage.completionTokens": result2.usage.completionTokens,
2363
- // deprecated:
2364
- "ai.finishReason": result2.finishReason,
2365
- "ai.result.object": { output: () => objectText },
2366
2242
  // standardized gen-ai llm span attributes:
2367
2243
  "gen_ai.response.finish_reasons": [result2.finishReason],
2368
2244
  "gen_ai.response.id": responseData.id,
@@ -2416,12 +2292,7 @@ async function generateObject({
2416
2292
  output: () => JSON.stringify(validationResult.value)
2417
2293
  },
2418
2294
  "ai.usage.promptTokens": usage.promptTokens,
2419
- "ai.usage.completionTokens": usage.completionTokens,
2420
- // deprecated:
2421
- "ai.finishReason": finishReason,
2422
- "ai.result.object": {
2423
- output: () => JSON.stringify(validationResult.value)
2424
- }
2295
+ "ai.usage.completionTokens": usage.completionTokens
2425
2296
  }
2426
2297
  })
2427
2298
  );
@@ -2450,22 +2321,18 @@ var DefaultGenerateObjectResult = class {
2450
2321
  this.experimental_providerMetadata = options.providerMetadata;
2451
2322
  this.response = options.response;
2452
2323
  this.request = options.request;
2453
- this.rawResponse = {
2454
- headers: options.response.headers
2455
- };
2456
2324
  this.logprobs = options.logprobs;
2457
2325
  }
2458
2326
  toJsonResponse(init) {
2459
2327
  var _a11;
2460
2328
  return new Response(JSON.stringify(this.object), {
2461
2329
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
2462
- headers: prepareResponseHeaders(init, {
2330
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
2463
2331
  contentType: "application/json; charset=utf-8"
2464
2332
  })
2465
2333
  });
2466
2334
  }
2467
2335
  };
2468
- var experimental_generateObject = generateObject;
2469
2336
 
2470
2337
  // core/generate-object/stream-object.ts
2471
2338
  var import_provider_utils6 = require("@ai-sdk/provider-utils");
@@ -2531,23 +2398,23 @@ function now() {
2531
2398
  }
2532
2399
 
2533
2400
  // core/util/prepare-outgoing-http-headers.ts
2534
- function prepareOutgoingHttpHeaders(init, {
2401
+ function prepareOutgoingHttpHeaders(headers, {
2535
2402
  contentType,
2536
2403
  dataStreamVersion
2537
2404
  }) {
2538
- const headers = {};
2539
- if ((init == null ? void 0 : init.headers) != null) {
2540
- for (const [key, value] of Object.entries(init.headers)) {
2541
- headers[key] = value;
2405
+ const outgoingHeaders = {};
2406
+ if (headers != null) {
2407
+ for (const [key, value] of Object.entries(headers)) {
2408
+ outgoingHeaders[key] = value;
2542
2409
  }
2543
2410
  }
2544
- if (headers["Content-Type"] == null) {
2545
- headers["Content-Type"] = contentType;
2411
+ if (outgoingHeaders["Content-Type"] == null) {
2412
+ outgoingHeaders["Content-Type"] = contentType;
2546
2413
  }
2547
2414
  if (dataStreamVersion !== void 0) {
2548
- headers["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
2415
+ outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
2549
2416
  }
2550
- return headers;
2417
+ return outgoingHeaders;
2551
2418
  }
2552
2419
 
2553
2420
  // core/util/write-to-server-response.ts
@@ -2828,7 +2695,6 @@ var DefaultStreamObjectResult = class {
2828
2695
  generateId: generateId3
2829
2696
  }) {
2830
2697
  this.warnings = warnings;
2831
- this.rawResponse = rawResponse;
2832
2698
  this.outputStrategy = outputStrategy;
2833
2699
  this.request = Promise.resolve(request);
2834
2700
  this.objectPromise = new DelayedPromise();
@@ -2961,9 +2827,6 @@ var DefaultStreamObjectResult = class {
2961
2827
  "ai.response.timestamp": response.timestamp.toISOString(),
2962
2828
  "ai.usage.promptTokens": finalUsage.promptTokens,
2963
2829
  "ai.usage.completionTokens": finalUsage.completionTokens,
2964
- // deprecated
2965
- "ai.finishReason": finishReason,
2966
- "ai.result.object": { output: () => JSON.stringify(object) },
2967
2830
  // standardized gen-ai llm span attributes:
2968
2831
  "gen_ai.response.finish_reasons": [finishReason],
2969
2832
  "gen_ai.response.id": response.id,
@@ -2982,9 +2845,7 @@ var DefaultStreamObjectResult = class {
2982
2845
  "ai.usage.completionTokens": finalUsage.completionTokens,
2983
2846
  "ai.response.object": {
2984
2847
  output: () => JSON.stringify(object)
2985
- },
2986
- // deprecated
2987
- "ai.result.object": { output: () => JSON.stringify(object) }
2848
+ }
2988
2849
  }
2989
2850
  })
2990
2851
  );
@@ -2992,7 +2853,6 @@ var DefaultStreamObjectResult = class {
2992
2853
  usage: finalUsage,
2993
2854
  object,
2994
2855
  error,
2995
- rawResponse,
2996
2856
  response: {
2997
2857
  ...response,
2998
2858
  headers: rawResponse == null ? void 0 : rawResponse.headers
@@ -3069,7 +2929,7 @@ var DefaultStreamObjectResult = class {
3069
2929
  response,
3070
2930
  status: init == null ? void 0 : init.status,
3071
2931
  statusText: init == null ? void 0 : init.statusText,
3072
- headers: prepareOutgoingHttpHeaders(init, {
2932
+ headers: prepareOutgoingHttpHeaders(init == null ? void 0 : init.headers, {
3073
2933
  contentType: "text/plain; charset=utf-8"
3074
2934
  }),
3075
2935
  stream: this.textStream.pipeThrough(new TextEncoderStream())
@@ -3079,13 +2939,12 @@ var DefaultStreamObjectResult = class {
3079
2939
  var _a11;
3080
2940
  return new Response(this.textStream.pipeThrough(new TextEncoderStream()), {
3081
2941
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
3082
- headers: prepareResponseHeaders(init, {
2942
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3083
2943
  contentType: "text/plain; charset=utf-8"
3084
2944
  })
3085
2945
  });
3086
2946
  }
3087
2947
  };
3088
- var experimental_streamObject = streamObject;
3089
2948
 
3090
2949
  // core/generate-text/generate-text.ts
3091
2950
  var import_provider_utils8 = require("@ai-sdk/provider-utils");
@@ -3116,25 +2975,6 @@ var InvalidToolArgumentsError = class extends import_provider11.AISDKError {
3116
2975
  static isInstance(error) {
3117
2976
  return import_provider11.AISDKError.hasMarker(error, marker8);
3118
2977
  }
3119
- /**
3120
- * @deprecated use `isInstance` instead
3121
- */
3122
- static isInvalidToolArgumentsError(error) {
3123
- return error instanceof Error && error.name === name8 && typeof error.toolName === "string" && typeof error.toolArgs === "string";
3124
- }
3125
- /**
3126
- * @deprecated Do not use this method. It will be removed in the next major version.
3127
- */
3128
- toJSON() {
3129
- return {
3130
- name: this.name,
3131
- message: this.message,
3132
- cause: this.cause,
3133
- stack: this.stack,
3134
- toolName: this.toolName,
3135
- toolArgs: this.toolArgs
3136
- };
3137
- }
3138
2978
  };
3139
2979
  _a8 = symbol8;
3140
2980
 
@@ -3158,24 +2998,6 @@ var NoSuchToolError = class extends import_provider12.AISDKError {
3158
2998
  static isInstance(error) {
3159
2999
  return import_provider12.AISDKError.hasMarker(error, marker9);
3160
3000
  }
3161
- /**
3162
- * @deprecated use `isInstance` instead
3163
- */
3164
- static isNoSuchToolError(error) {
3165
- return error instanceof Error && error.name === name9 && "toolName" in error && error.toolName != void 0 && typeof error.name === "string";
3166
- }
3167
- /**
3168
- * @deprecated Do not use this method. It will be removed in the next major version.
3169
- */
3170
- toJSON() {
3171
- return {
3172
- name: this.name,
3173
- message: this.message,
3174
- stack: this.stack,
3175
- toolName: this.toolName,
3176
- availableTools: this.availableTools
3177
- };
3178
- }
3179
3001
  };
3180
3002
  _a9 = symbol9;
3181
3003
 
@@ -3328,11 +3150,8 @@ async function generateText({
3328
3150
  maxRetries,
3329
3151
  abortSignal,
3330
3152
  headers,
3331
- maxAutomaticRoundtrips = 0,
3332
- maxToolRoundtrips = maxAutomaticRoundtrips,
3333
- maxSteps = maxToolRoundtrips != null ? maxToolRoundtrips + 1 : 1,
3334
- experimental_continuationSteps,
3335
- experimental_continueSteps: continueSteps = experimental_continuationSteps != null ? experimental_continuationSteps : false,
3153
+ maxSteps = 1,
3154
+ experimental_continueSteps: continueSteps = false,
3336
3155
  experimental_telemetry: telemetry,
3337
3156
  experimental_providerMetadata: providerMetadata,
3338
3157
  experimental_activeTools: activeTools,
@@ -3484,14 +3303,6 @@ async function generateText({
3484
3303
  "ai.response.timestamp": responseData.timestamp.toISOString(),
3485
3304
  "ai.usage.promptTokens": result.usage.promptTokens,
3486
3305
  "ai.usage.completionTokens": result.usage.completionTokens,
3487
- // deprecated:
3488
- "ai.finishReason": result.finishReason,
3489
- "ai.result.text": {
3490
- output: () => result.text
3491
- },
3492
- "ai.result.toolCalls": {
3493
- output: () => JSON.stringify(result.toolCalls)
3494
- },
3495
3306
  // standardized gen-ai llm span attributes:
3496
3307
  "gen_ai.response.finish_reasons": [result.finishReason],
3497
3308
  "gen_ai.response.id": responseData.id,
@@ -3594,15 +3405,7 @@ async function generateText({
3594
3405
  output: () => JSON.stringify(currentModelResponse.toolCalls)
3595
3406
  },
3596
3407
  "ai.usage.promptTokens": currentModelResponse.usage.promptTokens,
3597
- "ai.usage.completionTokens": currentModelResponse.usage.completionTokens,
3598
- // deprecated:
3599
- "ai.finishReason": currentModelResponse.finishReason,
3600
- "ai.result.text": {
3601
- output: () => currentModelResponse.text
3602
- },
3603
- "ai.result.toolCalls": {
3604
- output: () => JSON.stringify(currentModelResponse.toolCalls)
3605
- }
3408
+ "ai.usage.completionTokens": currentModelResponse.usage.completionTokens
3606
3409
  }
3607
3410
  })
3608
3411
  );
@@ -3620,7 +3423,6 @@ async function generateText({
3620
3423
  messages: responseMessages
3621
3424
  },
3622
3425
  logprobs: currentModelResponse.logprobs,
3623
- responseMessages,
3624
3426
  steps,
3625
3427
  providerMetadata: currentModelResponse.providerMetadata
3626
3428
  });
@@ -3697,20 +3499,15 @@ var DefaultGenerateTextResult = class {
3697
3499
  this.warnings = options.warnings;
3698
3500
  this.request = options.request;
3699
3501
  this.response = options.response;
3700
- this.responseMessages = options.responseMessages;
3701
- this.roundtrips = options.steps;
3702
3502
  this.steps = options.steps;
3703
3503
  this.experimental_providerMetadata = options.providerMetadata;
3704
- this.rawResponse = {
3705
- headers: options.response.headers
3706
- };
3707
3504
  this.logprobs = options.logprobs;
3708
3505
  }
3709
3506
  };
3710
- var experimental_generateText = generateText;
3711
3507
 
3712
3508
  // core/generate-text/stream-text.ts
3713
3509
  var import_provider_utils9 = require("@ai-sdk/provider-utils");
3510
+ var import_ui_utils6 = require("@ai-sdk/ui-utils");
3714
3511
 
3715
3512
  // core/util/create-stitchable-stream.ts
3716
3513
  function createStitchableStream() {
@@ -4067,8 +3864,7 @@ async function streamText({
4067
3864
  maxRetries,
4068
3865
  abortSignal,
4069
3866
  headers,
4070
- maxToolRoundtrips = 0,
4071
- maxSteps = maxToolRoundtrips != null ? maxToolRoundtrips + 1 : 1,
3867
+ maxSteps = 1,
4072
3868
  experimental_continueSteps: continueSteps = false,
4073
3869
  experimental_telemetry: telemetry,
4074
3870
  experimental_providerMetadata: providerMetadata,
@@ -4267,7 +4063,7 @@ var DefaultStreamTextResult = class {
4267
4063
  generateId: generateId3,
4268
4064
  tools
4269
4065
  }) {
4270
- this.warnings = warnings;
4066
+ this.rawWarnings = warnings;
4271
4067
  this.rawResponse = rawResponse;
4272
4068
  const { resolve: resolveUsage, promise: usagePromise } = createResolvablePromise();
4273
4069
  this.usage = usagePromise;
@@ -4290,11 +4086,8 @@ var DefaultStreamTextResult = class {
4290
4086
  this.request = requestPromise;
4291
4087
  const { resolve: resolveResponse, promise: responsePromise } = createResolvablePromise();
4292
4088
  this.response = responsePromise;
4293
- const {
4294
- resolve: resolveResponseMessages,
4295
- promise: responseMessagesPromise
4296
- } = createResolvablePromise();
4297
- this.responseMessages = responseMessagesPromise;
4089
+ const { resolve: resolveWarnings, promise: warningsPromise } = createResolvablePromise();
4090
+ this.warnings = warningsPromise;
4298
4091
  const {
4299
4092
  stream: stitchableStream,
4300
4093
  addStream,
@@ -4361,14 +4154,10 @@ var DefaultStreamTextResult = class {
4361
4154
  const msToFirstChunk = now2() - startTimestamp;
4362
4155
  stepFirstChunk = false;
4363
4156
  doStreamSpan2.addEvent("ai.stream.firstChunk", {
4364
- "ai.response.msToFirstChunk": msToFirstChunk,
4365
- // deprecated:
4366
- "ai.stream.msToFirstChunk": msToFirstChunk
4157
+ "ai.response.msToFirstChunk": msToFirstChunk
4367
4158
  });
4368
4159
  doStreamSpan2.setAttributes({
4369
- "ai.response.msToFirstChunk": msToFirstChunk,
4370
- // deprecated:
4371
- "ai.stream.msToFirstChunk": msToFirstChunk
4160
+ "ai.response.msToFirstChunk": msToFirstChunk
4372
4161
  });
4373
4162
  }
4374
4163
  if (chunk.type === "text-delta" && chunk.textDelta.length === 0) {
@@ -4452,7 +4241,7 @@ var DefaultStreamTextResult = class {
4452
4241
  },
4453
4242
  // invoke onFinish callback and resolve toolResults promise when the stream is about to close:
4454
4243
  async flush(controller) {
4455
- var _a11;
4244
+ var _a11, _b;
4456
4245
  const stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : void 0;
4457
4246
  let nextStepType = "done";
4458
4247
  if (currentStep + 1 < maxSteps) {
@@ -4493,12 +4282,6 @@ var DefaultStreamTextResult = class {
4493
4282
  "ai.response.timestamp": stepResponse.timestamp.toISOString(),
4494
4283
  "ai.usage.promptTokens": stepUsage.promptTokens,
4495
4284
  "ai.usage.completionTokens": stepUsage.completionTokens,
4496
- // deprecated
4497
- "ai.finishReason": stepFinishReason,
4498
- "ai.result.text": { output: () => stepText },
4499
- "ai.result.toolCalls": {
4500
- output: () => stepToolCallsJson
4501
- },
4502
4285
  // standardized gen-ai llm span attributes:
4503
4286
  "gen_ai.response.finish_reasons": [stepFinishReason],
4504
4287
  "gen_ai.response.id": stepResponse.id,
@@ -4550,10 +4333,9 @@ var DefaultStreamTextResult = class {
4550
4333
  toolResults: stepToolResults,
4551
4334
  finishReason: stepFinishReason,
4552
4335
  usage: stepUsage,
4553
- warnings: self.warnings,
4336
+ warnings: self.rawWarnings,
4554
4337
  logprobs: stepLogProbs,
4555
4338
  request: stepRequest,
4556
- rawResponse: self.rawResponse,
4557
4339
  response: {
4558
4340
  ...stepResponse,
4559
4341
  headers: (_a11 = self.rawResponse) == null ? void 0 : _a11.headers,
@@ -4576,7 +4358,7 @@ var DefaultStreamTextResult = class {
4576
4358
  doStreamSpan: doStreamSpan3,
4577
4359
  startTimestampMs: startTimestamp2
4578
4360
  } = await startStep({ responseMessages });
4579
- self.warnings = result.warnings;
4361
+ self.rawWarnings = result.warnings;
4580
4362
  self.rawResponse = result.rawResponse;
4581
4363
  addStepStream({
4582
4364
  stream: result.stream,
@@ -4614,13 +4396,7 @@ var DefaultStreamTextResult = class {
4614
4396
  output: () => stepToolCallsJson
4615
4397
  },
4616
4398
  "ai.usage.promptTokens": combinedUsage.promptTokens,
4617
- "ai.usage.completionTokens": combinedUsage.completionTokens,
4618
- // deprecated
4619
- "ai.finishReason": stepFinishReason,
4620
- "ai.result.text": { output: () => fullStepText },
4621
- "ai.result.toolCalls": {
4622
- output: () => stepToolCallsJson
4623
- }
4399
+ "ai.usage.completionTokens": combinedUsage.completionTokens
4624
4400
  }
4625
4401
  })
4626
4402
  );
@@ -4637,7 +4413,7 @@ var DefaultStreamTextResult = class {
4637
4413
  messages: responseMessages
4638
4414
  });
4639
4415
  resolveSteps(stepResults);
4640
- resolveResponseMessages(responseMessages);
4416
+ resolveWarnings((_b = self.rawWarnings) != null ? _b : []);
4641
4417
  await (onFinish == null ? void 0 : onFinish({
4642
4418
  finishReason: stepFinishReason,
4643
4419
  logprobs: stepLogProbs,
@@ -4650,7 +4426,6 @@ var DefaultStreamTextResult = class {
4650
4426
  // The type exposed to the users will be correctly inferred.
4651
4427
  toolResults: stepToolResults,
4652
4428
  request: stepRequest,
4653
- rawResponse,
4654
4429
  response: {
4655
4430
  ...stepResponse,
4656
4431
  headers: rawResponse == null ? void 0 : rawResponse.headers,
@@ -4658,8 +4433,7 @@ var DefaultStreamTextResult = class {
4658
4433
  },
4659
4434
  warnings,
4660
4435
  experimental_providerMetadata: stepProviderMetadata,
4661
- steps: stepResults,
4662
- responseMessages
4436
+ steps: stepResults
4663
4437
  }));
4664
4438
  } catch (error) {
4665
4439
  controller.error(error);
@@ -4714,37 +4488,18 @@ var DefaultStreamTextResult = class {
4714
4488
  }
4715
4489
  });
4716
4490
  }
4717
- toAIStream(callbacks = {}) {
4718
- return this.toDataStreamInternal({ callbacks });
4719
- }
4720
4491
  toDataStreamInternal({
4721
- callbacks = {},
4722
4492
  getErrorMessage: getErrorMessage3 = () => "",
4723
4493
  // mask error messages for safety by default
4724
4494
  sendUsage = true
4725
4495
  } = {}) {
4726
4496
  let aggregatedResponse = "";
4727
4497
  const callbackTransformer = new TransformStream({
4728
- async start() {
4729
- if (callbacks.onStart)
4730
- await callbacks.onStart();
4731
- },
4732
4498
  async transform(chunk, controller) {
4733
4499
  controller.enqueue(chunk);
4734
4500
  if (chunk.type === "text-delta") {
4735
- const textDelta = chunk.textDelta;
4736
- aggregatedResponse += textDelta;
4737
- if (callbacks.onToken)
4738
- await callbacks.onToken(textDelta);
4739
- if (callbacks.onText)
4740
- await callbacks.onText(textDelta);
4501
+ aggregatedResponse += chunk.textDelta;
4741
4502
  }
4742
- },
4743
- async flush() {
4744
- if (callbacks.onCompletion)
4745
- await callbacks.onCompletion(aggregatedResponse);
4746
- if (callbacks.onFinal)
4747
- await callbacks.onFinal(aggregatedResponse);
4748
4503
  }
4749
4504
  });
4750
4505
  const streamPartsTransformer = new TransformStream({
@@ -4752,12 +4507,12 @@ var DefaultStreamTextResult = class {
4752
4507
  const chunkType = chunk.type;
4753
4508
  switch (chunkType) {
4754
4509
  case "text-delta": {
4755
- controller.enqueue((0, import_ui_utils9.formatStreamPart)("text", chunk.textDelta));
4510
+ controller.enqueue((0, import_ui_utils6.formatStreamPart)("text", chunk.textDelta));
4756
4511
  break;
4757
4512
  }
4758
4513
  case "tool-call-streaming-start": {
4759
4514
  controller.enqueue(
4760
- (0, import_ui_utils9.formatStreamPart)("tool_call_streaming_start", {
4515
+ (0, import_ui_utils6.formatStreamPart)("tool_call_streaming_start", {
4761
4516
  toolCallId: chunk.toolCallId,
4762
4517
  toolName: chunk.toolName
4763
4518
  })
@@ -4766,7 +4521,7 @@ var DefaultStreamTextResult = class {
4766
4521
  }
4767
4522
  case "tool-call-delta": {
4768
4523
  controller.enqueue(
4769
- (0, import_ui_utils9.formatStreamPart)("tool_call_delta", {
4524
+ (0, import_ui_utils6.formatStreamPart)("tool_call_delta", {
4770
4525
  toolCallId: chunk.toolCallId,
4771
4526
  argsTextDelta: chunk.argsTextDelta
4772
4527
  })
@@ -4775,7 +4530,7 @@ var DefaultStreamTextResult = class {
4775
4530
  }
4776
4531
  case "tool-call": {
4777
4532
  controller.enqueue(
4778
- (0, import_ui_utils9.formatStreamPart)("tool_call", {
4533
+ (0, import_ui_utils6.formatStreamPart)("tool_call", {
4779
4534
  toolCallId: chunk.toolCallId,
4780
4535
  toolName: chunk.toolName,
4781
4536
  args: chunk.args
@@ -4785,7 +4540,7 @@ var DefaultStreamTextResult = class {
4785
4540
  }
4786
4541
  case "tool-result": {
4787
4542
  controller.enqueue(
4788
- (0, import_ui_utils9.formatStreamPart)("tool_result", {
4543
+ (0, import_ui_utils6.formatStreamPart)("tool_result", {
4789
4544
  toolCallId: chunk.toolCallId,
4790
4545
  result: chunk.result
4791
4546
  })
@@ -4794,13 +4549,13 @@ var DefaultStreamTextResult = class {
4794
4549
  }
4795
4550
  case "error": {
4796
4551
  controller.enqueue(
4797
- (0, import_ui_utils9.formatStreamPart)("error", getErrorMessage3(chunk.error))
4552
+ (0, import_ui_utils6.formatStreamPart)("error", getErrorMessage3(chunk.error))
4798
4553
  );
4799
4554
  break;
4800
4555
  }
4801
4556
  case "step-finish": {
4802
4557
  controller.enqueue(
4803
- (0, import_ui_utils9.formatStreamPart)("finish_step", {
4558
+ (0, import_ui_utils6.formatStreamPart)("finish_step", {
4804
4559
  finishReason: chunk.finishReason,
4805
4560
  usage: sendUsage ? {
4806
4561
  promptTokens: chunk.usage.promptTokens,
@@ -4813,7 +4568,7 @@ var DefaultStreamTextResult = class {
4813
4568
  }
4814
4569
  case "finish": {
4815
4570
  controller.enqueue(
4816
- (0, import_ui_utils9.formatStreamPart)("finish_message", {
4571
+ (0, import_ui_utils6.formatStreamPart)("finish_message", {
4817
4572
  finishReason: chunk.finishReason,
4818
4573
  usage: sendUsage ? {
4819
4574
  promptTokens: chunk.usage.promptTokens,
@@ -4832,23 +4587,19 @@ var DefaultStreamTextResult = class {
4832
4587
  });
4833
4588
  return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer).pipeThrough(new TextEncoderStream());
4834
4589
  }
4835
- pipeAIStreamToResponse(response, init) {
4836
- return this.pipeDataStreamToResponse(response, init);
4837
- }
4838
- pipeDataStreamToResponse(response, options) {
4839
- const init = options == null ? void 0 : "init" in options ? options.init : {
4840
- headers: "headers" in options ? options.headers : void 0,
4841
- status: "status" in options ? options.status : void 0,
4842
- statusText: "statusText" in options ? options.statusText : void 0
4843
- };
4844
- const data = options == null ? void 0 : "data" in options ? options.data : void 0;
4845
- const getErrorMessage3 = options == null ? void 0 : "getErrorMessage" in options ? options.getErrorMessage : void 0;
4846
- const sendUsage = options == null ? void 0 : "sendUsage" in options ? options.sendUsage : void 0;
4590
+ pipeDataStreamToResponse(response, {
4591
+ status,
4592
+ statusText,
4593
+ headers,
4594
+ data,
4595
+ getErrorMessage: getErrorMessage3,
4596
+ sendUsage
4597
+ } = {}) {
4847
4598
  writeToServerResponse({
4848
4599
  response,
4849
- status: init == null ? void 0 : init.status,
4850
- statusText: init == null ? void 0 : init.statusText,
4851
- headers: prepareOutgoingHttpHeaders(init, {
4600
+ status,
4601
+ statusText,
4602
+ headers: prepareOutgoingHttpHeaders(headers, {
4852
4603
  contentType: "text/plain; charset=utf-8",
4853
4604
  dataStreamVersion: "v1"
4854
4605
  }),
@@ -4860,15 +4611,12 @@ var DefaultStreamTextResult = class {
4860
4611
  response,
4861
4612
  status: init == null ? void 0 : init.status,
4862
4613
  statusText: init == null ? void 0 : init.statusText,
4863
- headers: prepareOutgoingHttpHeaders(init, {
4614
+ headers: prepareOutgoingHttpHeaders(init == null ? void 0 : init.headers, {
4864
4615
  contentType: "text/plain; charset=utf-8"
4865
4616
  }),
4866
4617
  stream: this.textStream.pipeThrough(new TextEncoderStream())
4867
4618
  });
4868
4619
  }
4869
- toAIStreamResponse(options) {
4870
- return this.toDataStreamResponse(options);
4871
- }
4872
4620
  toDataStream(options) {
4873
4621
  const stream = this.toDataStreamInternal({
4874
4622
  getErrorMessage: options == null ? void 0 : options.getErrorMessage,
@@ -4876,22 +4624,20 @@ var DefaultStreamTextResult = class {
4876
4624
  });
4877
4625
  return (options == null ? void 0 : options.data) ? mergeStreams(options == null ? void 0 : options.data.stream, stream) : stream;
4878
4626
  }
4879
- toDataStreamResponse(options) {
4880
- var _a11;
4881
- const init = options == null ? void 0 : "init" in options ? options.init : {
4882
- headers: "headers" in options ? options.headers : void 0,
4883
- status: "status" in options ? options.status : void 0,
4884
- statusText: "statusText" in options ? options.statusText : void 0
4885
- };
4886
- const data = options == null ? void 0 : "data" in options ? options.data : void 0;
4887
- const getErrorMessage3 = options == null ? void 0 : "getErrorMessage" in options ? options.getErrorMessage : void 0;
4888
- const sendUsage = options == null ? void 0 : "sendUsage" in options ? options.sendUsage : void 0;
4627
+ toDataStreamResponse({
4628
+ headers,
4629
+ status,
4630
+ statusText,
4631
+ data,
4632
+ getErrorMessage: getErrorMessage3,
4633
+ sendUsage
4634
+ } = {}) {
4889
4635
  return new Response(
4890
4636
  this.toDataStream({ data, getErrorMessage: getErrorMessage3, sendUsage }),
4891
4637
  {
4892
- status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
4893
- statusText: init == null ? void 0 : init.statusText,
4894
- headers: prepareResponseHeaders(init, {
4638
+ status,
4639
+ statusText,
4640
+ headers: prepareResponseHeaders(headers, {
4895
4641
  contentType: "text/plain; charset=utf-8",
4896
4642
  dataStreamVersion: "v1"
4897
4643
  })
@@ -4902,13 +4648,12 @@ var DefaultStreamTextResult = class {
4902
4648
  var _a11;
4903
4649
  return new Response(this.textStream.pipeThrough(new TextEncoderStream()), {
4904
4650
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
4905
- headers: prepareResponseHeaders(init, {
4651
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
4906
4652
  contentType: "text/plain; charset=utf-8"
4907
4653
  })
4908
4654
  });
4909
4655
  }
4910
4656
  };
4911
- var experimental_streamText = streamText;
4912
4657
 
4913
4658
  // core/middleware/wrap-language-model.ts
4914
4659
  var experimental_wrapLanguageModel = ({
@@ -4995,26 +4740,6 @@ var NoSuchProviderError = class extends import_provider15.NoSuchModelError {
4995
4740
  static isInstance(error) {
4996
4741
  return import_provider15.AISDKError.hasMarker(error, marker10);
4997
4742
  }
4998
- /**
4999
- * @deprecated use `isInstance` instead
5000
- */
5001
- static isNoSuchProviderError(error) {
5002
- return error instanceof Error && error.name === name10 && typeof error.providerId === "string" && Array.isArray(error.availableProviders);
5003
- }
5004
- /**
5005
- * @deprecated Do not use this method. It will be removed in the next major version.
5006
- */
5007
- toJSON() {
5008
- return {
5009
- name: this.name,
5010
- message: this.message,
5011
- stack: this.stack,
5012
- modelId: this.modelId,
5013
- modelType: this.modelType,
5014
- providerId: this.providerId,
5015
- availableProviders: this.availableProviders
5016
- };
5017
- }
5018
4743
  };
5019
4744
  _a10 = symbol10;
5020
4745
 
@@ -5027,15 +4752,11 @@ function experimental_createProviderRegistry(providers) {
5027
4752
  }
5028
4753
  return registry;
5029
4754
  }
5030
- var experimental_createModelRegistry = experimental_createProviderRegistry;
5031
4755
  var DefaultProviderRegistry = class {
5032
4756
  constructor() {
5033
4757
  this.providers = {};
5034
4758
  }
5035
- registerProvider({
5036
- id,
5037
- provider
5038
- }) {
4759
+ registerProvider({ id, provider }) {
5039
4760
  this.providers[id] = provider;
5040
4761
  }
5041
4762
  getProvider(id) {
@@ -5071,10 +4792,10 @@ var DefaultProviderRegistry = class {
5071
4792
  return model;
5072
4793
  }
5073
4794
  textEmbeddingModel(id) {
5074
- var _a11, _b, _c;
4795
+ var _a11;
5075
4796
  const [providerId, modelId] = this.splitId(id, "textEmbeddingModel");
5076
4797
  const provider = this.getProvider(providerId);
5077
- const model = (_c = (_a11 = provider.textEmbeddingModel) == null ? void 0 : _a11.call(provider, modelId)) != null ? _c : "textEmbedding" in provider ? (_b = provider.textEmbedding) == null ? void 0 : _b.call(provider, modelId) : void 0;
4798
+ const model = (_a11 = provider.textEmbeddingModel) == null ? void 0 : _a11.call(provider, modelId);
5078
4799
  if (model == null) {
5079
4800
  throw new import_provider16.NoSuchModelError({
5080
4801
  modelId: id,
@@ -5115,123 +4836,8 @@ function magnitude(vector) {
5115
4836
  return Math.sqrt(dotProduct(vector, vector));
5116
4837
  }
5117
4838
 
5118
- // streams/ai-stream.ts
5119
- var import_eventsource_parser = require("eventsource-parser");
5120
- function createEventStreamTransformer(customParser) {
5121
- const textDecoder = new TextDecoder();
5122
- let eventSourceParser;
5123
- return new TransformStream({
5124
- async start(controller) {
5125
- eventSourceParser = (0, import_eventsource_parser.createParser)(
5126
- (event) => {
5127
- if ("data" in event && event.type === "event" && event.data === "[DONE]" || // Replicate doesn't send [DONE] but does send a 'done' event
5128
- // @see https://replicate.com/docs/streaming
5129
- event.event === "done") {
5130
- controller.terminate();
5131
- return;
5132
- }
5133
- if ("data" in event) {
5134
- const parsedMessage = customParser ? customParser(event.data, {
5135
- event: event.event
5136
- }) : event.data;
5137
- if (parsedMessage)
5138
- controller.enqueue(parsedMessage);
5139
- }
5140
- }
5141
- );
5142
- },
5143
- transform(chunk) {
5144
- eventSourceParser.feed(textDecoder.decode(chunk));
5145
- }
5146
- });
5147
- }
5148
- function createCallbacksTransformer(cb) {
5149
- const textEncoder = new TextEncoder();
5150
- let aggregatedResponse = "";
5151
- const callbacks = cb || {};
5152
- return new TransformStream({
5153
- async start() {
5154
- if (callbacks.onStart)
5155
- await callbacks.onStart();
5156
- },
5157
- async transform(message, controller) {
5158
- const content = typeof message === "string" ? message : message.content;
5159
- controller.enqueue(textEncoder.encode(content));
5160
- aggregatedResponse += content;
5161
- if (callbacks.onToken)
5162
- await callbacks.onToken(content);
5163
- if (callbacks.onText && typeof message === "string") {
5164
- await callbacks.onText(message);
5165
- }
5166
- },
5167
- async flush() {
5168
- if (callbacks.onCompletion) {
5169
- await callbacks.onCompletion(aggregatedResponse);
5170
- }
5171
- }
5172
- });
5173
- }
5174
- function trimStartOfStreamHelper() {
5175
- let isStreamStart = true;
5176
- return (text) => {
5177
- if (isStreamStart) {
5178
- text = text.trimStart();
5179
- if (text)
5180
- isStreamStart = false;
5181
- }
5182
- return text;
5183
- };
5184
- }
5185
- function AIStream(response, customParser, callbacks) {
5186
- if (!response.ok) {
5187
- if (response.body) {
5188
- const reader = response.body.getReader();
5189
- return new ReadableStream({
5190
- async start(controller) {
5191
- const { done, value } = await reader.read();
5192
- if (!done) {
5193
- const errorText = new TextDecoder().decode(value);
5194
- controller.error(new Error(`Response error: ${errorText}`));
5195
- }
5196
- }
5197
- });
5198
- } else {
5199
- return new ReadableStream({
5200
- start(controller) {
5201
- controller.error(new Error("Response error: No response body"));
5202
- }
5203
- });
5204
- }
5205
- }
5206
- const responseBodyStream = response.body || createEmptyReadableStream();
5207
- return responseBodyStream.pipeThrough(createEventStreamTransformer(customParser)).pipeThrough(createCallbacksTransformer(callbacks));
5208
- }
5209
- function createEmptyReadableStream() {
5210
- return new ReadableStream({
5211
- start(controller) {
5212
- controller.close();
5213
- }
5214
- });
5215
- }
5216
- function readableFromAsyncIterable(iterable) {
5217
- let it = iterable[Symbol.asyncIterator]();
5218
- return new ReadableStream({
5219
- async pull(controller) {
5220
- const { done, value } = await it.next();
5221
- if (done)
5222
- controller.close();
5223
- else
5224
- controller.enqueue(value);
5225
- },
5226
- async cancel(reason) {
5227
- var _a11;
5228
- await ((_a11 = it.return) == null ? void 0 : _a11.call(it, reason));
5229
- }
5230
- });
5231
- }
5232
-
5233
4839
  // streams/assistant-response.ts
5234
- var import_ui_utils7 = require("@ai-sdk/ui-utils");
4840
+ var import_ui_utils8 = require("@ai-sdk/ui-utils");
5235
4841
  function AssistantResponse({ threadId, messageId }, process2) {
5236
4842
  const stream = new ReadableStream({
5237
4843
  async start(controller) {
@@ -5239,17 +4845,17 @@ function AssistantResponse({ threadId, messageId }, process2) {
5239
4845
  const textEncoder = new TextEncoder();
5240
4846
  const sendMessage = (message) => {
5241
4847
  controller.enqueue(
5242
- textEncoder.encode((0, import_ui_utils7.formatStreamPart)("assistant_message", message))
4848
+ textEncoder.encode((0, import_ui_utils8.formatStreamPart)("assistant_message", message))
5243
4849
  );
5244
4850
  };
5245
4851
  const sendDataMessage = (message) => {
5246
4852
  controller.enqueue(
5247
- textEncoder.encode((0, import_ui_utils7.formatStreamPart)("data_message", message))
4853
+ textEncoder.encode((0, import_ui_utils8.formatStreamPart)("data_message", message))
5248
4854
  );
5249
4855
  };
5250
4856
  const sendError = (errorMessage) => {
5251
4857
  controller.enqueue(
5252
- textEncoder.encode((0, import_ui_utils7.formatStreamPart)("error", errorMessage))
4858
+ textEncoder.encode((0, import_ui_utils8.formatStreamPart)("error", errorMessage))
5253
4859
  );
5254
4860
  };
5255
4861
  const forwardStream = async (stream2) => {
@@ -5260,7 +4866,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5260
4866
  case "thread.message.created": {
5261
4867
  controller.enqueue(
5262
4868
  textEncoder.encode(
5263
- (0, import_ui_utils7.formatStreamPart)("assistant_message", {
4869
+ (0, import_ui_utils8.formatStreamPart)("assistant_message", {
5264
4870
  id: value.data.id,
5265
4871
  role: "assistant",
5266
4872
  content: [{ type: "text", text: { value: "" } }]
@@ -5274,7 +4880,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5274
4880
  if ((content == null ? void 0 : content.type) === "text" && ((_b = content.text) == null ? void 0 : _b.value) != null) {
5275
4881
  controller.enqueue(
5276
4882
  textEncoder.encode(
5277
- (0, import_ui_utils7.formatStreamPart)("text", content.text.value)
4883
+ (0, import_ui_utils8.formatStreamPart)("text", content.text.value)
5278
4884
  )
5279
4885
  );
5280
4886
  }
@@ -5291,7 +4897,7 @@ function AssistantResponse({ threadId, messageId }, process2) {
5291
4897
  };
5292
4898
  controller.enqueue(
5293
4899
  textEncoder.encode(
5294
- (0, import_ui_utils7.formatStreamPart)("assistant_control_data", {
4900
+ (0, import_ui_utils8.formatStreamPart)("assistant_control_data", {
5295
4901
  threadId,
5296
4902
  messageId
5297
4903
  })
@@ -5299,8 +4905,6 @@ function AssistantResponse({ threadId, messageId }, process2) {
5299
4905
  );
5300
4906
  try {
5301
4907
  await process2({
5302
- threadId,
5303
- messageId,
5304
4908
  sendMessage,
5305
4909
  sendDataMessage,
5306
4910
  forwardStream
@@ -5323,24 +4927,48 @@ function AssistantResponse({ threadId, messageId }, process2) {
5323
4927
  }
5324
4928
  });
5325
4929
  }
5326
- var experimental_AssistantResponse = AssistantResponse;
5327
4930
 
5328
4931
  // streams/langchain-adapter.ts
5329
4932
  var langchain_adapter_exports = {};
5330
4933
  __export(langchain_adapter_exports, {
5331
- toAIStream: () => toAIStream,
5332
4934
  toDataStream: () => toDataStream,
5333
4935
  toDataStreamResponse: () => toDataStreamResponse
5334
4936
  });
5335
4937
 
4938
+ // streams/stream-callbacks.ts
4939
+ function createCallbacksTransformer(callbacks = {}) {
4940
+ const textEncoder = new TextEncoder();
4941
+ let aggregatedResponse = "";
4942
+ return new TransformStream({
4943
+ async start() {
4944
+ if (callbacks.onStart)
4945
+ await callbacks.onStart();
4946
+ },
4947
+ async transform(message, controller) {
4948
+ controller.enqueue(textEncoder.encode(message));
4949
+ aggregatedResponse += message;
4950
+ if (callbacks.onToken)
4951
+ await callbacks.onToken(message);
4952
+ if (callbacks.onText && typeof message === "string") {
4953
+ await callbacks.onText(message);
4954
+ }
4955
+ },
4956
+ async flush() {
4957
+ if (callbacks.onCompletion) {
4958
+ await callbacks.onCompletion(aggregatedResponse);
4959
+ }
4960
+ }
4961
+ });
4962
+ }
4963
+
5336
4964
  // streams/stream-data.ts
5337
- var import_ui_utils8 = require("@ai-sdk/ui-utils");
4965
+ var import_ui_utils9 = require("@ai-sdk/ui-utils");
5338
4966
 
5339
4967
  // util/constants.ts
5340
4968
  var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
5341
4969
 
5342
4970
  // streams/stream-data.ts
5343
- var StreamData2 = class {
4971
+ var StreamData = class {
5344
4972
  constructor() {
5345
4973
  this.encoder = new TextEncoder();
5346
4974
  this.controller = null;
@@ -5386,7 +5014,7 @@ var StreamData2 = class {
5386
5014
  throw new Error("Stream controller is not initialized.");
5387
5015
  }
5388
5016
  this.controller.enqueue(
5389
- this.encoder.encode((0, import_ui_utils8.formatStreamPart)("data", [value]))
5017
+ this.encoder.encode((0, import_ui_utils9.formatStreamPart)("data", [value]))
5390
5018
  );
5391
5019
  }
5392
5020
  appendMessageAnnotation(value) {
@@ -5397,7 +5025,7 @@ var StreamData2 = class {
5397
5025
  throw new Error("Stream controller is not initialized.");
5398
5026
  }
5399
5027
  this.controller.enqueue(
5400
- this.encoder.encode((0, import_ui_utils8.formatStreamPart)("message_annotations", [value]))
5028
+ this.encoder.encode((0, import_ui_utils9.formatStreamPart)("message_annotations", [value]))
5401
5029
  );
5402
5030
  }
5403
5031
  };
@@ -5407,17 +5035,12 @@ function createStreamDataTransformer() {
5407
5035
  return new TransformStream({
5408
5036
  transform: async (chunk, controller) => {
5409
5037
  const message = decoder.decode(chunk);
5410
- controller.enqueue(encoder.encode((0, import_ui_utils8.formatStreamPart)("text", message)));
5038
+ controller.enqueue(encoder.encode((0, import_ui_utils9.formatStreamPart)("text", message)));
5411
5039
  }
5412
5040
  });
5413
5041
  }
5414
- var experimental_StreamData = class extends StreamData2 {
5415
- };
5416
5042
 
5417
5043
  // streams/langchain-adapter.ts
5418
- function toAIStream(stream, callbacks) {
5419
- return toDataStream(stream, callbacks);
5420
- }
5421
5044
  function toDataStream(stream, callbacks) {
5422
5045
  return stream.pipeThrough(
5423
5046
  new TransformStream({
@@ -5450,7 +5073,7 @@ function toDataStreamResponse(stream, options) {
5450
5073
  return new Response(responseStream, {
5451
5074
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
5452
5075
  statusText: init == null ? void 0 : init.statusText,
5453
- headers: prepareResponseHeaders(init, {
5076
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
5454
5077
  contentType: "text/plain; charset=utf-8",
5455
5078
  dataStreamVersion: "v1"
5456
5079
  })
@@ -5475,8 +5098,16 @@ __export(llamaindex_adapter_exports, {
5475
5098
  toDataStream: () => toDataStream2,
5476
5099
  toDataStreamResponse: () => toDataStreamResponse2
5477
5100
  });
5101
+ var import_provider_utils10 = require("@ai-sdk/provider-utils");
5478
5102
  function toDataStream2(stream, callbacks) {
5479
- return toReadableStream(stream).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5103
+ const trimStart = trimStartOfStream();
5104
+ return (0, import_provider_utils10.convertAsyncIteratorToReadableStream)(stream[Symbol.asyncIterator]()).pipeThrough(
5105
+ new TransformStream({
5106
+ async transform(message, controller) {
5107
+ controller.enqueue(trimStart(message.delta));
5108
+ }
5109
+ })
5110
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5480
5111
  }
5481
5112
  function toDataStreamResponse2(stream, options = {}) {
5482
5113
  var _a11;
@@ -5486,79 +5117,26 @@ function toDataStreamResponse2(stream, options = {}) {
5486
5117
  return new Response(responseStream, {
5487
5118
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
5488
5119
  statusText: init == null ? void 0 : init.statusText,
5489
- headers: prepareResponseHeaders(init, {
5120
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
5490
5121
  contentType: "text/plain; charset=utf-8",
5491
5122
  dataStreamVersion: "v1"
5492
5123
  })
5493
5124
  });
5494
5125
  }
5495
- function toReadableStream(res) {
5496
- const it = res[Symbol.asyncIterator]();
5497
- const trimStartOfStream = trimStartOfStreamHelper();
5498
- return new ReadableStream({
5499
- async pull(controller) {
5500
- var _a11;
5501
- const { value, done } = await it.next();
5502
- if (done) {
5503
- controller.close();
5504
- return;
5505
- }
5506
- const text = trimStartOfStream((_a11 = value.delta) != null ? _a11 : "");
5507
- if (text) {
5508
- controller.enqueue(text);
5509
- }
5126
+ function trimStartOfStream() {
5127
+ let isStreamStart = true;
5128
+ return (text) => {
5129
+ if (isStreamStart) {
5130
+ text = text.trimStart();
5131
+ if (text)
5132
+ isStreamStart = false;
5510
5133
  }
5511
- });
5512
- }
5513
-
5514
- // streams/stream-to-response.ts
5515
- function streamToResponse(res, response, init, data) {
5516
- var _a11;
5517
- response.writeHead((_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200, {
5518
- "Content-Type": "text/plain; charset=utf-8",
5519
- ...init == null ? void 0 : init.headers
5520
- });
5521
- let processedStream = res;
5522
- if (data) {
5523
- processedStream = mergeStreams(data.stream, res);
5524
- }
5525
- const reader = processedStream.getReader();
5526
- function read() {
5527
- reader.read().then(({ done, value }) => {
5528
- if (done) {
5529
- response.end();
5530
- return;
5531
- }
5532
- response.write(value);
5533
- read();
5534
- });
5535
- }
5536
- read();
5134
+ return text;
5135
+ };
5537
5136
  }
5538
-
5539
- // streams/streaming-text-response.ts
5540
- var StreamingTextResponse = class extends Response {
5541
- constructor(res, init, data) {
5542
- let processedStream = res;
5543
- if (data) {
5544
- processedStream = mergeStreams(data.stream, res);
5545
- }
5546
- super(processedStream, {
5547
- ...init,
5548
- status: 200,
5549
- headers: prepareResponseHeaders(init, {
5550
- contentType: "text/plain; charset=utf-8"
5551
- })
5552
- });
5553
- }
5554
- };
5555
-
5556
- // streams/index.ts
5557
- var generateId2 = import_provider_utils10.generateId;
5558
5137
  // Annotate the CommonJS export names for ESM import in node:
5559
5138
  0 && (module.exports = {
5560
5139
  AISDKError,
5561
- AIStream,
5562
5140
  APICallError,
5563
5141
  AssistantResponse,
5564
5142
  DownloadError,
@@ -5581,25 +5159,15 @@ var generateId2 = import_provider_utils10.generateId;
5581
5159
  NoSuchToolError,
5582
5160
  RetryError,
5583
5161
  StreamData,
5584
- StreamingTextResponse,
5585
5162
  TypeValidationError,
5586
5163
  UnsupportedFunctionalityError,
5587
5164
  convertToCoreMessages,
5588
5165
  cosineSimilarity,
5589
- createCallbacksTransformer,
5590
- createEventStreamTransformer,
5591
5166
  createStreamDataTransformer,
5592
5167
  embed,
5593
5168
  embedMany,
5594
- experimental_AssistantResponse,
5595
- experimental_StreamData,
5596
- experimental_createModelRegistry,
5597
5169
  experimental_createProviderRegistry,
5598
5170
  experimental_customProvider,
5599
- experimental_generateObject,
5600
- experimental_generateText,
5601
- experimental_streamObject,
5602
- experimental_streamText,
5603
5171
  experimental_wrapLanguageModel,
5604
5172
  formatStreamPart,
5605
5173
  generateId,
@@ -5609,11 +5177,8 @@ var generateId2 = import_provider_utils10.generateId;
5609
5177
  parseStreamPart,
5610
5178
  processDataProtocolResponse,
5611
5179
  readDataStream,
5612
- readableFromAsyncIterable,
5613
5180
  streamObject,
5614
5181
  streamText,
5615
- streamToResponse,
5616
- tool,
5617
- trimStartOfStreamHelper
5182
+ tool
5618
5183
  });
5619
5184
  //# sourceMappingURL=index.js.map