ai 6.0.95 → 6.0.97

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.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  getErrorMessage,
3
3
  LanguageModelV3,
4
+ LanguageModelV3ToolChoice,
4
5
  SharedV3Warning,
5
6
  UnsupportedFunctionalityError,
6
7
  } from '@ai-sdk/provider';
@@ -9,7 +10,9 @@ import {
9
10
  DelayedPromise,
10
11
  IdGenerator,
11
12
  isAbortError,
13
+ ModelMessage,
12
14
  ProviderOptions,
15
+ SystemModelMessage,
13
16
  ToolApprovalResponse,
14
17
  ToolContent,
15
18
  } from '@ai-sdk/provider-utils';
@@ -23,6 +26,7 @@ import {
23
26
  getChunkTimeoutMs,
24
27
  getStepTimeoutMs,
25
28
  getTotalTimeoutMs,
29
+ TimeoutConfiguration,
26
30
  } from '../prompt/call-settings';
27
31
  import { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';
28
32
  import { createToolModelOutput } from '../prompt/create-tool-model-output';
@@ -77,6 +81,14 @@ import { mergeObjects } from '../util/merge-objects';
77
81
  import { now as originalNow } from '../util/now';
78
82
  import { prepareRetries } from '../util/prepare-retries';
79
83
  import { collectToolApprovals } from './collect-tool-approvals';
84
+ import type {
85
+ OnFinishEvent,
86
+ OnStartEvent,
87
+ OnStepFinishEvent,
88
+ OnStepStartEvent,
89
+ OnToolCallFinishEvent,
90
+ OnToolCallStartEvent,
91
+ } from './callback-events';
80
92
  import { ContentPart } from './content-part';
81
93
  import { executeToolCall } from './execute-tool-call';
82
94
  import { Output, text } from './output';
@@ -141,7 +153,7 @@ export type StreamTextOnErrorCallback = (event: {
141
153
  * @param stepResult - The result of the step.
142
154
  */
143
155
  export type StreamTextOnStepFinishCallback<TOOLS extends ToolSet> = (
144
- stepResult: StepResult<TOOLS>,
156
+ event: OnStepFinishEvent<TOOLS>,
145
157
  ) => PromiseLike<void> | void;
146
158
 
147
159
  /**
@@ -172,26 +184,7 @@ export type StreamTextOnChunkCallback<TOOLS extends ToolSet> = (event: {
172
184
  * @param event - The event that is passed to the callback.
173
185
  */
174
186
  export type StreamTextOnFinishCallback<TOOLS extends ToolSet> = (
175
- event: StepResult<TOOLS> & {
176
- /**
177
- * Details for all steps.
178
- */
179
- readonly steps: StepResult<TOOLS>[];
180
-
181
- /**
182
- * Total usage for all steps. This is the sum of the usage of all steps.
183
- */
184
- readonly totalUsage: LanguageModelUsage;
185
-
186
- /**
187
- * Context that is passed into tool execution.
188
- *
189
- * Experimental (can break in patch releases).
190
- *
191
- * @default undefined
192
- */
193
- experimental_context: unknown;
194
- },
187
+ event: OnFinishEvent<TOOLS>,
195
188
  ) => PromiseLike<void> | void;
196
189
 
197
190
  /**
@@ -206,6 +199,50 @@ export type StreamTextOnAbortCallback<TOOLS extends ToolSet> = (event: {
206
199
  readonly steps: StepResult<TOOLS>[];
207
200
  }) => PromiseLike<void> | void;
208
201
 
202
+ /**
203
+ * Include settings for streamText (requestBody only).
204
+ */
205
+ type StreamTextIncludeSettings = { requestBody?: boolean };
206
+
207
+ /**
208
+ * Callback that is set using the `experimental_onStart` option.
209
+ *
210
+ * Called when the streamText operation begins, before any LLM calls.
211
+ * Use this callback for logging, analytics, or initializing state at the
212
+ * start of a generation.
213
+ *
214
+ * @param event - The event object containing generation configuration.
215
+ */
216
+ export type StreamTextOnStartCallback<
217
+ TOOLS extends ToolSet = ToolSet,
218
+ OUTPUT extends Output = Output,
219
+ > = (
220
+ event: OnStartEvent<TOOLS, OUTPUT, StreamTextIncludeSettings>,
221
+ ) => PromiseLike<void> | void;
222
+
223
+ /**
224
+ * Callback that is set using the `experimental_onStepStart` option.
225
+ *
226
+ * Called when a step (LLM call) begins, before the provider is called.
227
+ * Each step represents a single LLM invocation. Multiple steps occur when
228
+ * using tool calls (the model may be called multiple times in a loop).
229
+ *
230
+ * @param event - The event object containing step configuration.
231
+ */
232
+ export type StreamTextOnStepStartCallback<
233
+ TOOLS extends ToolSet = ToolSet,
234
+ OUTPUT extends Output = Output,
235
+ > = (
236
+ event: OnStepStartEvent<TOOLS, OUTPUT, StreamTextIncludeSettings>,
237
+ ) => PromiseLike<void> | void;
238
+
239
+ export type StreamTextOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> =
240
+ (event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;
241
+
242
+ export type StreamTextOnToolCallFinishCallback<
243
+ TOOLS extends ToolSet = ToolSet,
244
+ > = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;
245
+
209
246
  /**
210
247
  * Generate a text and call tools for a given prompt using a language model.
211
248
  *
@@ -285,6 +322,10 @@ export function streamText<
285
322
  onFinish,
286
323
  onAbort,
287
324
  onStepFinish,
325
+ experimental_onStart: onStart,
326
+ experimental_onStepStart: onStepStart,
327
+ experimental_onToolCallStart: onToolCallStart,
328
+ experimental_onToolCallFinish: onToolCallFinish,
288
329
  experimental_context,
289
330
  experimental_include: include,
290
331
  _internal: { now = originalNow, generateId = originalGenerateId } = {},
@@ -421,6 +462,35 @@ export function streamText<
421
462
  */
422
463
  onStepFinish?: StreamTextOnStepFinishCallback<TOOLS>;
423
464
 
465
+ /**
466
+ * Callback that is called when the streamText operation begins,
467
+ * before any LLM calls are made.
468
+ */
469
+ experimental_onStart?: StreamTextOnStartCallback<NoInfer<TOOLS>, OUTPUT>;
470
+
471
+ /**
472
+ * Callback that is called when a step (LLM call) begins,
473
+ * before the provider is called.
474
+ */
475
+ experimental_onStepStart?: StreamTextOnStepStartCallback<
476
+ NoInfer<TOOLS>,
477
+ OUTPUT
478
+ >;
479
+
480
+ /**
481
+ * Callback that is called right before a tool's execute function runs.
482
+ */
483
+ experimental_onToolCallStart?: StreamTextOnToolCallStartCallback<
484
+ NoInfer<TOOLS>
485
+ >;
486
+
487
+ /**
488
+ * Callback that is called right after a tool's execute function completes (or errors).
489
+ */
490
+ experimental_onToolCallFinish?: StreamTextOnToolCallFinishCallback<
491
+ NoInfer<TOOLS>
492
+ >;
493
+
424
494
  /**
425
495
  * Context that is passed into tool execution.
426
496
  *
@@ -490,11 +560,18 @@ export function streamText<
490
560
  providerOptions,
491
561
  prepareStep,
492
562
  includeRawChunks,
563
+ timeout,
564
+ stopWhen,
565
+ originalAbortSignal: abortSignal,
493
566
  onChunk,
494
567
  onError,
495
568
  onFinish,
496
569
  onAbort,
497
570
  onStepFinish,
571
+ onStart,
572
+ onStepStart,
573
+ onToolCallStart,
574
+ onToolCallFinish,
498
575
  now,
499
576
  generateId,
500
577
  experimental_context,
@@ -663,11 +740,18 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
663
740
  includeRawChunks,
664
741
  now,
665
742
  generateId,
743
+ timeout,
744
+ stopWhen,
745
+ originalAbortSignal,
666
746
  onChunk,
667
747
  onError,
668
748
  onFinish,
669
749
  onAbort,
670
750
  onStepFinish,
751
+ onStart,
752
+ onStepStart,
753
+ onToolCallStart,
754
+ onToolCallFinish,
671
755
  experimental_context,
672
756
  download,
673
757
  include,
@@ -697,6 +781,12 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
697
781
  includeRawChunks: boolean;
698
782
  now: () => number;
699
783
  generateId: () => string;
784
+ timeout: TimeoutConfiguration | undefined;
785
+ stopWhen:
786
+ | StopCondition<NoInfer<TOOLS>>
787
+ | Array<StopCondition<NoInfer<TOOLS>>>
788
+ | undefined;
789
+ originalAbortSignal: AbortSignal | undefined;
700
790
  experimental_context: unknown;
701
791
  download: DownloadFunction | undefined;
702
792
  include: { requestBody?: boolean } | undefined;
@@ -707,6 +797,10 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
707
797
  onFinish: undefined | StreamTextOnFinishCallback<TOOLS>;
708
798
  onAbort: undefined | StreamTextOnAbortCallback<TOOLS>;
709
799
  onStepFinish: undefined | StreamTextOnStepFinishCallback<TOOLS>;
800
+ onStart: undefined | StreamTextOnStartCallback<TOOLS, OUTPUT>;
801
+ onStepStart: undefined | StreamTextOnStepStartCallback<TOOLS, OUTPUT>;
802
+ onToolCallStart: undefined | StreamTextOnToolCallStartCallback<TOOLS>;
803
+ onToolCallFinish: undefined | StreamTextOnToolCallFinishCallback<TOOLS>;
710
804
  }) {
711
805
  this.outputSpecification = output;
712
806
  this.includeRawChunks = includeRawChunks;
@@ -918,14 +1012,8 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
918
1012
  // Add step information (after response messages are updated):
919
1013
  const currentStepResult: StepResult<TOOLS> = new DefaultStepResult({
920
1014
  stepNumber: recordedSteps.length,
921
- model: {
922
- provider: model.provider,
923
- modelId: model.modelId,
924
- },
925
- functionId: telemetry?.functionId,
926
- metadata: telemetry?.metadata as
927
- | Record<string, unknown>
928
- | undefined,
1015
+ model: modelInfo,
1016
+ ...callbackTelemetryProps,
929
1017
  experimental_context,
930
1018
  content: recordedContent,
931
1019
  finishReason: part.finishReason,
@@ -944,8 +1032,8 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
944
1032
 
945
1033
  logWarnings({
946
1034
  warnings: recordedWarnings,
947
- provider: model.provider,
948
- model: model.modelId,
1035
+ provider: modelInfo.provider,
1036
+ model: modelInfo.modelId,
949
1037
  });
950
1038
 
951
1039
  recordedSteps.push(currentStepResult);
@@ -1153,6 +1241,12 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
1153
1241
 
1154
1242
  const self = this;
1155
1243
 
1244
+ const modelInfo = { provider: model.provider, modelId: model.modelId };
1245
+ const callbackTelemetryProps = {
1246
+ functionId: telemetry?.functionId,
1247
+ metadata: telemetry?.metadata as Record<string, unknown> | undefined,
1248
+ };
1249
+
1156
1250
  recordSpan({
1157
1251
  name: 'ai.streamText',
1158
1252
  attributes: selectTelemetryAttributes({
@@ -1177,6 +1271,38 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
1177
1271
  messages,
1178
1272
  } as Prompt);
1179
1273
 
1274
+ try {
1275
+ await onStart?.({
1276
+ model: modelInfo,
1277
+ system,
1278
+ prompt,
1279
+ messages,
1280
+ tools,
1281
+ toolChoice,
1282
+ activeTools,
1283
+ maxOutputTokens: callSettings.maxOutputTokens,
1284
+ temperature: callSettings.temperature,
1285
+ topP: callSettings.topP,
1286
+ topK: callSettings.topK,
1287
+ presencePenalty: callSettings.presencePenalty,
1288
+ frequencyPenalty: callSettings.frequencyPenalty,
1289
+ stopSequences: callSettings.stopSequences,
1290
+ seed: callSettings.seed,
1291
+ maxRetries,
1292
+ timeout,
1293
+ headers,
1294
+ providerOptions,
1295
+ stopWhen,
1296
+ output,
1297
+ abortSignal: originalAbortSignal,
1298
+ include,
1299
+ ...callbackTelemetryProps,
1300
+ experimental_context,
1301
+ });
1302
+ } catch (_ignored) {
1303
+ // Errors in callbacks should not break the generation flow.
1304
+ }
1305
+
1180
1306
  const initialMessages = initialPrompt.messages;
1181
1307
  const initialResponseMessages: Array<ResponseMessage> = [];
1182
1308
 
@@ -1242,6 +1368,10 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
1242
1368
  messages: initialMessages,
1243
1369
  abortSignal,
1244
1370
  experimental_context,
1371
+ stepNumber: recordedSteps.length,
1372
+ model: modelInfo,
1373
+ onToolCallStart,
1374
+ onToolCallFinish,
1245
1375
  onPreliminaryToolResult: result => {
1246
1376
  toolExecutionStepStreamController?.enqueue(result);
1247
1377
  },
@@ -1381,6 +1511,10 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
1381
1511
  const stepModel = resolveLanguageModel(
1382
1512
  prepareStepResult?.model ?? model,
1383
1513
  );
1514
+ const stepModelInfo = {
1515
+ provider: stepModel.provider,
1516
+ modelId: stepModel.modelId,
1517
+ };
1384
1518
 
1385
1519
  const promptMessages = await convertToLanguageModelPrompt({
1386
1520
  prompt: {
@@ -1391,20 +1525,54 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
1391
1525
  download,
1392
1526
  });
1393
1527
 
1528
+ const stepActiveTools =
1529
+ prepareStepResult?.activeTools ?? activeTools;
1530
+
1394
1531
  const { toolChoice: stepToolChoice, tools: stepTools } =
1395
1532
  await prepareToolsAndToolChoice({
1396
1533
  tools,
1397
1534
  toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1398
- activeTools: prepareStepResult?.activeTools ?? activeTools,
1535
+ activeTools: stepActiveTools,
1399
1536
  });
1400
1537
 
1401
1538
  experimental_context =
1402
1539
  prepareStepResult?.experimental_context ?? experimental_context;
1403
1540
 
1541
+ const stepMessages =
1542
+ prepareStepResult?.messages ?? stepInputMessages;
1543
+
1544
+ const stepSystem =
1545
+ prepareStepResult?.system ?? initialPrompt.system;
1546
+
1404
1547
  const stepProviderOptions = mergeObjects(
1405
1548
  providerOptions,
1406
1549
  prepareStepResult?.providerOptions,
1407
1550
  );
1551
+
1552
+ try {
1553
+ await onStepStart?.({
1554
+ stepNumber: recordedSteps.length,
1555
+ model: stepModelInfo,
1556
+ system: stepSystem,
1557
+ messages: stepMessages,
1558
+ tools,
1559
+ toolChoice: stepToolChoice,
1560
+ activeTools: stepActiveTools,
1561
+ steps: [...recordedSteps],
1562
+ providerOptions: stepProviderOptions,
1563
+ timeout,
1564
+ headers,
1565
+ stopWhen,
1566
+ output,
1567
+ abortSignal: originalAbortSignal,
1568
+ include,
1569
+ ...callbackTelemetryProps,
1570
+ experimental_context,
1571
+ });
1572
+ } catch (_ignored) {
1573
+ // Errors in callbacks should not break the generation flow.
1574
+ }
1575
+
1408
1576
  const {
1409
1577
  result: { stream, response, request },
1410
1578
  doStreamSpan,
@@ -1483,6 +1651,10 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
1483
1651
  abortSignal,
1484
1652
  experimental_context,
1485
1653
  generateId,
1654
+ stepNumber: recordedSteps.length,
1655
+ model: stepModelInfo,
1656
+ onToolCallStart,
1657
+ onToolCallFinish,
1486
1658
  });
1487
1659
 
1488
1660
  // Conditionally include request.body based on include settings.
@@ -1507,7 +1679,7 @@ class DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT extends Output>
1507
1679
  {
1508
1680
  id: generateId(),
1509
1681
  timestamp: new Date(),
1510
- modelId: model.modelId,
1682
+ modelId: modelInfo.modelId,
1511
1683
  };
1512
1684
 
1513
1685
  // raw text as it comes from the provider. recorded for telemetry.
@@ -1,31 +0,0 @@
1
- import { StepResult } from '../generate-text/step-result';
2
- import { ToolSet } from '../generate-text/tool-set';
3
- import { LanguageModelUsage } from '../types/usage';
4
-
5
- /**
6
- * Callback that is set using the `onFinish` option.
7
- *
8
- * @param event - The event that is passed to the callback.
9
- */
10
- export type ToolLoopAgentOnFinishCallback<TOOLS extends ToolSet = {}> = (
11
- event: StepResult<TOOLS> & {
12
- /**
13
- * Details for all steps.
14
- */
15
- readonly steps: StepResult<TOOLS>[];
16
-
17
- /**
18
- * Total usage for all steps. This is the sum of the usage of all steps.
19
- */
20
- readonly totalUsage: LanguageModelUsage;
21
-
22
- /**
23
- * Context that is passed into tool execution.
24
- *
25
- * Experimental (can break in patch releases).
26
- *
27
- * @default undefined
28
- */
29
- experimental_context: unknown;
30
- },
31
- ) => PromiseLike<void> | void;
@@ -1,11 +0,0 @@
1
- import { StepResult } from '../generate-text/step-result';
2
- import { ToolSet } from '../generate-text/tool-set';
3
-
4
- /**
5
- * Callback that is set using the `onStepFinish` option.
6
- *
7
- * @param stepResult - The result of the step.
8
- */
9
- export type ToolLoopAgentOnStepFinishCallback<TOOLS extends ToolSet = {}> = (
10
- stepResult: StepResult<TOOLS>,
11
- ) => Promise<void> | void;