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.
@@ -54,6 +54,14 @@ import { DownloadFunction } from '../util/download/download-function';
54
54
  import { mergeObjects } from '../util/merge-objects';
55
55
  import { prepareRetries } from '../util/prepare-retries';
56
56
  import { VERSION } from '../version';
57
+ import type {
58
+ OnFinishEvent,
59
+ OnStartEvent,
60
+ OnStepFinishEvent,
61
+ OnStepStartEvent,
62
+ OnToolCallFinishEvent,
63
+ OnToolCallStartEvent,
64
+ } from './callback-events';
57
65
  import { collectToolApprovals } from './collect-tool-approvals';
58
66
  import { ContentPart } from './content-part';
59
67
  import { executeToolCall } from './execute-tool-call';
@@ -88,6 +96,14 @@ const originalGenerateId = createIdGenerator({
88
96
  size: 24,
89
97
  });
90
98
 
99
+ /**
100
+ * Include settings for generateText (requestBody and responseBody).
101
+ */
102
+ type GenerateTextIncludeSettings = {
103
+ requestBody?: boolean;
104
+ responseBody?: boolean;
105
+ };
106
+
91
107
  /**
92
108
  * Callback that is set using the `experimental_onStart` option.
93
109
  *
@@ -100,106 +116,9 @@ const originalGenerateId = createIdGenerator({
100
116
  export type GenerateTextOnStartCallback<
101
117
  TOOLS extends ToolSet = ToolSet,
102
118
  OUTPUT extends Output = Output,
103
- > = (event: {
104
- /** The model being used for generation. */
105
- readonly model: {
106
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
107
- readonly provider: string;
108
- /** The specific model identifier (e.g., 'gpt-4o'). */
109
- readonly modelId: string;
110
- };
111
-
112
- /** The system message(s) provided to the model. */
113
- readonly system:
114
- | string
115
- | SystemModelMessage
116
- | Array<SystemModelMessage>
117
- | undefined;
118
-
119
- /** The prompt string or array of messages if using the prompt option. */
120
- readonly prompt: string | Array<ModelMessage> | undefined;
121
-
122
- /** The messages array if using the messages option. */
123
- readonly messages: Array<ModelMessage> | undefined;
124
-
125
- /** The tools available for this generation. */
126
- readonly tools: TOOLS | undefined;
127
-
128
- /** The tool choice strategy for this generation. */
129
- readonly toolChoice: ToolChoice<NoInfer<TOOLS>> | undefined;
130
-
131
- /** Limits which tools are available for the model to call. */
132
- readonly activeTools: Array<keyof TOOLS> | undefined;
133
-
134
- /** Maximum number of tokens to generate. */
135
- readonly maxOutputTokens: number | undefined;
136
- /** Sampling temperature for generation. */
137
- readonly temperature: number | undefined;
138
- /** Top-p (nucleus) sampling parameter. */
139
- readonly topP: number | undefined;
140
- /** Top-k sampling parameter. */
141
- readonly topK: number | undefined;
142
- /** Presence penalty for generation. */
143
- readonly presencePenalty: number | undefined;
144
- /** Frequency penalty for generation. */
145
- readonly frequencyPenalty: number | undefined;
146
- /** Sequences that will stop generation. */
147
- readonly stopSequences: string[] | undefined;
148
- /** Random seed for reproducible generation. */
149
- readonly seed: number | undefined;
150
- /** Maximum number of retries for failed requests. */
151
- readonly maxRetries: number;
152
-
153
- /**
154
- * Timeout configuration for the generation.
155
- * Can be a number (milliseconds) or an object with totalMs, stepMs, chunkMs.
156
- */
157
- readonly timeout: TimeoutConfiguration | undefined;
158
-
159
- /** Additional HTTP headers sent with the request. */
160
- readonly headers: Record<string, string | undefined> | undefined;
161
-
162
- /** Additional provider-specific options. */
163
- readonly providerOptions: ProviderOptions | undefined;
164
-
165
- /**
166
- * Condition(s) for stopping the generation.
167
- * When the condition is an array, any of the conditions can be met to stop.
168
- */
169
- readonly stopWhen:
170
- | StopCondition<TOOLS>
171
- | Array<StopCondition<TOOLS>>
172
- | undefined;
173
-
174
- /** The output specification for structured outputs, if configured. */
175
- readonly output: OUTPUT | undefined;
176
-
177
- /** Abort signal for cancelling the operation. */
178
- readonly abortSignal: AbortSignal | undefined;
179
-
180
- /**
181
- * Settings for controlling what data is included in step results.
182
- * `requestBody` and `responseBody` control whether these are retained.
183
- */
184
- readonly include:
185
- | {
186
- requestBody?: boolean;
187
- responseBody?: boolean;
188
- }
189
- | undefined;
190
-
191
- /** Identifier from telemetry settings for grouping related operations. */
192
- readonly functionId: string | undefined;
193
-
194
- /** Additional metadata passed to the generation. */
195
- readonly metadata: Record<string, unknown> | undefined;
196
-
197
- /**
198
- * User-defined context object that flows through the entire generation lifecycle.
199
- * Can be accessed and modified in `prepareStep` and tool `execute` functions.
200
- */
201
- readonly experimental_context: unknown;
202
- }) => PromiseLike<void> | void;
119
+ > = (
120
+ event: OnStartEvent<TOOLS, OUTPUT, GenerateTextIncludeSettings>,
121
+ ) => PromiseLike<void> | void;
203
122
 
