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.
package/dist/index.d.mts CHANGED
@@ -4,7 +4,7 @@ import * as _ai_sdk_provider_utils from '@ai-sdk/provider-utils';
4
4
  import { Tool, InferToolInput, InferToolOutput, FlexibleSchema, InferSchema, SystemModelMessage, ModelMessage, AssistantModelMessage, ToolModelMessage, ReasoningPart, ProviderOptions, UserModelMessage, IdGenerator, ToolCall, MaybePromiseLike, TextPart, FilePart, Resolvable, FetchFunction, DataContent } from '@ai-sdk/provider-utils';
5
5
  export { AssistantContent, AssistantModelMessage, DataContent, DownloadError, FilePart, FlexibleSchema, IdGenerator, ImagePart, InferSchema, InferToolInput, InferToolOutput, ModelMessage, Schema, SystemModelMessage, TextPart, Tool, ToolApprovalRequest, ToolApprovalResponse, ToolCallOptions, ToolCallPart, ToolContent, ToolExecuteFunction, ToolExecutionOptions, ToolModelMessage, ToolResultPart, UserContent, UserModelMessage, asSchema, createIdGenerator, dynamicTool, generateId, jsonSchema, parseJsonEventStream, tool, zodSchema } from '@ai-sdk/provider-utils';
6
6
  import * as _ai_sdk_provider from '@ai-sdk/provider';
7
- import { EmbeddingModelV3, EmbeddingModelV2, EmbeddingModelV3Embedding, EmbeddingModelV3Middleware, ImageModelV3, ImageModelV2, ImageModelV3ProviderMetadata, ImageModelV2ProviderMetadata, ImageModelV3Middleware, JSONValue as JSONValue$1, LanguageModelV3, LanguageModelV2, SharedV3Warning, LanguageModelV3Source, LanguageModelV3Middleware, RerankingModelV3, SharedV3ProviderMetadata, SpeechModelV3, SpeechModelV2, TranscriptionModelV3, TranscriptionModelV2, JSONObject, ImageModelV3Usage, AISDKError, LanguageModelV3ToolCall, JSONSchema7, LanguageModelV3ToolChoice, LanguageModelV3CallOptions, JSONParseError, TypeValidationError, Experimental_VideoModelV3, EmbeddingModelV3CallOptions, ProviderV3, ProviderV2, NoSuchModelError } from '@ai-sdk/provider';
7
+ import { EmbeddingModelV3, EmbeddingModelV2, EmbeddingModelV3Embedding, EmbeddingModelV3Middleware, ImageModelV3, ImageModelV2, ImageModelV3ProviderMetadata, ImageModelV2ProviderMetadata, ImageModelV3Middleware, JSONValue as JSONValue$1, LanguageModelV3, LanguageModelV2, SharedV3Warning, LanguageModelV3Source, LanguageModelV3Middleware, RerankingModelV3, SharedV3ProviderMetadata, SpeechModelV3, SpeechModelV2, TranscriptionModelV3, TranscriptionModelV2, JSONObject, ImageModelV3Usage, LanguageModelV3ToolChoice, AISDKError, LanguageModelV3ToolCall, JSONSchema7, LanguageModelV3CallOptions, JSONParseError, TypeValidationError, Experimental_VideoModelV3, EmbeddingModelV3CallOptions, ProviderV3, ProviderV2, NoSuchModelError } from '@ai-sdk/provider';
8
8
  export { AISDKError, APICallError, EmptyResponseBodyError, InvalidPromptError, InvalidResponseDataError, JSONParseError, JSONSchema7, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, TooManyEmbeddingValuesForCallError, TypeValidationError, UnsupportedFunctionalityError } from '@ai-sdk/provider';
9
9
  import { AttributeValue, Tracer } from '@opentelemetry/api';
10
10
  import { ServerResponse } from 'node:http';
@@ -896,164 +896,32 @@ type StepResult<TOOLS extends ToolSet> = {
896
896
  readonly providerMetadata: ProviderMetadata | undefined;
897
897
  };
898
898
 
899
- /**
900
- * Function that you can use to provide different settings for a step.
901
- *
902
- * @param options - The options for the step.
903
- * @param options.steps - The steps that have been executed so far.
904
- * @param options.stepNumber - The number of the step that is being executed.
905
- * @param options.model - The model that is being used.
906
- * @param options.messages - The messages that will be sent to the model for the current step.
907
- * @param options.experimental_context - The context passed via the experimental_context setting (experimental).
908
- *
909
- * @returns An object that contains the settings for the step.
910
- * If you return undefined (or for undefined settings), the settings from the outer level will be used.
911
- */
912
- type PrepareStepFunction<TOOLS extends Record<string, Tool> = Record<string, Tool>> = (options: {
913
- /**
914
- * The steps that have been executed so far.
915
- */
916
- steps: Array<StepResult<NoInfer<TOOLS>>>;
917
- /**
918
- * The number of the step that is being executed.
919
- */
920
- stepNumber: number;
921
- /**
922
- * The model instance that is being used for this step.
923
- */
924
- model: LanguageModel;
925
- /**
926
- * The messages that will be sent to the model for the current step.
927
- */
928
- messages: Array<ModelMessage>;
929
- /**
930
- * The context passed via the experimental_context setting (experimental).
931
- */
932
- experimental_context: unknown;
933
- }) => PromiseLike<PrepareStepResult<TOOLS>> | PrepareStepResult<TOOLS>;
934
- /**
935
- * The result type returned by a {@link PrepareStepFunction},
936
- * allowing per-step overrides of model, tools, or messages.
937
- */
938
- type PrepareStepResult<TOOLS extends Record<string, Tool> = Record<string, Tool>> = {
939
- /**
940
- * Optionally override which LanguageModel instance is used for this step.
941
- */
942
- model?: LanguageModel;
943
- /**
944
- * Optionally set which tool the model must call, or provide tool call configuration
945
- * for this step.
946
- */
947
- toolChoice?: ToolChoice<NoInfer<TOOLS>>;
948
- /**
949
- * If provided, only these tools are enabled/available for this step.
950
- */
951
- activeTools?: Array<keyof NoInfer<TOOLS>>;
952
- /**
953
- * Optionally override the system message(s) sent to the model for this step.
954
- */
955
- system?: string | SystemModelMessage | Array<SystemModelMessage>;
956
- /**
957
- * Optionally override the full set of messages sent to the model
958
- * for this step.
959
- */
960
- messages?: Array<ModelMessage>;
961
- /**
962
- * Context that is passed into tool execution. Experimental.
963
- *
964
- * Changing the context will affect the context in this step
965
- * and all subsequent steps.
966
- */
967
- experimental_context?: unknown;
968
- /**
969
- * Additional provider-specific options for this step.
970
- *
971
- * Can be used to pass provider-specific configuration such as
972
- * container IDs for Anthropic's code execution.
973
- */
974
- providerOptions?: ProviderOptions;
975
- } | undefined;
976
-
977
899
  type StopCondition<TOOLS extends ToolSet> = (options: {
978
900
  steps: Array<StepResult<TOOLS>>;
979
901
  }) => PromiseLike<boolean> | boolean;
980
902
  declare function stepCountIs(stepCount: number): StopCondition<any>;
981
903
  declare function hasToolCall(toolName: string): StopCondition<any>;
982
904
 