204
123
  /**
205
124
  * Callback that is set using the `experimental_onStepStart` option.
@@ -213,94 +132,9 @@ export type GenerateTextOnStartCallback<
213
132
  export type GenerateTextOnStepStartCallback<
214
133
  TOOLS extends ToolSet = ToolSet,
215
134
  OUTPUT extends Output = Output,
216
- > = (event: {
217
- /** Zero-based index of the current step. */
218
- readonly stepNumber: number;
219
-
220
- /** The model being used for this step. */
221
- readonly model: {
222
- /** The provider identifier. */
223
- readonly provider: string;
224
- /** The specific model identifier. */
225
- readonly modelId: string;
226
- };
227
-
228
- /**
229
- * The system message for this step.
230
- */
231
- readonly system:
232
- | string
233
- | SystemModelMessage
234
- | Array<SystemModelMessage>
235
- | undefined;
236
-
237
- /**
238
- * The messages that will be sent to the model for this step.
239
- * Uses the user-facing `ModelMessage` format.
240
- * May be overridden by prepareStep.
241
- */
242
- readonly messages: Array<ModelMessage>;
243
-
244
- /** The tools available for this generation. */
245
- readonly tools: TOOLS | undefined;
246
-
247
- /** The tool choice configuration for this step. */
248
- readonly toolChoice: LanguageModelV3ToolChoice | undefined;
249
-
250
- /** Limits which tools are available for this step. */
251
- readonly activeTools: Array<keyof TOOLS> | undefined;
252
-
253
- /** Array of results from previous steps (empty for first step). */
254
- readonly steps: ReadonlyArray<StepResult<TOOLS>>;
255
-
256
- /** Additional provider-specific options for this step. */
257
- readonly providerOptions: ProviderOptions | undefined;
258
-
259
- /**
260
- * Timeout configuration for the generation.
261
- * Can be a number (milliseconds) or an object with totalMs, stepMs, chunkMs.
262
- */
263
- readonly timeout: TimeoutConfiguration | undefined;
264
-
265
- /** Additional HTTP headers sent with the request. */
266
- readonly headers: Record<string, string | undefined> | undefined;
267
-
268
- /**
269
- * Condition(s) for stopping the generation.
270
- * When the condition is an array, any of the conditions can be met to stop.
271
- */
272
- readonly stopWhen:
273
- | StopCondition<TOOLS>
274
- | Array<StopCondition<TOOLS>>
275
- | undefined;
276
-
277
- /** The output specification for structured outputs, if configured. */
278
- readonly output: OUTPUT | undefined;
279
-
280
- /** Abort signal for cancelling the operation. */
281
- readonly abortSignal: AbortSignal | undefined;
282
-
283
- /**
284
- * Settings for controlling what data is included in step results.
285
- */
286
- readonly include:
287
- | {
288
- requestBody?: boolean;
289
- responseBody?: boolean;
290
- }
291
- | undefined;
292
-
293
- /** Identifier from telemetry settings for grouping related operations. */
294
- readonly functionId: string | undefined;
295
-
296
- /** Additional metadata from telemetry settings. */
297
- readonly metadata: Record<string, unknown> | undefined;
298
-
299
- /**
300
- * User-defined context object. May be updated from `prepareStep` between steps.
301
- */
302
- readonly experimental_context: unknown;
303
- }) => PromiseLike<void> | void;
135
+ > = (
136
+ event: OnStepStartEvent<TOOLS, OUTPUT, GenerateTextIncludeSettings>,
137
+ ) => PromiseLike<void> | void;
304
138
 