983
- declare const systemModelMessageSchema: z.ZodType<SystemModelMessage>;
984
- declare const userModelMessageSchema: z.ZodType<UserModelMessage>;
985
- declare const assistantModelMessageSchema: z.ZodType<AssistantModelMessage>;
986
- declare const toolModelMessageSchema: z.ZodType<ToolModelMessage>;
987
- declare const modelMessageSchema: z.ZodType<ModelMessage>;
988
-
989
- declare const symbol$j: unique symbol;
990
- declare class InvalidToolInputError extends AISDKError {
991
- private readonly [symbol$j];
992
- readonly toolName: string;
993
- readonly toolInput: string;
994
- constructor({ toolInput, toolName, cause, message, }: {
995
- message?: string;
996
- toolInput: string;
997
- toolName: string;
998
- cause: unknown;
999
- });
1000
- static isInstance(error: unknown): error is InvalidToolInputError;
1001
- }
1002
-
1003
- declare const symbol$i: unique symbol;
1004
- declare class NoSuchToolError extends AISDKError {
1005
- private readonly [symbol$i];
1006
- readonly toolName: string;
1007
- readonly availableTools: string[] | undefined;
1008
- constructor({ toolName, availableTools, message, }: {
1009
- toolName: string;
1010
- availableTools?: string[] | undefined;
1011
- message?: string;
1012
- });
1013
- static isInstance(error: unknown): error is NoSuchToolError;
1014
- }
1015
-
1016
905
  /**
1017
- * A function that attempts to repair a tool call that failed to parse.
1018
- *
1019
- * It receives the error and the context as arguments and returns the repair
1020
- * tool call JSON as text.
1021
- *
1022
- * @param options.system - The system prompt.
1023
- * @param options.messages - The messages in the current generation step.
1024
- * @param options.toolCall - The tool call that failed to parse.
1025
- * @param options.tools - The tools that are available.
1026
- * @param options.inputSchema - A function that returns the JSON Schema for a tool.
1027
- * @param options.error - The error that occurred while parsing the tool call.
906
+ * Common model information used across callback events.
1028
907
  */
1029
- type ToolCallRepairFunction<TOOLS extends ToolSet> = (options: {
1030
- system: string | SystemModelMessage | Array<SystemModelMessage> | undefined;
1031
- messages: ModelMessage[];
1032
- toolCall: LanguageModelV3ToolCall;
1033
- tools: TOOLS;
1034
- inputSchema: (options: {
1035
- toolName: string;
1036
- }) => PromiseLike<JSONSchema7>;
1037
- error: NoSuchToolError | InvalidToolInputError;
1038
- }) => Promise<LanguageModelV3ToolCall | null>;
1039
-
908
+ interface CallbackModelInfo {
909
+ /** The provider identifier (e.g., 'openai', 'anthropic'). */
910
+ readonly provider: string;
911
+ /** The specific model identifier (e.g., 'gpt-4o'). */
912
+ readonly modelId: string;
913
+ }
1040
914
  /**
1041
- * Callback that is set using the `experimental_onStart` option.
915
+ * Event passed to the `onStart` callback.
1042
916
  *
1043
- * Called when the generateText operation begins, before any LLM calls.
1044
- * Use this callback for logging, analytics, or initializing state at the
1045
- * start of a generation.
1046
- *
1047
- * @param event - The event object containing generation configuration.
917
+ * Called when the generation operation begins, before any LLM calls.
1048
918
  */
1049
- type GenerateTextOnStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: {
919
+ interface OnStartEvent<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output, INCLUDE = {
920
+ requestBody?: boolean;
921
+ responseBody?: boolean;
922
+ }> {
1050
923
  /** The model being used for generation. */
1051
- readonly model: {
1052
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
1053
- readonly provider: string;
1054
- /** The specific model identifier (e.g., 'gpt-4o'). */
1055
- readonly modelId: string;
1056
- };
924
+ readonly model: CallbackModelInfo;
1057
925
  /** The system message(s) provided to the model. */
1058
926
  readonly system: string | SystemModelMessage | Array<SystemModelMessage> | undefined;
1059
927
  /** The prompt string or array of messages if using the prompt option. */
@@ -1104,12 +972,8 @@ type GenerateTextOnStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends
1104
972
  readonly abortSignal: AbortSignal | undefined;
1105
973
  /**
1106
974
  * Settings for controlling what data is included in step results.
1107
- * `requestBody` and `responseBody` control whether these are retained.
1108
975
  */
1109
- readonly include: {
1110
- requestBody?: boolean;
1111
- responseBody?: boolean;
1112
- } | undefined;
976
+ readonly include: INCLUDE | undefined;
1113
977
  /** Identifier from telemetry settings for grouping related operations. */
1114
978
  readonly functionId: string | undefined;
1115
979
  /** Additional metadata passed to the generation. */
@@ -1119,26 +983,21 @@ type GenerateTextOnStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends
1119
983
  * Can be accessed and modified in `prepareStep` and tool `execute` functions.
1120
984
  */
1121
985
  readonly experimental_context: unknown;
1122
- }) => PromiseLike<void> | void;
986
+ }
1123
987
  /**
1124
- * Callback that is set using the `experimental_onStepStart` option.
988
+ * Event passed to the `onStepStart` callback.
1125
989
  *
1126
990
  * Called when a step (LLM call) begins, before the provider is called.
1127
- * Each step represents a single LLM invocation. Multiple steps occur when
1128
- * using tool calls (the model may be called multiple times in a loop).
1129
- *
1130
- * @param event - The event object containing step configuration.
991
+ * Each step represents a single LLM invocation.
1131
992
  */
1132
- type GenerateTextOnStepStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: {
993
+ interface OnStepStartEvent<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output, INCLUDE = {
994
+ requestBody?: boolean;
995
+ responseBody?: boolean;
996
+ }> {
1133
997
  /** Zero-based index of the current step. */
1134
998
  readonly stepNumber: number;
1135
999
  /** The model being used for this step. */
1136
- readonly model: {
1137
- /** The provider identifier. */
1138
- readonly provider: string;
1139
- /** The specific model identifier. */
1140
- readonly modelId: string;
1141
- };
1000
+ readonly model: CallbackModelInfo;
1142
1001
  /**
1143
1002
  * The system message for this step.
1144
1003
  */
@@ -1178,10 +1037,7 @@ type GenerateTextOnStepStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT ext
1178
1037
  /**
1179
1038
  * Settings for controlling what data is included in step results.
1180
1039
  */
1181
- readonly include: {
1182
- requestBody?: boolean;
1183
- responseBody?: boolean;
1184
- } | undefined;
1040
+ readonly include: INCLUDE | undefined;
1185
1041
  /** Identifier from telemetry settings for grouping related operations. */
1186
1042
  readonly functionId: string | undefined;
1187
1043
  /** Additional metadata from telemetry settings. */
@@ -1190,33 +1046,17 @@ type GenerateTextOnStepStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT ext
1190
1046
  * User-defined context object. May be updated from `prepareStep` between steps.
1191
1047
  */
1192
1048
  readonly experimental_context: unknown;
1193
- }) => PromiseLike<void> | void;
1049
+ }
1194
1050
  /**
1195
- * Callback that is set using the `experimental_onToolCallStart` option.
1051
+ * Event passed to the `onToolCallStart` callback.
1196
1052
  *
1197
1053
  * Called when a tool execution begins, before the tool's `execute` function is invoked.
1198
- * Use this for logging tool invocations, tracking tool usage, or pre-execution validation.
1199
- *
1200
- * @param event - The event object containing tool call information.
1201
- * @param event.stepNumber - Zero-based index of the current step where this tool call occurs.
1202
- * @param event.model - Information about the model being used (provider and modelId).
1203
- * @param event.toolCall - The full tool call object containing toolName, toolCallId, input, and metadata.
1204
- * @param event.messages - The conversation messages available at tool execution time.
1205
- * @param event.abortSignal - Signal for cancelling the operation.
1206
- * @param event.functionId - Identifier from telemetry settings for grouping related operations.
1207
- * @param event.metadata - Additional metadata from telemetry settings.
1208
- * @param event.experimental_context - User-defined context object flowing through the generation.
1209
- */
1210
- type GenerateTextOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> = (event: {
1211
- /** Zero-based index of the current step where this tool call occurs. May be undefined in streaming contexts. */
1054
+ */
1055
+ interface OnToolCallStartEvent<TOOLS extends ToolSet = ToolSet> {
1056
+ /** Zero-based index of the current step where this tool call occurs. */
1212
1057
  readonly stepNumber: number | undefined;
1213
- /** Information about the model being used. May be undefined in streaming contexts. */
1214
- readonly model: {
1215
- /** The provider of the model. */
1216
- readonly provider: string;
1217
- /** The ID of the model. */
1218
- readonly modelId: string;
1219
- } | undefined;
1058
+ /** The model being used for this step. */
1059
+ readonly model: CallbackModelInfo | undefined;
1220
1060
  /** The full tool call object. */
1221
1061
  readonly toolCall: TypedToolCall<TOOLS>;
1222
1062
  /** The conversation messages available at tool execution time. */
@@ -1229,41 +1069,18 @@ type GenerateTextOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> = (eve
1229
1069
  readonly metadata: Record<string, unknown> | undefined;
1230
1070
  /** User-defined context object flowing through the generation. */
1231
1071
  readonly experimental_context: unknown;
1232
- }) => PromiseLike<void> | void;
1072
+ }
1233
1073
  /**
1234
- * Callback that is set using the `experimental_onToolCallFinish` option.
1074
+ * Event passed to the `onToolCallFinish` callback.
1235
1075
  *
1236
1076
  * Called when a tool execution completes, either successfully or with an error.
1237
- * Use this for logging tool results, tracking execution time, or error handling.
1238
- *
1239
- * The event uses a discriminated union on the `success` field:
1240
- * - When `success: true`: `output` contains the tool result, `error` is never present.
1241
- * - When `success: false`: `error` contains the error, `output` is never present.
1242
- *
1243
- * @param event - The event object containing tool call result information.
1244
- * @param event.stepNumber - Zero-based index of the current step where this tool call occurred.
1245
- * @param event.model - Information about the model being used (provider and modelId).
1246
- * @param event.toolCall - The full tool call object containing toolName, toolCallId, input, and metadata.
1247
- * @param event.messages - The conversation messages available at tool execution time.
1248
- * @param event.abortSignal - Signal for cancelling the operation.
1249
- * @param event.durationMs - Execution time of the tool call in milliseconds.
1250
- * @param event.functionId - Identifier from telemetry settings for grouping related operations.
1251
- * @param event.metadata - Additional metadata from telemetry settings.
1252
- * @param event.experimental_context - User-defined context object flowing through the generation.
1253
- * @param event.success - Discriminator indicating whether the tool call succeeded.
1254
- * @param event.output - The tool's return value (only present when `success: true`).
1255
- * @param event.error - The error that occurred (only present when `success: false`).
1256
- */
1257
- type GenerateTextOnToolCallFinishCallback<TOOLS extends ToolSet = ToolSet> = (event: {
1258
- /** Zero-based index of the current step where this tool call occurred. May be undefined in streaming contexts. */
1077
+ * Uses a discriminated union on the `success` field.
1078
+ */
1079
+ type OnToolCallFinishEvent<TOOLS extends ToolSet = ToolSet> = {
1080
+ /** Zero-based index of the current step where this tool call occurred. */
1259
1081
  readonly stepNumber: number | undefined;
1260
- /** Information about the model being used. May be undefined in streaming contexts. */
1261
- readonly model: {
1262
- /** The provider of the model. */
1263
- readonly provider: string;
1264
- /** The ID of the model. */
1265
- readonly modelId: string;
1266
- } | undefined;
1082
+ /** The model being used for this step. */
1083
+ readonly model: CallbackModelInfo | undefined;
1267
1084
  /** The full tool call object. */
1268
1085
  readonly toolCall: TypedToolCall<TOOLS>;
1269
1086
  /** The conversation messages available at tool execution time. */
@@ -1290,62 +1107,27 @@ type GenerateTextOnToolCallFinishCallback<TOOLS extends ToolSet = ToolSet> = (ev
1290
1107
  readonly output?: never;
1291
1108
  /** The error that occurred during tool execution. */
1292
1109
  readonly error: unknown;
1293
- })) => PromiseLike<void> | void;
1110
+ });
1294
1111
  /**
1295
- * Callback that is set using the `onStepFinish` option.
1112
+ * Event passed to the `onStepFinish` callback.
1296
1113
  *
1297
- * Called when a step (LLM call) completes. The event includes all step result
1298
- * properties (text, tool calls, usage, etc.) along with additional metadata.
1299
- *
1300
- * @param stepResult - The result of the step.
1114
+ * Called when a step (LLM call) completes.
1115
+ * This is simply the StepResult for that step.
1301
1116
  */
1302
- type GenerateTextOnStepFinishCallback<TOOLS extends ToolSet> = (stepResult: StepResult<TOOLS>) => Promise<void> | void;
1117
+ type OnStepFinishEvent<TOOLS extends ToolSet = ToolSet> = StepResult<TOOLS>;
1303
1118
  /**
1304
- * Callback that is set using the `onFinish` option.
1119
+ * Event passed to the `onFinish` callback.
1305
1120
  *
1306
1121
  * Called when the entire generation completes (all steps finished).
1307
- * The event includes the final step's result properties along with
1308
- * aggregated data from all steps.
1309
- *
1310
- * @param event - The final result along with aggregated step data.
1311
- *
1312
- * Inherited from StepResult (reflects the final step):
1313
- * @param event.content - Array of content parts from the final step.
1314
- * @param event.text - The generated text from the final step.
1315
- * @param event.reasoning - Array of reasoning parts from the final step.
1316
- * @param event.reasoningText - Combined reasoning text from the final step.
1317
- * @param event.files - Array of generated files from the final step.
1318
- * @param event.sources - Array of sources from the final step.
1319
- * @param event.toolCalls - Array of tool calls from the final step.
1320
- * @param event.toolResults - Array of tool results from the final step.
1321
- * @param event.finishReason - Finish reason from the final step.
1322
- * @param event.usage - Token usage from the final step only.
1323
- * @param event.warnings - Warnings from the final step.
1324
- * @param event.request - Request metadata from the final step.
1325
- * @param event.response - Response metadata from the final step.
1326
- * @param event.providerMetadata - Provider metadata from the final step.
1327
- *
1328
- * Additional properties:
1329
- * @param event.steps - Array containing results from all steps in the generation.
1330
- * @param event.totalUsage - Aggregated token usage across all steps.
1331
- * @param event.experimental_context - The final state of the user-defined context object.
1332
- * @param event.functionId - Identifier from telemetry settings for grouping related operations.
1333
- * @param event.metadata - Additional metadata from telemetry settings.
1334
- */
1335
- type GenerateTextOnFinishCallback<TOOLS extends ToolSet> = (event: StepResult<TOOLS> & {
1336
- /**
1337
- * Array containing results from all steps in the generation.
1338
- */
1122
+ * Includes the final step's result along with aggregated data from all steps.
1123
+ */
1124
+ type OnFinishEvent<TOOLS extends ToolSet = ToolSet> = StepResult<TOOLS> & {
1125
+ /** Array containing results from all steps in the generation. */
1339
1126
  readonly steps: StepResult<TOOLS>[];
1340
- /**
1341
- * Aggregated token usage across all steps.
1342
- * This is the sum of the usage from each individual step.
1343
- */
1127
+ /** Aggregated token usage across all steps. */
1344
1128
  readonly totalUsage: LanguageModelUsage;
1345
1129
  /**
1346
1130
  * The final state of the user-defined context object.
1347
- * This reflects any modifications made during the generation lifecycle
1348
- * via `prepareStep` or tool execution.
1349
1131
  *
1350
1132
  * Experimental (can break in patch releases).
1351
1133
  *
@@ -1356,7 +1138,211 @@ type GenerateTextOnFinishCallback<TOOLS extends ToolSet> = (event: StepResult<TO
1356
1138
  readonly functionId: string | undefined;
1357
1139
  /** Additional metadata from telemetry settings. */
1358
1140
  readonly metadata: Record<string, unknown> | undefined;
1359
- }) => PromiseLike<void> | void;
1141
+ };
1142
+
1143
+ /**
1144
+ * Function that you can use to provide different settings for a step.
1145
+ *
1146
+ * @param options - The options for the step.
1147
+ * @param options.steps - The steps that have been executed so far.
1148
+ * @param options.stepNumber - The number of the step that is being executed.
1149
+ * @param options.model - The model that is being used.
1150
+ * @param options.messages - The messages that will be sent to the model for the current step.
1151
+ * @param options.experimental_context - The context passed via the experimental_context setting (experimental).
1152
+ *
1153
+ * @returns An object that contains the settings for the step.
1154
+ * If you return undefined (or for undefined settings), the settings from the outer level will be used.
1155
+ */
1156
+ type PrepareStepFunction<TOOLS extends Record<string, Tool> = Record<string, Tool>> = (options: {
1157
+ /**
1158
+ * The steps that have been executed so far.
1159
+ */
1160
+ steps: Array<StepResult<NoInfer<TOOLS>>>;
1161
+ /**
1162
+ * The number of the step that is being executed.
1163
+ */
1164
+ stepNumber: number;
1165
+ /**
1166
+ * The model instance that is being used for this step.
1167
+ */
1168
+ model: LanguageModel;
1169
+ /**
1170
+ * The messages that will be sent to the model for the current step.
1171
+ */
1172
+ messages: Array<ModelMessage>;
1173
+ /**
1174
+ * The context passed via the experimental_context setting (experimental).
1175
+ */
1176
+ experimental_context: unknown;
1177
+ }) => PromiseLike<PrepareStepResult<TOOLS>> | PrepareStepResult<TOOLS>;
1178
+ /**
1179
+ * The result type returned by a {@link PrepareStepFunction},
1180
+ * allowing per-step overrides of model, tools, or messages.
1181
+ */
1182
+ type PrepareStepResult<TOOLS extends Record<string, Tool> = Record<string, Tool>> = {
1183
+ /**
1184
+ * Optionally override which LanguageModel instance is used for this step.
1185
+ */
1186
+ model?: LanguageModel;
1187
+ /**
1188
+ * Optionally set which tool the model must call, or provide tool call configuration
1189
+ * for this step.
1190
+ */
1191
+ toolChoice?: ToolChoice<NoInfer<TOOLS>>;
1192
+ /**
1193
+ * If provided, only these tools are enabled/available for this step.
1194
+ */
1195
+ activeTools?: Array<keyof NoInfer<TOOLS>>;
1196
+ /**
1197
+ * Optionally override the system message(s) sent to the model for this step.
1198
+ */
1199
+ system?: string | SystemModelMessage | Array<SystemModelMessage>;
1200
+ /**
1201
+ * Optionally override the full set of messages sent to the model
1202
+ * for this step.
1203
+ */
1204
+ messages?: Array<ModelMessage>;
1205
+ /**
1206
+ * Context that is passed into tool execution. Experimental.
1207
+ *
1208
+ * Changing the context will affect the context in this step
1209
+ * and all subsequent steps.
1210
+ */
1211
+ experimental_context?: unknown;
1212
+ /**
1213
+ * Additional provider-specific options for this step.
1214
+ *
1215
+ * Can be used to pass provider-specific configuration such as
1216
+ * container IDs for Anthropic's code execution.
1217
+ */
1218
+ providerOptions?: ProviderOptions;
1219
+ } | undefined;
1220
+
1221
+ declare const symbol$j: unique symbol;
1222
+ declare class InvalidToolInputError extends AISDKError {
1223
+ private readonly [symbol$j];
1224
+ readonly toolName: string;
1225
+ readonly toolInput: string;
1226
+ constructor({ toolInput, toolName, cause, message, }: {
1227
+ message?: string;
1228
+ toolInput: string;
1229
+ toolName: string;
1230
+ cause: unknown;
1231
+ });
1232
+ static isInstance(error: unknown): error is InvalidToolInputError;
1233
+ }
1234
+
1235
+ declare const symbol$i: unique symbol;
1236
+ declare class NoSuchToolError extends AISDKError {
1237
+ private readonly [symbol$i];
1238
+ readonly toolName: string;
1239
+ readonly availableTools: string[] | undefined;
1240
+ constructor({ toolName, availableTools, message, }: {
1241
+ toolName: string;
1242
+ availableTools?: string[] | undefined;
1243
+ message?: string;
1244
+ });
1245
+ static isInstance(error: unknown): error is NoSuchToolError;
1246
+ }
1247
+
1248
+ declare const systemModelMessageSchema: z.ZodType<SystemModelMessage>;
1249
+ declare const userModelMessageSchema: z.ZodType<UserModelMessage>;
1250
+ declare const assistantModelMessageSchema: z.ZodType<AssistantModelMessage>;
1251
+ declare const toolModelMessageSchema: z.ZodType<ToolModelMessage>;
1252
+ declare const modelMessageSchema: z.ZodType<ModelMessage>;
1253
+
1254
+ /**
1255
+ * A function that attempts to repair a tool call that failed to parse.
1256
+ *
1257
+ * It receives the error and the context as arguments and returns the repair
1258
+ * tool call JSON as text.
1259
+ *
1260
+ * @param options.system - The system prompt.
1261
+ * @param options.messages - The messages in the current generation step.
1262
+ * @param options.toolCall - The tool call that failed to parse.
1263
+ * @param options.tools - The tools that are available.
1264
+ * @param options.inputSchema - A function that returns the JSON Schema for a tool.
1265
+ * @param options.error - The error that occurred while parsing the tool call.
1266
+ */
1267
+ type ToolCallRepairFunction<TOOLS extends ToolSet> = (options: {
1268
+ system: string | SystemModelMessage | Array<SystemModelMessage> | undefined;
1269
+ messages: ModelMessage[];
1270
+ toolCall: LanguageModelV3ToolCall;
1271
+ tools: TOOLS;
1272
+ inputSchema: (options: {
1273
+ toolName: string;
1274
+ }) => PromiseLike<JSONSchema7>;
1275
+ error: NoSuchToolError | InvalidToolInputError;
1276
+ }) => Promise<LanguageModelV3ToolCall | null>;
1277
+
1278
+ /**
1279
+ * Include settings for generateText (requestBody and responseBody).
1280
+ */
1281
+ type GenerateTextIncludeSettings = {
1282
+ requestBody?: boolean;
1283
+ responseBody?: boolean;
1284
+ };
1285
+ /**
1286
+ * Callback that is set using the `experimental_onStart` option.
1287
+ *
1288
+ * Called when the generateText operation begins, before any LLM calls.
1289
+ * Use this callback for logging, analytics, or initializing state at the
1290
+ * start of a generation.
1291
+ *
1292
+ * @param event - The event object containing generation configuration.
1293
+ */
1294
+ type GenerateTextOnStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: OnStartEvent<TOOLS, OUTPUT, GenerateTextIncludeSettings>) => PromiseLike<void> | void;
1295
+ /**
1296
+ * Callback that is set using the `experimental_onStepStart` option.
1297
+ *
1298
+ * Called when a step (LLM call) begins, before the provider is called.
1299
+ * Each step represents a single LLM invocation. Multiple steps occur when
1300
+ * using tool calls (the model may be called multiple times in a loop).
1301
+ *
1302
+ * @param event - The event object containing step configuration.
1303
+ */
1304
+ type GenerateTextOnStepStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: OnStepStartEvent<TOOLS, OUTPUT, GenerateTextIncludeSettings>) => PromiseLike<void> | void;
1305
+ /**
1306
+ * Callback that is set using the `experimental_onToolCallStart` option.
1307
+ *
1308
+ * Called when a tool execution begins, before the tool's `execute` function is invoked.
1309
+ * Use this for logging tool invocations, tracking tool usage, or pre-execution validation.
1310
+ *
1311
+ * @param event - The event object containing tool call information.
1312
+ */
1313
+ type GenerateTextOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> = (event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;
1314
+ /**
1315
+ * Callback that is set using the `experimental_onToolCallFinish` option.
1316
+ *
1317
+ * Called when a tool execution completes, either successfully or with an error.
1318
+ * Use this for logging tool results, tracking execution time, or error handling.
1319
+ *
1320
+ * The event uses a discriminated union on the `success` field:
1321
+ * - When `success: true`: `output` contains the tool result, `error` is never present.
1322
+ * - When `success: false`: `error` contains the error, `output` is never present.
1323
+ *
1324
+ * @param event - The event object containing tool call result information.
1325
+ */
1326
+ type GenerateTextOnToolCallFinishCallback<TOOLS extends ToolSet = ToolSet> = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;
1327
+ /**
1328
+ * Callback that is set using the `onStepFinish` option.
1329
+ *
1330
+ * Called when a step (LLM call) completes. The event includes all step result
1331
+ * properties (text, tool calls, usage, etc.) along with additional metadata.
1332
+ *
1333
+ * @param stepResult - The result of the step.
1334
+ */
1335
+ type GenerateTextOnStepFinishCallback<TOOLS extends ToolSet> = (event: OnStepFinishEvent<TOOLS>) => Promise<void> | void;
1336
+ /**
1337
+ * Callback that is set using the `onFinish` option.
1338
+ *
1339
+ * Called when the entire generation completes (all steps finished).
1340
+ * The event includes the final step's result properties along with
1341
+ * aggregated data from all steps.
1342
+ *
1343
+ * @param event - The final result along with aggregated step data.
1344
+ */
1345
+ type GenerateTextOnFinishCallback<TOOLS extends ToolSet> = (event: OnFinishEvent<TOOLS>) => PromiseLike<void> | void;
1360
1346
  /**
1361
1347
  * Generate a text and call tools for a given prompt using a language model.
1362
1348
  *
@@ -2686,7 +2672,7 @@ type StreamTextOnErrorCallback = (event: {
2686
2672
  *
2687
2673
  * @param stepResult - The result of the step.
2688
2674
  */
2689
- type StreamTextOnStepFinishCallback<TOOLS extends ToolSet> = (stepResult: StepResult<TOOLS>) => PromiseLike<void> | void;
2675
+ type StreamTextOnStepFinishCallback<TOOLS extends ToolSet> = (event: OnStepFinishEvent<TOOLS>) => PromiseLike<void> | void;
2690
2676
  /**
2691
2677
  * Callback that is set using the `onChunk` option.
2692
2678
  *
@@ -2702,35 +2688,46 @@ type StreamTextOnChunkCallback<TOOLS extends ToolSet> = (event: {
2702
2688
  *
2703
2689
  * @param event - The event that is passed to the callback.
2704
2690
  */
2705
- type StreamTextOnFinishCallback<TOOLS extends ToolSet> = (event: StepResult<TOOLS> & {
2691
+ type StreamTextOnFinishCallback<TOOLS extends ToolSet> = (event: OnFinishEvent<TOOLS>) => PromiseLike<void> | void;
2692
+ /**
2693
+ * Callback that is set using the `onAbort` option.
2694
+ *
2695
+ * @param event - The event that is passed to the callback.
2696
+ */
2697
+ type StreamTextOnAbortCallback<TOOLS extends ToolSet> = (event: {
2706
2698
  /**
2707
- * Details for all steps.
2699
+ * Details for all previously finished steps.
2708
2700
  */
2709
2701
  readonly steps: StepResult<TOOLS>[];
2710
- /**
2711
- * Total usage for all steps. This is the sum of the usage of all steps.
2712
- */
2713
- readonly totalUsage: LanguageModelUsage;
2714
- /**
2715
- * Context that is passed into tool execution.
2716
- *
2717
- * Experimental (can break in patch releases).
2718
- *
2719
- * @default undefined
2720
- */
2721
- experimental_context: unknown;
2722
2702
  }) => PromiseLike<void> | void;
2723
2703
  /**
2724
- * Callback that is set using the `onAbort` option.
2704
+ * Include settings for streamText (requestBody only).
2705
+ */
2706
+ type StreamTextIncludeSettings = {
2707
+ requestBody?: boolean;
2708
+ };
2709
+ /**
2710
+ * Callback that is set using the `experimental_onStart` option.
2711
+ *
2712
+ * Called when the streamText operation begins, before any LLM calls.
2713
+ * Use this callback for logging, analytics, or initializing state at the
2714
+ * start of a generation.
2715
+ *
2716
+ * @param event - The event object containing generation configuration.
2717
+ */
2718
+ type StreamTextOnStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: OnStartEvent<TOOLS, OUTPUT, StreamTextIncludeSettings>) => PromiseLike<void> | void;
2719
+ /**
2720
+ * Callback that is set using the `experimental_onStepStart` option.
2725
2721
  *
2726
- * @param event - The event that is passed to the callback.
2722
+ * Called when a step (LLM call) begins, before the provider is called.
2723
+ * Each step represents a single LLM invocation. Multiple steps occur when
2724
+ * using tool calls (the model may be called multiple times in a loop).
2725
+ *
2726
+ * @param event - The event object containing step configuration.
2727
2727
  */
2728
- type StreamTextOnAbortCallback<TOOLS extends ToolSet> = (event: {
2729
- /**
2730
- * Details for all previously finished steps.
2731
- */
2732
- readonly steps: StepResult<TOOLS>[];
2733
- }) => PromiseLike<void> | void;
2728
+ type StreamTextOnStepStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: OnStepStartEvent<TOOLS, OUTPUT, StreamTextIncludeSettings>) => PromiseLike<void> | void;
2729
+ type StreamTextOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> = (event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;
2730
+ type StreamTextOnToolCallFinishCallback<TOOLS extends ToolSet = ToolSet> = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;
2734
2731
  /**
2735
2732
  * Generate a text and call tools for a given prompt using a language model.
2736
2733
  *
@@ -2777,7 +2774,7 @@ type StreamTextOnAbortCallback<TOOLS extends ToolSet> = (event: {
2777
2774
  * @returns
2778
2775
  * A result object for accessing different stream types and additional information.
2779
2776
  */
2780
- declare function streamText<TOOLS extends ToolSet, OUTPUT extends Output = Output<string, string, never>>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, timeout, headers, stopWhen, experimental_output, output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_activeTools, activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError, onFinish, onAbort, onStepFinish, experimental_context, experimental_include: include, _internal: { now, generateId }, ...settings }: CallSettings & Prompt & {
2777
+ declare function streamText<TOOLS extends ToolSet, OUTPUT extends Output = Output<string, string, never>>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, timeout, headers, stopWhen, experimental_output, output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_activeTools, activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError, onFinish, onAbort, onStepFinish, experimental_onStart: onStart, experimental_onStepStart: onStepStart, experimental_onToolCallStart: onToolCallStart, experimental_onToolCallFinish: onToolCallFinish, experimental_context, experimental_include: include, _internal: { now, generateId }, ...settings }: CallSettings & Prompt & {
2781
2778
  /**
2782
2779
  * The language model to use.
2783
2780
  */
@@ -2884,6 +2881,24 @@ declare function streamText<TOOLS extends ToolSet, OUTPUT extends Output = Outpu
2884
2881
  * Callback that is called when each step (LLM call) is finished, including intermediate steps.
2885
2882
  */
2886
2883
  onStepFinish?: StreamTextOnStepFinishCallback<TOOLS>;
2884
+ /**
2885
+ * Callback that is called when the streamText operation begins,
2886
+ * before any LLM calls are made.
2887
+ */
2888
+ experimental_onStart?: StreamTextOnStartCallback<NoInfer<TOOLS>, OUTPUT>;
2889
+ /**
2890
+ * Callback that is called when a step (LLM call) begins,
2891
+ * before the provider is called.
2892
+ */
2893
+ experimental_onStepStart?: StreamTextOnStepStartCallback<NoInfer<TOOLS>, OUTPUT>;
2894
+ /**
2895
+ * Callback that is called right before a tool's execute function runs.
2896
+ */
2897
+ experimental_onToolCallStart?: StreamTextOnToolCallStartCallback<NoInfer<TOOLS>>;
2898
+ /**
2899
+ * Callback that is called right after a tool's execute function completes (or errors).
2900
+ */
2901
+ experimental_onToolCallFinish?: StreamTextOnToolCallFinishCallback<NoInfer<TOOLS>>;
2887
2902
  /**
2888
2903
  * Context that is passed into tool execution.
2889
2904
  *
@@ -3190,128 +3205,12 @@ interface GenerateTextResult<TOOLS extends ToolSet, OUTPUT extends Output> {
3190
3205
  readonly output: InferCompleteOutput<OUTPUT>;
3191
3206
  }
3192
3207
 
3193
- /**
3194
- * Callback that is set using the `onStepFinish` option.
3195
- *
3196
- * @param stepResult - The result of the step.
3197
- */
3198
- type ToolLoopAgentOnStepFinishCallback<TOOLS extends ToolSet = {}> = (stepResult: StepResult<TOOLS>) => Promise<void> | void;
3199
-
3200
- /**
3201
- * Parameters for calling an agent.
3202
- */
3203
- type AgentCallParameters<CALL_OPTIONS, TOOLS extends ToolSet = {}> = ([
3204
- CALL_OPTIONS
3205
- ] extends [never] ? {
3206
- options?: never;
3207
- } : {
3208
- options: CALL_OPTIONS;
3209
- }) & ({
3210
- /**
3211
- * A prompt. It can be either a text prompt or a list of messages.
3212
- *
3213
- * You can either use `prompt` or `messages` but not both.
3214
- */
3215
- prompt: string | Array<ModelMessage>;
3216
- /**
3217
- * A list of messages.
3218
- *
3219
- * You can either use `prompt` or `messages` but not both.
3220
- */
3221
- messages?: never;
3222
- } | {
3223
- /**
3224
- * A list of messages.
3225
- *
3226
- * You can either use `prompt` or `messages` but not both.
3227
- */
3228
- messages: Array<ModelMessage>;
3229
- /**
3230
- * A prompt. It can be either a text prompt or a list of messages.
3231
- *
3232
- * You can either use `prompt` or `messages` but not both.
3233
- */
3234
- prompt?: never;
3235
- }) & {
3236
- /**
3237
- * Abort signal.
3238
- */
3239
- abortSignal?: AbortSignal;
3240
- /**
3241
- * Timeout in milliseconds. Can be specified as a number or as an object with `totalMs`.
3242
- */
3243
- timeout?: TimeoutConfiguration;
3244
- /**
3245
- * Callback that is called when each step (LLM call) is finished, including intermediate steps.
3246
- */
3247
- onStepFinish?: ToolLoopAgentOnStepFinishCallback<TOOLS>;
3248
- };
3249
- /**
3250
- * Parameters for streaming an output from an agent.
3251
- */
3252
- type AgentStreamParameters<CALL_OPTIONS, TOOLS extends ToolSet> = AgentCallParameters<CALL_OPTIONS, TOOLS> & {
3253
- /**
3254
- * Optional stream transformations.
3255
- * They are applied in the order they are provided.
3256
- * The stream transformations must maintain the stream structure for streamText to work correctly.
3257
- */
3258
- experimental_transform?: StreamTextTransform<TOOLS> | Array<StreamTextTransform<TOOLS>>;
3259
- };
3260
- /**
3261
- * An Agent receives a prompt (text or messages) and generates or streams an output
3262
- * that consists of steps, tool calls, data parts, etc.
3263
- *
3264
- * You can implement your own Agent by implementing the `Agent` interface,
3265
- * or use the `ToolLoopAgent` class.
3266
- */
3267
- interface Agent<CALL_OPTIONS = never, TOOLS extends ToolSet = {}, OUTPUT extends Output = never> {
3268
- /**
3269
- * The specification version of the agent interface. This will enable
3270
- * us to evolve the agent interface and retain backwards compatibility.
3271
- */
3272
- readonly version: 'agent-v1';
3273
- /**
3274
- * The id of the agent.
3275
- */
3276
- readonly id: string | undefined;
3277
- /**
3278
- * The tools that the agent can use.
3279
- */
3280
- readonly tools: TOOLS;
3281
- /**
3282
- * Generates an output from the agent (non-streaming).
3283
- */
3284
- generate(options: AgentCallParameters<CALL_OPTIONS, TOOLS>): PromiseLike<GenerateTextResult<TOOLS, OUTPUT>>;
3285
- /**
3286
- * Streams an output from the agent (streaming).
3287
- */
3288
- stream(options: AgentStreamParameters<CALL_OPTIONS, TOOLS>): PromiseLike<StreamTextResult<TOOLS, OUTPUT>>;
3289
- }
3290
-
3291
- /**
3292
- * Callback that is set using the `onFinish` option.
3293
- *
3294
- * @param event - The event that is passed to the callback.
3295
- */
3296
- type ToolLoopAgentOnFinishCallback<TOOLS extends ToolSet = {}> = (event: StepResult<TOOLS> & {
3297
- /**
3298
- * Details for all steps.
3299
- */
3300
- readonly steps: StepResult<TOOLS>[];
3301
- /**
3302
- * Total usage for all steps. This is the sum of the usage of all steps.
3303
- */
3304
- readonly totalUsage: LanguageModelUsage;
3305
- /**
3306
- * Context that is passed into tool execution.
3307
- *
3308
- * Experimental (can break in patch releases).
3309
- *
3310
- * @default undefined
3311
- */
3312
- experimental_context: unknown;
3313
- }) => PromiseLike<void> | void;
3314
-
3208
+ type ToolLoopAgentOnStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: OnStartEvent<TOOLS, OUTPUT>) => PromiseLike<void> | void;
3209
+ type ToolLoopAgentOnStepStartCallback<TOOLS extends ToolSet = ToolSet, OUTPUT extends Output = Output> = (event: OnStepStartEvent<TOOLS, OUTPUT>) => PromiseLike<void> | void;
3210
+ type ToolLoopAgentOnToolCallStartCallback<TOOLS extends ToolSet = ToolSet> = (event: OnToolCallStartEvent<TOOLS>) => PromiseLike<void> | void;
3211
+ type ToolLoopAgentOnToolCallFinishCallback<TOOLS extends ToolSet = ToolSet> = (event: OnToolCallFinishEvent<TOOLS>) => PromiseLike<void> | void;
3212
+ type ToolLoopAgentOnStepFinishCallback<TOOLS extends ToolSet = {}> = (stepResult: OnStepFinishEvent<TOOLS>) => Promise<void> | void;
3213
+ type ToolLoopAgentOnFinishCallback<TOOLS extends ToolSet = {}> = (event: OnFinishEvent<TOOLS>) => PromiseLike<void> | void;
3315
3214
  /**
3316
3215
  * Configuration options for an agent.
3317
3216
  */
@@ -3366,6 +3265,22 @@ type ToolLoopAgentSettings<CALL_OPTIONS = never, TOOLS extends ToolSet = {}, OUT
3366
3265
  * A function that attempts to repair a tool call that failed to parse.
3367
3266
  */
3368
3267
  experimental_repairToolCall?: ToolCallRepairFunction<NoInfer<TOOLS>>;
3268
+ /**
3269
+ * Callback that is called when the agent operation begins, before any LLM calls.
3270
+ */
3271
+ experimental_onStart?: ToolLoopAgentOnStartCallback<NoInfer<TOOLS>, OUTPUT>;
3272
+ /**
3273
+ * Callback that is called when a step (LLM call) begins, before the provider is called.
3274
+ */
3275
+ experimental_onStepStart?: ToolLoopAgentOnStepStartCallback<NoInfer<TOOLS>, OUTPUT>;
3276
+ /**
3277
+ * Callback that is called before each tool execution begins.
3278
+ */
3279
+ experimental_onToolCallStart?: ToolLoopAgentOnToolCallStartCallback<NoInfer<TOOLS>>;
3280
+ /**
3281
+ * Callback that is called after each tool execution completes.
3282
+ */
3283
+ experimental_onToolCallFinish?: ToolLoopAgentOnToolCallFinishCallback<NoInfer<TOOLS>>;
3369
3284
  /**
3370
3285
  * Callback that is called when each step (LLM call) is finished, including intermediate steps.
3371
3286
  */
@@ -3406,6 +3321,117 @@ type ToolLoopAgentSettings<CALL_OPTIONS = never, TOOLS extends ToolSet = {}, OUT
3406
3321
  prepareCall?: (options: Omit<AgentCallParameters<CALL_OPTIONS, NoInfer<TOOLS>>, 'onStepFinish'> & Pick<ToolLoopAgentSettings<CALL_OPTIONS, TOOLS, OUTPUT>, 'model' | 'tools' | 'maxOutputTokens' | 'temperature' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed' | 'headers' | 'instructions' | 'stopWhen' | 'experimental_telemetry' | 'activeTools' | 'providerOptions' | 'experimental_context' | 'experimental_download'>) => MaybePromiseLike<Pick<ToolLoopAgentSettings<CALL_OPTIONS, TOOLS, OUTPUT>, 'model' | 'tools' | 'maxOutputTokens' | 'temperature' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed' | 'headers' | 'instructions' | 'stopWhen' | 'experimental_telemetry' | 'activeTools' | 'providerOptions' | 'experimental_context' | 'experimental_download'> & Omit<Prompt, 'system'>>;
3407
3322
  };
3408
3323
 
3324
+ /**
3325
+ * Parameters for calling an agent.
3326
+ */
3327
+ type AgentCallParameters<CALL_OPTIONS, TOOLS extends ToolSet = {}> = ([
3328
+ CALL_OPTIONS
3329
+ ] extends [never] ? {
3330
+ options?: never;
3331
+ } : {
3332
+ options: CALL_OPTIONS;
3333
+ }) & ({
3334
+ /**
3335
+ * A prompt. It can be either a text prompt or a list of messages.
3336
+ *
3337
+ * You can either use `prompt` or `messages` but not both.
3338
+ */
3339
+ prompt: string | Array<ModelMessage>;
3340
+ /**
3341
+ * A list of messages.
3342
+ *
3343
+ * You can either use `prompt` or `messages` but not both.
3344
+ */
3345
+ messages?: never;
3346
+ } | {
3347
+ /**
3348
+ * A list of messages.
3349
+ *
3350
+ * You can either use `prompt` or `messages` but not both.
3351
+ */
3352
+ messages: Array<ModelMessage>;
3353
+ /**
3354
+ * A prompt. It can be either a text prompt or a list of messages.
3355
+ *
3356
+ * You can either use `prompt` or `messages` but not both.
3357
+ */
3358
+ prompt?: never;
3359
+ }) & {
3360
+ /**
3361
+ * Abort signal.
3362
+ */
3363
+ abortSignal?: AbortSignal;
3364
+ /**
3365
+ * Timeout in milliseconds. Can be specified as a number or as an object with `totalMs`.
3366
+ */
3367
+ timeout?: TimeoutConfiguration;
3368
+ /**
3369
+ * Callback that is called when the agent operation begins, before any LLM calls.
3370
+ */
3371
+ experimental_onStart?: ToolLoopAgentOnStartCallback<TOOLS>;
3372
+ /**
3373
+ * Callback that is called when a step (LLM call) begins, before the provider is called.
3374
+ */
3375
+ experimental_onStepStart?: ToolLoopAgentOnStepStartCallback<TOOLS>;
3376
+ /**
3377
+ * Callback that is called before each tool execution begins.
3378
+ */
3379
+ experimental_onToolCallStart?: ToolLoopAgentOnToolCallStartCallback<TOOLS>;
3380
+ /**
3381
+ * Callback that is called after each tool execution completes.
3382
+ */
3383
+ experimental_onToolCallFinish?: ToolLoopAgentOnToolCallFinishCallback<TOOLS>;
3384
+ /**
3385
+ * Callback that is called when each step (LLM call) is finished, including intermediate steps.
3386
+ */
3387
+ onStepFinish?: ToolLoopAgentOnStepFinishCallback<TOOLS>;
3388
+ /**
3389
+ * Callback that is called when all steps are finished and the response is complete.
3390
+ */
3391
+ onFinish?: ToolLoopAgentOnFinishCallback<TOOLS>;
3392
+ };
3393
+ /**
3394
+ * Parameters for streaming an output from an agent.
3395
+ */
3396
+ type AgentStreamParameters<CALL_OPTIONS, TOOLS extends ToolSet> = AgentCallParameters<CALL_OPTIONS, TOOLS> & {
3397
+ /**
3398
+ * Optional stream transformations.
3399
+ * They are applied in the order they are provided.
3400
+ * The stream transformations must maintain the stream structure for streamText to work correctly.
3401
+ */
3402
+ experimental_transform?: StreamTextTransform<TOOLS> | Array<StreamTextTransform<TOOLS>>;
3403
+ };
3404
+ /**
3405
+ * An Agent receives a prompt (text or messages) and generates or streams an output
3406
+ * that consists of steps, tool calls, data parts, etc.
3407
+ *
3408
+ * You can implement your own Agent by implementing the `Agent` interface,
3409
+ * or use the `ToolLoopAgent` class.
3410
+ */
3411
+ interface Agent<CALL_OPTIONS = never, TOOLS extends ToolSet = {}, OUTPUT extends Output = never> {
3412
+ /**
3413
+ * The specification version of the agent interface. This will enable
3414
+ * us to evolve the agent interface and retain backwards compatibility.
3415
+ */
3416
+ readonly version: 'agent-v1';
3417
+ /**
3418
+ * The id of the agent.
3419
+ */
3420
+ readonly id: string | undefined;
3421
+ /**
3422
+ * The tools that the agent can use.
3423
+ */
3424
+ readonly tools: TOOLS;
3425
+ /**
3426
+ * Generates an output from the agent (non-streaming).
3427
+ */
3428
+ generate(options: AgentCallParameters<CALL_OPTIONS, TOOLS>): PromiseLike<GenerateTextResult<TOOLS, OUTPUT>>;
3429
+ /**
3430
+ * Streams an output from the agent (streaming).
3431
+ */
3432
+ stream(options: AgentStreamParameters<CALL_OPTIONS, TOOLS>): PromiseLike<StreamTextResult<TOOLS, OUTPUT>>;
3433
+ }
3434
+
3409
3435
  /**
3410
3436
  * A tool loop agent is an agent that runs tools in a loop. In each step,
3411
3437
  * it calls the LLM, and if there are tool calls, it executes the tools
@@ -3430,15 +3456,15 @@ declare class ToolLoopAgent<CALL_OPTIONS = never, TOOLS extends ToolSet = {}, OU
3430
3456
  */
3431
3457
  get tools(): TOOLS;
3432
3458
  private prepareCall;
3433
- private mergeOnStepFinishCallbacks;
3459
+ private mergeCallbacks;
3434
3460
  /**
3435
3461
  * Generates an output from the agent (non-streaming).
3436
3462
  */
3437
- generate({ abortSignal, timeout, onStepFinish, ...options }: AgentCallParameters<CALL_OPTIONS, TOOLS>): Promise<GenerateTextResult<TOOLS, OUTPUT>>;
3463
+ generate({ abortSignal, timeout, experimental_onStart, experimental_onStepStart, experimental_onToolCallStart, experimental_onToolCallFinish, onStepFinish, onFinish, ...options }: AgentCallParameters<CALL_OPTIONS, TOOLS>): Promise<GenerateTextResult<TOOLS, OUTPUT>>;
3438
3464
  /**
3439
3465
  * Streams an output from the agent (streaming).
3440
3466
  */
3441
- stream({ abortSignal, timeout, experimental_transform, onStepFinish, ...options }: AgentStreamParameters<CALL_OPTIONS, TOOLS>): Promise<StreamTextResult<TOOLS, OUTPUT>>;
3467
+ stream({ abortSignal, timeout, experimental_transform, experimental_onStart, experimental_onStepStart, experimental_onToolCallStart, experimental_onToolCallFinish, onStepFinish, onFinish, ...options }: AgentStreamParameters<CALL_OPTIONS, TOOLS>): Promise<StreamTextResult<TOOLS, OUTPUT>>;
3442
3468
  }