305
139
  /**
306
140
  * Callback that is set using the `experimental_onToolCallStart` option.
@@ -309,42 +143,10 @@ export type GenerateTextOnStepStartCallback<
309
143
  * Use this for logging tool invocations, tracking tool usage, or pre-execution validation.
310
144
  *
311
145
  * @param event - The event object containing tool call information.
312
- * @param event.stepNumber - Zero-based index of the current step where this tool call occurs.
313
- * @param event.model - Information about the model being used (provider and modelId).
314
- * @param event.toolCall - The full tool call object containing toolName, toolCallId, input, and metadata.
315
- * @param event.messages - The conversation messages available at tool execution time.
316
- * @param event.abortSignal - Signal for cancelling the operation.
317
- * @param event.functionId - Identifier from telemetry settings for grouping related operations.
318
- * @param event.metadata - Additional metadata from telemetry settings.
319
- * @param event.experimental_context - User-defined context object flowing through the generation.
320
146
  */
321
147
  export type GenerateTextOnToolCallStartCallback<
322
148
  TOOLS extends ToolSet = ToolSet,
323
- > = (event: {
324
- /** Zero-based index of the current step where this tool call occurs. May be undefined in streaming contexts. */
325
- readonly stepNumber: number | undefined;
326
- /** Information about the model being used. May be undefined in streaming contexts. */
327
- readonly model:
328
- | {
329
- /** The provider of the model. */
330
- readonly provider: string;
331
- /** The ID of the model. */
332
- readonly modelId: string;
333
- }
334
- | undefined;
335
- /** The full tool call object. */
336
- readonly toolCall: TypedToolCall<TOOLS>;
337
- /** The conversation messages available at tool execution time. */
338
- readonly messages: Array<ModelMessage>;
339
- /** Signal for cancelling the operation. */
340
- readonly abortSignal: AbortSignal | undefined;
341
- /** Identifier from telemetry settings for grouping related operations. */
342
- readonly functionId: string | undefined;
343
- /** Additional metadata from telemetry settings. */
344
- readonly metadata: Record<string, unknown> | undefined;
345
- /** User-defined context object flowing through the generation. */
346
- readonly experimental_context: unknown;
347
- }) => PromiseLike<void> | void;
149
+ > = (event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;
348
150
 
349
151
  /**
350
152
  * Callback that is set using the `experimental_onToolCallFinish` option.
@@ -357,65 +159,10 @@ export type GenerateTextOnToolCallStartCallback<
357
159
  * - When `success: false`: `error` contains the error, `output` is never present.
358
160
  *
359
161
  * @param event - The event object containing tool call result information.
360
- * @param event.stepNumber - Zero-based index of the current step where this tool call occurred.
361
- * @param event.model - Information about the model being used (provider and modelId).
362
- * @param event.toolCall - The full tool call object containing toolName, toolCallId, input, and metadata.
363
- * @param event.messages - The conversation messages available at tool execution time.
364
- * @param event.abortSignal - Signal for cancelling the operation.
365
- * @param event.durationMs - Execution time of the tool call in milliseconds.
366
- * @param event.functionId - Identifier from telemetry settings for grouping related operations.
367
- * @param event.metadata - Additional metadata from telemetry settings.
368
- * @param event.experimental_context - User-defined context object flowing through the generation.
369
- * @param event.success - Discriminator indicating whether the tool call succeeded.
370
- * @param event.output - The tool's return value (only present when `success: true`).
371
- * @param event.error - The error that occurred (only present when `success: false`).
372
162
  */
373
163
  export type GenerateTextOnToolCallFinishCallback<
374
164
  TOOLS extends ToolSet = ToolSet,
375
- > = (
376
- event: {
377
- /** Zero-based index of the current step where this tool call occurred. May be undefined in streaming contexts. */
378
- readonly stepNumber: number | undefined;
379
- /** Information about the model being used. May be undefined in streaming contexts. */
380
- readonly model:
381
- | {
382
- /** The provider of the model. */
383
- readonly provider: string;
384
- /** The ID of the model. */
385
- readonly modelId: string;
386
- }
387
- | undefined;
388
- /** The full tool call object. */
389
- readonly toolCall: TypedToolCall<TOOLS>;
390
- /** The conversation messages available at tool execution time. */
391
- readonly messages: Array<ModelMessage>;
392
- /** Signal for cancelling the operation. */
393
- readonly abortSignal: AbortSignal | undefined;
394
- /** Execution time of the tool call in milliseconds. */
395
- readonly durationMs: number;
396
- /** Identifier from telemetry settings for grouping related operations. */
397
- readonly functionId: string | undefined;
398
- /** Additional metadata from telemetry settings. */
399
- readonly metadata: Record<string, unknown> | undefined;
400
- /** User-defined context object flowing through the generation. */
401
- readonly experimental_context: unknown;
402
- } & (
403
- | {
404
- /** Indicates the tool call succeeded. */
405
- readonly success: true;
406
- /** The tool's return value. */
407
- readonly output: unknown;
408
- readonly error?: never;
409
- }
410
- | {
411
- /** Indicates the tool call failed. */
412
- readonly success: false;
413
- readonly output?: never;
414
- /** The error that occurred during tool execution. */
415
- readonly error: unknown;
416
- }
417
- ),
418
- ) => PromiseLike<void> | void;
165
+ > = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;
419
166
 
420
167
  /**
421
168
  * Callback that is set using the `onStepFinish` option.
@@ -426,7 +173,7 @@ export type GenerateTextOnToolCallFinishCallback<
426
173
  * @param stepResult - The result of the step.
427
174
  */
428
175
  export type GenerateTextOnStepFinishCallback<TOOLS extends ToolSet> = (
429
- stepResult: StepResult<TOOLS>,
176
+ event: OnStepFinishEvent<TOOLS>,
430
177
  ) => Promise<void> | void;
431
178
 
432
179
  /**
@@ -437,60 +184,9 @@ export type GenerateTextOnStepFinishCallback<TOOLS extends ToolSet> = (
437
184
  * aggregated data from all steps.
438
185
  *
439
186
  * @param event - The final result along with aggregated step data.
440
- *
441
- * Inherited from StepResult (reflects the final step):
442
- * @param event.content - Array of content parts from the final step.
443
- * @param event.text - The generated text from the final step.
444
- * @param event.reasoning - Array of reasoning parts from the final step.
445
- * @param event.reasoningText - Combined reasoning text from the final step.
446
- * @param event.files - Array of generated files from the final step.
447
- * @param event.sources - Array of sources from the final step.
448
- * @param event.toolCalls - Array of tool calls from the final step.
449
- * @param event.toolResults - Array of tool results from the final step.
450
- * @param event.finishReason - Finish reason from the final step.
451
- * @param event.usage - Token usage from the final step only.
452
- * @param event.warnings - Warnings from the final step.
453
- * @param event.request - Request metadata from the final step.
454
- * @param event.response - Response metadata from the final step.
455
- * @param event.providerMetadata - Provider metadata from the final step.
456
- *
457
- * Additional properties:
458
- * @param event.steps - Array containing results from all steps in the generation.
459
- * @param event.totalUsage - Aggregated token usage across all steps.
460
- * @param event.experimental_context - The final state of the user-defined context object.
461
- * @param event.functionId - Identifier from telemetry settings for grouping related operations.
462
- * @param event.metadata - Additional metadata from telemetry settings.
463
187
  */
464
188
  export type GenerateTextOnFinishCallback<TOOLS extends ToolSet> = (
465
- event: StepResult<TOOLS> & {
466
- /**
467
- * Array containing results from all steps in the generation.
468
- */
469
- readonly steps: StepResult<TOOLS>[];
470
-
471
- /**
472
- * Aggregated token usage across all steps.
473
- * This is the sum of the usage from each individual step.
474
- */
475
- readonly totalUsage: LanguageModelUsage;
476
-
477
- /**
478
- * The final state of the user-defined context object.
479
- * This reflects any modifications made during the generation lifecycle
480
- * via `prepareStep` or tool execution.
481
- *
482
- * Experimental (can break in patch releases).
483
- *
484
- * @default undefined
485
- */
486
- experimental_context: unknown;
487
-
488
- /** Identifier from telemetry settings for grouping related operations. */
489
- readonly functionId: string | undefined;
490
-
491
- /** Additional metadata from telemetry settings. */
492
- readonly metadata: Record<string, unknown> | undefined;
493
- },
189
+ event: OnFinishEvent<TOOLS>,
494
190
  ) => PromiseLike<void> | void;
495
191
 
496
192
  /**
@@ -775,6 +471,8 @@ export async function generateText<
775
471
  settings: { ...callSettings, maxRetries },
776
472
  });
777
473
 
474
+ const modelInfo = { provider: model.provider, modelId: model.modelId };
475
+
778
476
  const initialPrompt = await standardizePrompt({
779
477
  system,
780
478
  prompt,
@@ -783,7 +481,7 @@ export async function generateText<
783
481
 
784
482
  try {
785
483
  await onStart?.({
786
- model: { provider: model.provider, modelId: model.modelId },
484
+ model: modelInfo,
787
485
  system,
788
486
  prompt,
789
487
  messages,
@@ -863,7 +561,7 @@ export async function generateText<
863
561
  abortSignal: mergedAbortSignal,
864
562
  experimental_context,
865
563
  stepNumber: 0,
866
- model: { provider: model.provider, modelId: model.modelId },
564
+ model: modelInfo,
867
565
  onToolCallStart: onToolCallStart,
868
566
  onToolCallFinish: onToolCallFinish,
869
567
  });
@@ -976,6 +674,10 @@ export async function generateText<
976
674
  const stepModel = resolveLanguageModel(
977
675
  prepareStepResult?.model ?? model,
978
676
  );
677
+ const stepModelInfo = {
678
+ provider: stepModel.provider,
679
+ modelId: stepModel.modelId,
680
+ };
979
681
 
980
682
  const promptMessages = await convertToLanguageModelPrompt({
981
683
  prompt: {
@@ -1013,10 +715,7 @@ export async function generateText<
1013
715
  try {
1014
716
  await onStepStart?.({
1015
717
  stepNumber: steps.length,
1016
- model: {
1017
- provider: stepModel.provider,
1018
- modelId: stepModel.modelId,
1019
- },
718
+ model: stepModelInfo,
1020
719
  system: stepSystem,
1021
720
  messages: stepMessages,
1022
721
  tools,
@@ -1258,10 +957,7 @@ export async function generateText<
1258
957
  abortSignal: mergedAbortSignal,
1259
958
  experimental_context,
1260
959
  stepNumber: steps.length,
1261
- model: {
1262
- provider: stepModel.provider,
1263
- modelId: stepModel.modelId,
1264
- },
960
+ model: stepModelInfo,
1265
961
  onToolCallStart: onToolCallStart,
1266
962
  onToolCallFinish: onToolCallFinish,
1267
963
  })),
@@ -1337,10 +1033,7 @@ export async function generateText<
1337
1033
 
1338
1034
  const currentStepResult: StepResult<TOOLS> = new DefaultStepResult({
1339
1035
  stepNumber,
1340
- model: {
1341
- provider: stepModel.provider,
1342
- modelId: stepModel.modelId,
1343
- },
1036
+ model: stepModelInfo,
1344
1037
  functionId: telemetry?.functionId,
1345
1038
  metadata: telemetry?.metadata as
1346
1039
  | Record<string, unknown>
@@ -1358,8 +1051,8 @@ export async function generateText<
1358
1051
 
1359
1052
  logWarnings({
1360
1053
  warnings: currentModelResponse.warnings ?? [],
1361
- provider: stepModel.provider,
1362
- model: stepModel.modelId,
1054
+ provider: stepModelInfo.provider,
1055
+ model: stepModelInfo.modelId,
1363
1056
  });
1364
1057
 
1365
1058
  steps.push(currentStepResult);
@@ -30,7 +30,11 @@ export {
30
30
  type StreamTextOnChunkCallback,
31
31
  type StreamTextOnErrorCallback,
32
32
  type StreamTextOnFinishCallback,
33
+ type StreamTextOnStartCallback,
33
34
  type StreamTextOnStepFinishCallback,
35
+ type StreamTextOnStepStartCallback,
36
+ type StreamTextOnToolCallFinishCallback,
37
+ type StreamTextOnToolCallStartCallback,
34
38
  type StreamTextTransform,
35
39
  } from './stream-text';
36
40
  export type {
@@ -12,6 +12,10 @@ import { FinishReason, LanguageModelUsage, ProviderMetadata } from '../types';
12
12
  import { Source } from '../types/language-model';
13
13
  import { asLanguageModelUsage } from '../types/usage';
14
14
  import { executeToolCall } from './execute-tool-call';
15
+ import {
16
+ StreamTextOnToolCallFinishCallback,
17
+ StreamTextOnToolCallStartCallback,
18
+ } from './stream-text';
15
19
  import { DefaultGeneratedFileWithType, GeneratedFile } from './generated-file';
16
20
  import { isApprovalNeeded } from './is-approval-needed';
17
21
  import { parseToolCall } from './parse-tool-call';
@@ -116,6 +120,10 @@ export function runToolsTransformation<TOOLS extends ToolSet>({
116
120
  repairToolCall,
117
121
  experimental_context,
118
122
  generateId,
123
+ stepNumber,
124
+ model,
125
+ onToolCallStart,
126
+ onToolCallFinish,
119
127
  }: {
120
128
  tools: TOOLS | undefined;
121
129
  generatorStream: ReadableStream<LanguageModelV3StreamPart>;
@@ -127,6 +135,10 @@ export function runToolsTransformation<TOOLS extends ToolSet>({
127
135
  repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;
128
136
  experimental_context: unknown;
129
137
  generateId: IdGenerator;
138
+ stepNumber?: number;
139
+ model?: { provider: string; modelId: string };
140
+ onToolCallStart?: StreamTextOnToolCallStartCallback<TOOLS>;
141
+ onToolCallFinish?: StreamTextOnToolCallFinishCallback<TOOLS>;
130
142
  }): ReadableStream<SingleRequestTextStreamPart<TOOLS>> {
131
143
  // tool results stream
132
144
  let toolResultsStreamController: ReadableStreamDefaultController<
@@ -323,6 +335,10 @@ export function runToolsTransformation<TOOLS extends ToolSet>({
323
335
  messages,
324
336
  abortSignal,
325
337
  experimental_context,
338
+ stepNumber,
339
+ model,
340
+ onToolCallStart,
341
+ onToolCallFinish,
326
342
  onPreliminaryToolResult: result => {
327
343
  toolResultsStreamController!.enqueue(result);
328
344
  },