3443
3469
 
3444
3470
  /**
@@ -6354,4 +6380,4 @@ declare global {
6354
6380
  var AI_SDK_LOG_WARNINGS: LogWarningsFunction | undefined | false;
6355
6381
  }
6356
6382
 
6357
- export { AbstractChat, Agent, AgentCallParameters, AgentStreamParameters, AsyncIterableStream, CallSettings, CallWarning, ChatAddToolApproveResponseFunction, ChatInit, ChatOnDataCallback, ChatOnErrorCallback, ChatOnFinishCallback, ChatOnToolCallCallback, ChatRequestOptions, ChatState, ChatStatus, ChatTransport, ChunkDetector, CompletionRequestOptions, ContentPart, CreateUIMessage, DataUIPart, DeepPartial, DefaultChatTransport, DefaultGeneratedFile, DirectChatTransport, DirectChatTransportOptions, DynamicToolCall, DynamicToolError, DynamicToolResult, DynamicToolUIPart, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelMiddleware, EmbeddingModelUsage, ErrorHandler, ToolLoopAgent as Experimental_Agent, ToolLoopAgentSettings as Experimental_AgentSettings, DownloadFunction as Experimental_DownloadFunction, Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, InferAgentUIMessage as Experimental_InferAgentUIMessage, LogWarningsFunction as Experimental_LogWarningsFunction, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, FileUIPart, FinishReason, GenerateImageResult, GenerateObjectResult, GenerateTextOnFinishCallback, GenerateTextOnStartCallback, GenerateTextOnStepFinishCallback, GenerateTextOnStepStartCallback, GenerateTextOnToolCallFinishCallback, GenerateTextOnToolCallStartCallback, GenerateTextResult, GenerateVideoPrompt, GenerateVideoResult, GeneratedAudioFile, GeneratedFile, HttpChatTransport, HttpChatTransportInitOptions, ImageModel, ImageModelMiddleware, ImageModelProviderMetadata, ImageModelResponseMetadata, ImageModelUsage, InferAgentUIMessage, InferCompleteOutput as InferGenerateOutput, InferPartialOutput as InferStreamOutput, InferUIDataParts, InferUIMessageChunk, InferUITool, InferUITools, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolApprovalError, InvalidToolInputError, JSONValue, JsonToSseTransformStream, LanguageModel, LanguageModelMiddleware, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, LogWarningsFunction, MessageConversionError, MissingToolResultsError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoSpeechGeneratedError, NoSuchProviderError, NoSuchToolError, NoTranscriptGeneratedError, NoVideoGeneratedError, ObjectStreamPart, output as Output, PrepareReconnectToStreamRequest, PrepareSendMessagesRequest, PrepareStepFunction, PrepareStepResult, Prompt, Provider, ProviderMetadata, ProviderRegistryProvider, ReasoningOutput, ReasoningUIPart, RepairTextFunction, RerankResult, RerankingModel, RetryError, SafeValidateUIMessagesResult, SerialJobExecutor, SourceDocumentUIPart, SourceUrlUIPart, SpeechModel, SpeechModelResponseMetadata, StaticToolCall, StaticToolError, StaticToolOutputDenied, StaticToolResult, StepResult, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, TelemetrySettings, TextStreamChatTransport, TextStreamPart, TextUIPart, TimeoutConfiguration, ToolApprovalRequestOutput, ToolCallNotFoundForApprovalError, ToolCallRepairError, ToolCallRepairFunction, ToolChoice, ToolLoopAgent, ToolLoopAgentOnFinishCallback, ToolLoopAgentOnStepFinishCallback, ToolLoopAgentSettings, ToolSet, ToolUIPart, TranscriptionModel, TranscriptionModelResponseMetadata, TypedToolCall, TypedToolError, TypedToolOutputDenied, TypedToolResult, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessageChunk, UIMessagePart, UIMessageStreamError, UIMessageStreamOnFinishCallback, UIMessageStreamOnStepFinishCallback, UIMessageStreamOptions, UIMessageStreamWriter, UITool, UIToolInvocation, UITools, UI_MESSAGE_STREAM_HEADERS, UnsupportedModelVersionError, UseCompletionOptions, Warning, addToolInputExamplesMiddleware, assistantModelMessageSchema, callCompletionApi, consumeStream, convertFileListToFileUIParts, convertToModelMessages, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createDownload, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultEmbeddingSettingsMiddleware, defaultSettingsMiddleware, embed, embedMany, experimental_createProviderRegistry, experimental_customProvider, experimental_generateImage, generateSpeech as experimental_generateSpeech, experimental_generateVideo, transcribe as experimental_transcribe, extractJsonMiddleware, extractReasoningMiddleware, generateImage, generateObject, generateText, getStaticToolName, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, hasToolCall, isDataUIPart, isDeepEqualData, isFileUIPart, isReasoningUIPart, isStaticToolUIPart, isTextUIPart, isToolOrDynamicToolUIPart, isToolUIPart, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, rerank, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, toolModelMessageSchema, uiMessageChunkSchema, userModelMessageSchema, validateUIMessages, wrapEmbeddingModel, wrapImageModel, wrapLanguageModel, wrapProvider };
6383
+ export { AbstractChat, Agent, AgentCallParameters, AgentStreamParameters, AsyncIterableStream, CallSettings, CallWarning, ChatAddToolApproveResponseFunction, ChatInit, ChatOnDataCallback, ChatOnErrorCallback, ChatOnFinishCallback, ChatOnToolCallCallback, ChatRequestOptions, ChatState, ChatStatus, ChatTransport, ChunkDetector, CompletionRequestOptions, ContentPart, CreateUIMessage, DataUIPart, DeepPartial, DefaultChatTransport, DefaultGeneratedFile, DirectChatTransport, DirectChatTransportOptions, DynamicToolCall, DynamicToolError, DynamicToolResult, DynamicToolUIPart, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelMiddleware, EmbeddingModelUsage, ErrorHandler, ToolLoopAgent as Experimental_Agent, ToolLoopAgentSettings as Experimental_AgentSettings, DownloadFunction as Experimental_DownloadFunction, Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, InferAgentUIMessage as Experimental_InferAgentUIMessage, LogWarningsFunction as Experimental_LogWarningsFunction, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, FileUIPart, FinishReason, GenerateImageResult, GenerateObjectResult, GenerateTextOnFinishCallback, GenerateTextOnStartCallback, GenerateTextOnStepFinishCallback, GenerateTextOnStepStartCallback, GenerateTextOnToolCallFinishCallback, GenerateTextOnToolCallStartCallback, GenerateTextResult, GenerateVideoPrompt, GenerateVideoResult, GeneratedAudioFile, GeneratedFile, HttpChatTransport, HttpChatTransportInitOptions, ImageModel, ImageModelMiddleware, ImageModelProviderMetadata, ImageModelResponseMetadata, ImageModelUsage, InferAgentUIMessage, InferCompleteOutput as InferGenerateOutput, InferPartialOutput as InferStreamOutput, InferUIDataParts, InferUIMessageChunk, InferUITool, InferUITools, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolApprovalError, InvalidToolInputError, JSONValue, JsonToSseTransformStream, LanguageModel, LanguageModelMiddleware, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, LogWarningsFunction, MessageConversionError, MissingToolResultsError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoSpeechGeneratedError, NoSuchProviderError, NoSuchToolError, NoTranscriptGeneratedError, NoVideoGeneratedError, ObjectStreamPart, output as Output, PrepareReconnectToStreamRequest, PrepareSendMessagesRequest, PrepareStepFunction, PrepareStepResult, Prompt, Provider, ProviderMetadata, ProviderRegistryProvider, ReasoningOutput, ReasoningUIPart, RepairTextFunction, RerankResult, RerankingModel, RetryError, SafeValidateUIMessagesResult, SerialJobExecutor, SourceDocumentUIPart, SourceUrlUIPart, SpeechModel, SpeechModelResponseMetadata, StaticToolCall, StaticToolError, StaticToolOutputDenied, StaticToolResult, StepResult, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStartCallback, StreamTextOnStepFinishCallback, StreamTextOnStepStartCallback, StreamTextOnToolCallFinishCallback, StreamTextOnToolCallStartCallback, StreamTextResult, StreamTextTransform, TelemetrySettings, TextStreamChatTransport, TextStreamPart, TextUIPart, TimeoutConfiguration, ToolApprovalRequestOutput, ToolCallNotFoundForApprovalError, ToolCallRepairError, ToolCallRepairFunction, ToolChoice, ToolLoopAgent, ToolLoopAgentOnFinishCallback, ToolLoopAgentOnStartCallback, ToolLoopAgentOnStepFinishCallback, ToolLoopAgentOnStepStartCallback, ToolLoopAgentOnToolCallFinishCallback, ToolLoopAgentOnToolCallStartCallback, ToolLoopAgentSettings, ToolSet, ToolUIPart, TranscriptionModel, TranscriptionModelResponseMetadata, TypedToolCall, TypedToolError, TypedToolOutputDenied, TypedToolResult, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessageChunk, UIMessagePart, UIMessageStreamError, UIMessageStreamOnFinishCallback, UIMessageStreamOnStepFinishCallback, UIMessageStreamOptions, UIMessageStreamWriter, UITool, UIToolInvocation, UITools, UI_MESSAGE_STREAM_HEADERS, UnsupportedModelVersionError, UseCompletionOptions, Warning, addToolInputExamplesMiddleware, assistantModelMessageSchema, callCompletionApi, consumeStream, convertFileListToFileUIParts, convertToModelMessages, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createDownload, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultEmbeddingSettingsMiddleware, defaultSettingsMiddleware, embed, embedMany, experimental_createProviderRegistry, experimental_customProvider, experimental_generateImage, generateSpeech as experimental_generateSpeech, experimental_generateVideo, transcribe as experimental_transcribe, extractJsonMiddleware, extractReasoningMiddleware, generateImage, generateObject, generateText, getStaticToolName, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, hasToolCall, isDataUIPart, isDeepEqualData, isFileUIPart, isReasoningUIPart, isStaticToolUIPart, isTextUIPart, isToolOrDynamicToolUIPart, isToolUIPart, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, rerank, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, toolModelMessageSchema, uiMessageChunkSchema, userModelMessageSchema, validateUIMessages, wrapEmbeddingModel, wrapImageModel, wrapLanguageModel, wrapProvider };