ai 7.0.179 → 7.0.181

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/{default-stop-condition-wtuJTiTo.js → default-stop-condition-D8PwkeWe.js} +52 -27
  3. package/dist/default-stop-condition-D8PwkeWe.js.map +1 -0
  4. package/dist/{index-CM_8u8gB.d.ts → index-CKEJqCzY.d.ts} +69 -4
  5. package/dist/index-CKEJqCzY.d.ts.map +1 -0
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +192 -119
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal/index.d.ts +8 -4
  10. package/dist/internal/index.d.ts.map +1 -1
  11. package/dist/internal/index.js +1 -1
  12. package/docs/03-agents/04-loop-control.mdx +35 -1
  13. package/docs/03-agents/06-policy-tool-approvals.mdx +5 -2
  14. package/docs/03-agents/08-terminal-ui.mdx +10 -0
  15. package/docs/03-ai-sdk-core/16-mcp-tools.mdx +59 -0
  16. package/docs/03-ai-sdk-core/65-lifecycle-callbacks.mdx +6 -0
  17. package/docs/04-ai-sdk-ui/21-error-handling.mdx +21 -0
  18. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +19 -0
  19. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +25 -0
  20. package/docs/07-reference/01-ai-sdk-core/16-tool-loop-agent.mdx +7 -0
  21. package/docs/07-reference/01-ai-sdk-core/25-create-mcp-tools.mdx +65 -0
  22. package/docs/07-reference/06-ai-sdk-tui/01-run-agent-tui.mdx +3 -0
  23. package/package.json +4 -4
  24. package/src/agent/default-stop-condition.ts +12 -3
  25. package/src/agent/tool-loop-agent-settings.ts +11 -0
  26. package/src/agent/tool-loop-agent.ts +3 -1
  27. package/src/extract/restricted-telemetry-dispatcher.ts +9 -5
  28. package/src/generate-text/default-generate-text-result.ts +4 -0
  29. package/src/generate-text/generate-text-events.ts +7 -0
  30. package/src/generate-text/generate-text-result.ts +9 -0
  31. package/src/generate-text/generate-text.ts +37 -5
  32. package/src/generate-text/index.ts +1 -0
  33. package/src/generate-text/steering.ts +19 -5
  34. package/src/generate-text/stopped-by.ts +43 -0
  35. package/src/generate-text/stream-language-model-call.ts +21 -2
  36. package/src/generate-text/stream-text-result.ts +18 -0
  37. package/src/generate-text/stream-text.ts +59 -6
  38. package/src/logger/create-log-warnings.ts +17 -0
  39. package/src/model/as-language-model-v3.ts +3 -0
  40. package/src/model/as-language-model-v4.ts +5 -1
  41. package/src/model/resolve-model.ts +8 -3
  42. package/src/prompt/convert-to-language-model-prompt.ts +15 -6
  43. package/src/util/log-v2-compatibility-warning.ts +5 -2
  44. package/dist/default-stop-condition-wtuJTiTo.js.map +0 -1
  45. package/dist/index-CM_8u8gB.d.ts.map +0 -1
@@ -1,13 +1,14 @@
1
- import { $c as LanguageModelCallOptions, Al as addLanguageModelUsage, Ao as ToolApprovalStatus, Ba as GenerateTextOnEndCallback, Bl as LanguageModelResponseMetadata, Ca as TelemetryDispatcher, El as Warning, Eo as ResolvedToolCallers, Ga as GenerateTextOnStepFinishCallback, Go as StaticToolOutputDenied, Ha as GenerateTextOnStartCallback, Hl as LanguageModelRequestMetadata, Jl as ToolChoice, Js as ContentPart, Ka as GenerateTextOnStepStartCallback, Kl as FinishReason, Ks as StepResult, Ml as createNullLanguageModelUsage, Pc as ToolModelMessage$1, So as ToolCallRepairFunction, Ua as GenerateTextOnStepEndCallback, Vl as ResponseMessage, Vo as ToolOrder, Wa as GenerateTextOnStepErrorCallback, Ws as DefaultStepResult, Xs as StaticToolResult, Ys as DynamicToolResult, Zo as createAsyncIterableStream, Zs as TypedToolResult, _a as LanguageModelStreamPart, _c as StandardizedPrompt, _l as DownloadFunction, _o as OnToolExecutionEndCallback, ac as TypedToolCall, dc as IncludedContext, fc as IncludedToolsContext, ga as GenerateTextResult, gc as Callback, ic as StaticToolCall, jl as asLanguageModelUsage, kl as LanguageModelUsage, ko as ToolApprovalConfiguration, mo as ToolInputRefinement, nc as ToolApprovalRequestOutput, oc as ReasoningFileOutput, pc as TelemetryOptions, po as ToolsContextSettings, ql as LanguageModel, qo as InferCompleteOutput, rc as DynamicToolCall, sc as ReasoningOutput, tc as ToolApprovalResponseOutput, to as Output, uc as GeneratedFile, vc as standardizePrompt, vl as createDefaultDownloadFunction, vo as OnToolExecutionStartCallback, wc as AssistantModelMessage$1, wl as logWarnings, wo as InvalidToolInputError, xo as ToolOutput, za as GenerateTextOnAbortCallback, zc as Instructions } from "../index-CM_8u8gB.js";
1
+ import { Al as LanguageModelUsage, Ao as ToolApprovalStatus, Ba as GenerateTextOnEndCallback, Bc as Instructions, Ca as TelemetryDispatcher, Dl as Warning, Eo as ResolvedToolCallers, Fc as ToolModelMessage$1, Ga as GenerateTextOnStepFinishCallback, Go as StoppedBy, Gs as DefaultStepResult, Ha as GenerateTextOnStartCallback, Hl as ResponseMessage, Jl as LanguageModel, Jo as InferCompleteOutput, Ka as GenerateTextOnStepStartCallback, Ko as StaticToolOutputDenied, Ml as asLanguageModelUsage, Nl as createNullLanguageModelUsage, Qo as createAsyncIterableStream, Qs as TypedToolResult, So as ToolCallRepairFunction, Tc as AssistantModelMessage$1, Tl as logWarnings, Ua as GenerateTextOnStepEndCallback, Ul as LanguageModelRequestMetadata, Vl as LanguageModelResponseMetadata, Vo as ToolOrder, Wa as GenerateTextOnStepErrorCallback, Xs as DynamicToolResult, Yl as ToolChoice, Ys as ContentPart, Zs as StaticToolResult, _a as LanguageModelStreamPart, _c as Callback, _o as OnToolExecutionEndCallback, ac as StaticToolCall, cc as ReasoningOutput, dc as GeneratedFile, el as LanguageModelCallOptions, fc as IncludedContext, ga as GenerateTextResult, ic as DynamicToolCall, jl as addLanguageModelUsage, ko as ToolApprovalConfiguration, mc as TelemetryOptions, mo as ToolInputRefinement, nc as ToolApprovalResponseOutput, oc as TypedToolCall, pc as IncludedToolsContext, po as ToolsContextSettings, ql as FinishReason, qs as StepResult, rc as ToolApprovalRequestOutput, sc as ReasoningFileOutput, to as Output, vc as StandardizedPrompt, vl as DownloadFunction, vo as OnToolExecutionStartCallback, wl as LogWarningsFunction, wo as InvalidToolInputError, xo as ToolOutput, yc as standardizePrompt, yl as createDefaultDownloadFunction, za as GenerateTextOnAbortCallback } from "../index-CKEJqCzY.js";
2
2
  import { Arrayable, Context, Experimental_SandboxSession, FlexibleSchema, IdGenerator, InferToolSetContext, ModelMessage, RetryFunction, ShouldRetryFunction, Tool, ToolApprovalRequest, ToolApprovalResponse, ToolResultOutput, ToolResultPart, ToolSet, convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
3
  import { EmbeddingModelV4, Experimental_DecisionModelV4, Experimental_ExtractionModelV4, Experimental_SpeechTranslationModelV4, Experimental_VideoModelV4, ImageModelV4, LanguageModelV4, LanguageModelV4Content, LanguageModelV4FunctionTool, LanguageModelV4Prompt, LanguageModelV4ProviderTool, LanguageModelV4ToolCall, LanguageModelV4ToolChoice, LanguageModelV4ToolResultOutput, RerankingModelV4, SharedV4Warning, SpeechModelV4, TranscriptionModelV4 } from "@ai-sdk/provider";
4
4
  //#region src/prompt/convert-to-language-model-prompt.d.ts
5
- export declare function convertToLanguageModelPrompt({ prompt, supportedUrls, download, abortSignal, provider }: {
5
+ export declare function convertToLanguageModelPrompt({ prompt, supportedUrls, download, abortSignal, provider, warnings }: {
6
6
  prompt: StandardizedPrompt;
7
7
  supportedUrls: Record<string, RegExp[]>;
8
8
  download: DownloadFunction | undefined;
9
9
  abortSignal?: AbortSignal;
10
10
  provider?: string;
11
+ warnings?: Warning[];
11
12
  }): Promise<LanguageModelV4Prompt>;
12
13
  /**
13
14
  * Downloads files from URLs in the user messages.
@@ -70,7 +71,7 @@ export declare function prepareRetries({ maxRetries, abortSignal, additionalRetr
70
71
  };
71
72
  //#endregion
72
73
  //#region src/model/resolve-model.d.ts
73
- export declare function resolveLanguageModel(model: LanguageModel): LanguageModelV4;
74
+ export declare function resolveLanguageModel(model: LanguageModel, onWarning?: LogWarningsFunction): LanguageModelV4;
74
75
  //#endregion
75
76
  //#region src/util/merge-abort-signals.d.ts
76
77
  /**
@@ -248,10 +249,11 @@ export declare function createToolSearchState({ tools, toolCallers }: {
248
249
  /**
249
250
  * Logs the warning for the default stopWhen condition.
250
251
  */
251
- export declare function logDefaultStopConditionWarning({ stepCount, provider, modelId }: {
252
+ export declare function logDefaultStopConditionWarning({ stepCount, provider, modelId, onWarning }: {
252
253
  stepCount: number;
253
254
  provider: string;
254
255
  modelId: string;
256
+ onWarning?: LogWarningsFunction;
255
257
  }): void;
256
258
  //#endregion
257
259
  //#region src/generate-text/collect-tool-approvals.d.ts
@@ -361,12 +363,14 @@ export declare function toResponseMessages<TOOLS extends ToolSet>({ content: inp
361
363
  export declare class DefaultGenerateTextResult<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context, OUTPUT extends Output> implements GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT> {
362
364
  readonly steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps'];
363
365
  readonly totalUsage: LanguageModelUsage;
366
+ readonly stoppedBy: StoppedBy | undefined;
364
367
  private readonly _output;
365
368
  constructor(options: {
366
369
  initialResponseMessages: Array<ResponseMessage>;
367
370
  steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps'];
368
371
  output: InferCompleteOutput<OUTPUT> | undefined;
369
372
  totalUsage: LanguageModelUsage;
373
+ stoppedBy?: StoppedBy;
370
374
  });
371
375
  private readonly initialResponseMessages;
372
376
  get finalStep(): StepResult<TOOLS, RUNTIME_CONTEXT>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["SandboxSession","SandboxSession","AssistantModelMessage","ToolModelMessage","_$__step_result0.StepResult","_$__content_part0.ContentPart","_$__generated_file0.GeneratedFile","_$__reasoning_output0.ReasoningOutput","_$__reasoning_output0.ReasoningFileOutput","_$__tool_call0.TypedToolCall","_$__tool_call0.StaticToolCall","_$__tool_call0.DynamicToolCall","_$__tool_result0.TypedToolResult","_$__tool_result0.StaticToolResult","_$__tool_result0.DynamicToolResult","_$__0.FinishReason","_$__0.LanguageModelResponseMetadata","_$__0.LanguageModelRequestMetadata"],"sources":["../../src/prompt/convert-to-language-model-prompt.ts","../../src/prompt/create-tool-model-output.ts","../../src/prompt/prepare-tool-choice.ts","../../src/prompt/prepare-tools.ts","../../src/prompt/prepare-language-model-call-options.ts","../../src/util/prepare-retries.ts","../../src/model/resolve-model.ts","../../src/util/merge-abort-signals.ts","../../src/util/set-abort-timeout.ts","../../src/util/merge-callbacks.ts","../../src/util/merge-objects.ts","../../src/telemetry/create-telemetry-dispatcher.ts","../../src/telemetry/filter-included-context.ts","../../src/generate-text/restricted-telemetry-dispatcher.ts","../../src/generate-text/parse-tool-call.ts","../../src/generate-text/stream-retry-attempt-boundary.ts","../../src/generate-text/execute-tools-from-stream.ts","../../src/generate-text/is-output-chunk.ts","../../src/generate-text/validate-tool-context.ts","../../src/tool-search/prepare-tool-search.ts","../../src/agent/default-stop-condition.ts","../../src/generate-text/collect-tool-approvals.ts","../../src/generate-text/tool-approval-signature.ts","../../src/generate-text/validate-tool-approvals.ts","../../src/generate-text/resolve-tool-approval.ts","../../src/generate-text/to-response-messages.ts","../../src/generate-text/default-generate-text-result.ts","../../src/generate-text/resolve-generated-file-data.ts","../../src/generate-text/convert-language-model-content.ts","../../src/generate-text/calculate-tokens-per-second.ts","../../src/generate-text/tool-call-concurrency.ts"],"mappings":";;;;wBAmCsB,+BACpB,QACA,eACA,UACA,aAGA;EAEA,QAAQ;EACR,eAAe,eAAe;EAC9B,UAAU;EACV,cAAc;EACd;IACE,QAAQ;;;;wBAuWU,eACpB,UAAU,gBACV,UAAU,kBACV,eAAe,eAAe,WAC9B,cAAc,cACb,QACD;EAAiB;EAA+B,MAAM;;wBA0OxC,sBACd,QAGA,UACA,UACA;EAEA,QAAQ;EACR;EACA,WAAW;EACX,kBAAkB;IAEd;IAA+B,MAAM;;IA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C9D,SACA,WACA,aACA,sBACA,uBACA,OACA,UACA,aACA;EAEA,SAAS,MAAM;EACf,WAAW,MAAM,cAAc;EAC/B,aAAa,MAAM,WAAW;EAC9B,sBAAsB,MAAM,0BAA0B;EACtD,uBAAuB,MAAM,2BAA2B;EACxD,OAAO;EACP,WAAW;EACX,cAAc;EACd,yBAAyB;IACvB,QAAQ,MAAM,YAAY;;;;;;;;;wBChCd,2BACd,QACA;EAEA;EACA;;;;;;;wBCNc,2BACd;;;;;;;wBA+BoB,mBAAmB,OAAO,UAC9C,OACA,aACA,aACA;EAEA,OAAO,MAAM;EACb;EACA,cAAc;EACd,UAAU,MAAM,OAAO,kBAAkB,QAAQ;IAC/C,QAAQ,MAAM"}
1
+ {"version":3,"file":"index.d.ts","names":["SandboxSession","SandboxSession","AssistantModelMessage","ToolModelMessage","_$__step_result0.StepResult","_$__content_part0.ContentPart","_$__generated_file0.GeneratedFile","_$__reasoning_output0.ReasoningOutput","_$__reasoning_output0.ReasoningFileOutput","_$__tool_call0.TypedToolCall","_$__tool_call0.StaticToolCall","_$__tool_call0.DynamicToolCall","_$__tool_result0.TypedToolResult","_$__tool_result0.StaticToolResult","_$__tool_result0.DynamicToolResult","_$__0.FinishReason","_$__0.LanguageModelResponseMetadata","_$__0.LanguageModelRequestMetadata"],"sources":["../../src/prompt/convert-to-language-model-prompt.ts","../../src/prompt/create-tool-model-output.ts","../../src/prompt/prepare-tool-choice.ts","../../src/prompt/prepare-tools.ts","../../src/prompt/prepare-language-model-call-options.ts","../../src/util/prepare-retries.ts","../../src/model/resolve-model.ts","../../src/util/merge-abort-signals.ts","../../src/util/set-abort-timeout.ts","../../src/util/merge-callbacks.ts","../../src/util/merge-objects.ts","../../src/telemetry/create-telemetry-dispatcher.ts","../../src/telemetry/filter-included-context.ts","../../src/generate-text/restricted-telemetry-dispatcher.ts","../../src/generate-text/parse-tool-call.ts","../../src/generate-text/stream-retry-attempt-boundary.ts","../../src/generate-text/execute-tools-from-stream.ts","../../src/generate-text/is-output-chunk.ts","../../src/generate-text/validate-tool-context.ts","../../src/tool-search/prepare-tool-search.ts","../../src/agent/default-stop-condition.ts","../../src/generate-text/collect-tool-approvals.ts","../../src/generate-text/tool-approval-signature.ts","../../src/generate-text/validate-tool-approvals.ts","../../src/generate-text/resolve-tool-approval.ts","../../src/generate-text/to-response-messages.ts","../../src/generate-text/default-generate-text-result.ts","../../src/generate-text/resolve-generated-file-data.ts","../../src/generate-text/convert-language-model-content.ts","../../src/generate-text/calculate-tokens-per-second.ts","../../src/generate-text/tool-call-concurrency.ts"],"mappings":";;;;wBAmCsB,+BACpB,QACA,eACA,UACA,aAGA,UACA;EAEA,QAAQ;EACR,eAAe,eAAe;EAC9B,UAAU;EACV,cAAc;EACd;EACA,WAAW;IACT,QAAQ;;;;wBA8WU,eACpB,UAAU,gBACV,UAAU,kBACV,eAAe,eAAe,WAC9B,cAAc,cACb,QACD;EAAiB;EAA+B,MAAM;;wBA0OxC,sBACd,QAGA,UACA,UACA;EAEA,QAAQ;EACR;EACA,WAAW;EACX,kBAAkB;IAEd;IAA+B,MAAM;;IAEvC;;;wBC7pBkB,wBACpB,YACA,OACA,QACA,MACA;EAEA;EACA;EACA;EACA,MAAM;EACN;IACE,QAAQ;;;wBCZI,oBACd;EAGA,YAAY;IACV;;;wBCMkB,aAAa,cAAc,WAC/C,OACA,WACA,cACA,sBAAsB;EAEtB,OAAO;EACP,YAAY,UAAU;EACtB,eAAe,oBAAoB;EACnC,uBAAuBA;IACrB,QACF,MAAM,8BAA8B;;;;;;wBCnBtB,kCACd,iBACA,aACA,MACA,MACA,iBACA,kBACA,MACA,eACA,aACC,2BAA2B;;;;;;wBCPd,iBACd,YACA,aACA,0BACA,WACA;EAEA;EACA,aAAa;EACb,2BAA2B;EAC3B;EACA;;EAEA;EACA,OAAO;;;;wBCeO,qBACd,OAAO,eACP,YAAY,sBACX;;;;;;;;;;;;;wBC7Ba,qBACX,UAAU,6CACZ;;;;;;;;;;;;;;;;wBCDa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ortTimeout, C as resolveToolApproval, E as DefaultGenerateTextResult, Et as logWarnings, G as addLanguageModelUsage, H as mergeAbortSignals, J as standardizePrompt, K as asLanguageModelUsage, O as validateToolContext, P as convertLanguageModelContent, Q as createToolModelOutput, R as collectToolApprovals, S as filterIncludedContext, V as prepareRetries, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, a as createAsyncIterableStream, c as validateApprovedToolApprovals, d as verifyToolApprovalSignature, et as downloadAssets, g as DefaultStepResult, h as createRestrictedTelemetryDispatcher, ht as resolveLanguageModel, k as createToolSearchState, n as logDefaultStopConditionWarning, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, q as createNullLanguageModelUsage, r as isOutputChunk, s as prepareToolCallConcurrency, st as createDefaultDownloadFunction, tt as mapToolResultOutput, u as signToolApproval, w as parseToolCall, x as mergeCallbacks, z as calculateTokensPerSecond } from "../default-stop-condition-wtuJTiTo.js";
1
+ import { $ as convertToLanguageModelPrompt, B as setAbortTimeout, C as resolveToolApproval, Dt as logWarnings, E as DefaultGenerateTextResult, G as addLanguageModelUsage, H as mergeAbortSignals, J as standardizePrompt, K as asLanguageModelUsage, O as validateToolContext, P as convertLanguageModelContent, Q as createToolModelOutput, R as collectToolApprovals, S as filterIncludedContext, V as prepareRetries, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, a as createAsyncIterableStream, c as validateApprovedToolApprovals, d as verifyToolApprovalSignature, et as downloadAssets, g as DefaultStepResult, h as createRestrictedTelemetryDispatcher, ht as resolveLanguageModel, k as createToolSearchState, n as logDefaultStopConditionWarning, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, q as createNullLanguageModelUsage, r as isOutputChunk, s as prepareToolCallConcurrency, st as createDefaultDownloadFunction, tt as mapToolResultOutput, u as signToolApproval, w as parseToolCall, x as mergeCallbacks, z as calculateTokensPerSecond } from "../default-stop-condition-D8PwkeWe.js";
2
2
  import { convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
3
  export { DefaultGenerateTextResult, DefaultStepResult, addLanguageModelUsage, asLanguageModelUsage, calculateTokensPerSecond, collectToolApprovals, convertAsyncIteratorToReadableStream, convertLanguageModelContent, convertToLanguageModelPrompt, createAsyncIterableStream, createDefaultDownloadFunction, createNullLanguageModelUsage, createRestrictedTelemetryDispatcher, createTelemetryDispatcher, createToolModelOutput, createToolSearchState, downloadAssets, filterIncludedContext, isOutputChunk, logDefaultStopConditionWarning, logWarnings, mapToolResultOutput, mapWithConcurrency, mergeAbortSignals, mergeCallbacks, mergeObjects, parseToolCall, prepareLanguageModelCallOptions as prepareCallSettings, prepareLanguageModelCallOptions, prepareRetries, prepareToolCallConcurrency, prepareToolChoice, prepareTools, resolveLanguageModel, resolveToolApproval, setAbortTimeout, signToolApproval, standardizePrompt, toResponseMessages, validateApprovedToolApprovals, validateToolContext, verifyToolApprovalSignature };
@@ -16,6 +16,38 @@ A [steering message](#steering) that is waiting when the model finishes its answ
16
16
 
17
17
  The AI SDK provides built-in loop control through two parameters: `stopWhen` for defining stopping conditions and `prepareStep` for modifying settings (model, tools, messages, and more) between steps.
18
18
 
19
+ ## Why the Loop Stopped
20
+
21
+ `stoppedBy` tells you which of these ended the loop. It is on the `generateText` and `streamText` results, the `onEnd` callback, and the final `finish` stream part:
22
+
23
+ ```ts
24
+ import { ToolLoopAgent, isStepCount } from 'ai';
25
+ __PROVIDER_IMPORT__;
26
+
27
+ const agent = new ToolLoopAgent({
28
+ model: __MODEL__,
29
+ tools: {
30
+ // your tools here
31
+ },
32
+ stopWhen: isStepCount(5),
33
+ });
34
+
35
+ const result = await agent.generate({
36
+ prompt: 'Analyze this dataset and create a summary report',
37
+ });
38
+
39
+ if (result.stoppedBy === 'stop-condition') {
40
+ // the step limit ended the loop before the model finished
41
+ }
42
+ ```
43
+
44
+ - `model`: the model finished without tool calls that continue the loop. `finishReason` tells how its last call finished, e.g. `stop` or `length`.
45
+ - `stop-condition`: a stop condition was met, e.g. `isStepCount(5)`.
46
+ - `tool-without-execute`: a tool call needs a result from a tool without an `execute` function.
47
+ - `approval`: a tool call needs an [approval](/docs/agents/tool-approvals).
48
+
49
+ `finishReason` only describes the last model call, so a loop that hits `isStepCount(5)` still reports `tool-calls`. `stoppedBy` tells these cases apart. `WorkflowAgent` and `HarnessAgent` do not report it yet.
50
+
19
51
  ## Stop Conditions
20
52
 
21
53
  The `stopWhen` parameter controls when to stop execution when there are tool results in the last step. By default, `ToolLoopAgent` stops after 20 steps using `isStepCount(20)`. This default is a safety measure to prevent runaway loops that could result in excessive API calls and costs.
@@ -547,7 +579,7 @@ if (outcome.type === 'delivered') {
547
579
  }
548
580
  ```
549
581
 
550
- A message is delivered when it is part of the messages that are sent to the model, after `prepareStep`. It is not delivered when the loop ends before the next step boundary, or when `prepareStep` removes it. The `reason` is one of:
582
+ A message is delivered when it is part of the messages that are sent to the model, after `prepareStep`. It is not delivered when the loop ends before the next step boundary, or when `prepareStep` removes it. `prepareStep` can copy the message, turn its text into a text part, or add provider options to its parts and it still counts as delivered. A message whose text `prepareStep` changes counts as removed, so add details like timestamps before you send the message. The `reason` is one of:
551
583
 
552
584
  - `finished`: the loop ended before the message could be added.
553
585
  - `removed-by-prepare-step`: `prepareStep` returned messages without it.
@@ -556,6 +588,8 @@ A message is delivered when it is part of the messages that are sent to the mode
556
588
  - `aborted`: the loop was aborted.
557
589
  - `error`: the loop failed.
558
590
 
591
+ A message sent after the loop ended is not delivered and has the reason the loop ended with, e.g. `aborted` after an abort.
592
+
559
593
  Pass an `id` to make retries safe. Sending a message again with the same `id` returns the outcome of the first message.
560
594
 
561
595
  ### Saving Steering Messages
@@ -71,14 +71,15 @@ A model can return several tool calls in one response. `generateText`, `streamTe
71
71
  `opaPolicy` therefore evaluates every tool call after the first one of a response twice, unless the first evaluation already denies it:
72
72
 
73
73
  1. With `messages` as they were sent to the model.
74
- 2. With the earlier tool calls of the same response appended as an assistant message. Tool calls that the policy denied are followed by a tool message with their `execution-denied` result. The other tool calls have no result yet.
74
+ 2. With the earlier tool calls of the same response appended as an assistant message. Tool calls that are denied are followed by a tool message with their `execution-denied` result. The other tool calls have no result yet.
75
75
 
76
76
  The more restrictive decision applies: `deny` before `requires-approval`, before no matching rule, before `allow`.
77
77
 
78
78
  - A limit such as a budget, a quota, or "only one delete per conversation" counts the earlier tool calls of the same response.
79
79
  - A rule that allows a tool call only after another one, such as "deploy only after the tests ran", is not satisfied by a tool call of the same response, because that call has not run yet.
80
+ - Check a prerequisite through the earlier tool's result in history, not through the presence of its tool call. A tool call does not prove that the tool ran or succeeded. This also matters when an approved tool call is evaluated again before it runs: the history then contains the response with the tool calls, but not their results.
80
81
  - Base a limit that must hold within one response on tool calls, not on tool results. The earlier tool calls of a response have no results when the policy is evaluated.
81
- - OPA receives two queries for such a tool call, so it appears twice in OPA decision logs. A custom `toInput` is called twice as well. When it returns the same input both times, for example because it does not use `messages`, the policy is evaluated once.
82
+ - OPA receives two queries for such a tool call, so it appears twice in OPA decision logs. A custom `toInput` is called twice as well. When it returns the same input both times, for example because it does not use `messages`, the policy is evaluated once. With `wrapMcpTools` in hard allowlist mode (`default: 'denied'`), a tool call whose first evaluation is `not-applicable` is treated as denied by the fallback and evaluated once.
82
83
  - `opaPolicy` recognizes the tool calls of one response by the `messages` array they are evaluated with. `generateText`, `streamText`, and `ToolLoopAgent` pass the same array for all tool calls of a response and a new array for every response. When a caller passes a separate array for each tool call, `opaPolicy` evaluates each tool call once, with `messages` as passed. A caller must not pass one array for several responses: the tool calls of the earlier responses would count as earlier tool calls of the later ones.
83
84
 
84
85
  ### Tool calls that a user approved
@@ -350,6 +351,8 @@ Defaults for uncovered tools:
350
351
  - `'denied'`: hard allowlist mode. The policy enumerates what is allowed; everything else is rejected.
351
352
  - `'approved'`: allow. Only when the discovery source is fully trusted.
352
353
 
354
+ When the approval is an `opaPolicy` approval, the fallback is applied to each policy evaluation for a tool call, before the evaluations are compared. This holds when you pass `opaPolicy(...)` or `shadow(opaPolicy(...))` directly. A custom wrapper function around it hides the fallback from the policy, so the fallback then applies to the combined decision only.
355
+
353
356
  Despite the name, it works on any `Record<string, Tool>`.
354
357
 
355
358
  ## Allow-all when no policy is configured
@@ -157,6 +157,16 @@ const agent = new ToolLoopAgent({
157
157
  await runAgentTUI({ title: 'Weather Agent', agent });
158
158
  ```
159
159
 
160
+ Tool calls are decided one at a time, in the order the agent requested them.
161
+ While the terminal UI waits for a decision, the tool call that the decision
162
+ applies to is marked with `approve? y/n` and shown with its input, regardless of
163
+ the `tools` display mode. When the input does not fit on the screen, you can
164
+ only approve after you have scrolled to the end of the input.
165
+
166
+ Tool sections show tool input and output as they are, without markdown
167
+ formatting. Invisible Unicode format characters, such as bidirectional controls
168
+ and zero-width characters, are shown as escapes like `\u{202e}`.
169
+
160
170
  ## Compatibility
161
171
 
162
172
  When using the `agent` option, the agent must be runnable directly from terminal
@@ -218,6 +218,65 @@ const mcpClient = await createMCPClient({
218
218
 
219
219
  You can also bring your own transport by implementing the `MCPTransport` interface for specific requirements not covered by the standard transports.
220
220
 
221
+ ### WebMCP Transport
222
+
223
+ `Experimental_WebMCPTransport` (aliased below as `WebMCPTransport`) adapts tools
224
+ registered with the browser's
225
+ [`document.modelContext`](https://webmachinelearning.github.io/webmcp/) to the
226
+ existing MCP client:
227
+
228
+ ```ts
229
+ import {
230
+ createMCPClient,
231
+ Experimental_WebMCPTransport as WebMCPTransport,
232
+ } from '@ai-sdk/mcp';
233
+
234
+ // Run in a browser with WebMCP enabled, after checking API availability.
235
+ const client = await createMCPClient({
236
+ transport: new WebMCPTransport({ modelContext: document.modelContext }),
237
+ });
238
+
239
+ const tools = await client.tools();
240
+ ```
241
+
242
+ The required `modelContext` provides WebMCP's `getTools` and `executeTool`
243
+ methods. The optional `fromOrigins: string[]` constructor option discovers tools
244
+ exposed by additional frame origins, subject to browser permissions. The package
245
+ exports structural `Experimental_WebMCPModelContext` and
246
+ `Experimental_WebMCPTool` types; use browser API
247
+ typings such as `webmcp-types` to declare `document.modelContext`.
248
+
249
+ Use the tool names returned by `listTools` or `tools`: duplicate names across
250
+ frames receive stable aliases such as `getCart_2`. Results include text `content`
251
+ and parsed `structuredContent`. WebMCP `OperationError` failures become tool
252
+ results with `isError: true`; other failures reject the request.
253
+
254
+ WebMCP is an experimental browser API, not an HTTP MCP endpoint. Tool discovery
255
+ and execution happen in the page. To keep model inference on your backend, send
256
+ tool definitions to your API route, then execute the returned calls in
257
+ [`useChat.onToolCall`](/docs/ai-sdk-ui/chatbot-tool-usage) and return results with
258
+ `addToolOutput`. On the backend,
259
+ [`createMCPTools`](/docs/reference/ai-sdk-core/create-mcp-tools) validates and
260
+ converts those definitions into model-facing tools without `execute` functions:
261
+
262
+ ```ts
263
+ import { createMCPTools } from '@ai-sdk/mcp';
264
+
265
+ const { messages, tools: definitions } = await request.json();
266
+ const tools = createMCPTools(definitions);
267
+ ```
268
+
269
+ Pass `tools` to `streamText` and to `convertToModelMessages(messages, { tools })`
270
+ so returned MCP results are converted to model content. The
271
+ [shopping cart example](https://github.com/vercel/ai/tree/main/examples/ai-e2e-next/app/chat/webmcp)
272
+ demonstrates this flow with live page state. Follow the
273
+ [WebMCP shopping cart recipe](/cookbook/next/webmcp-tools) to build it.
274
+
275
+ Tool lists are snapshots. List tools again when the page's available tools change,
276
+ and close the client when the consuming component or browser connection is
277
+ disposed. Cancellation is forwarded to tool execution. Closing the client aborts
278
+ pending calls without unregistering the page's tools.
279
+
221
280
  <Note>
222
281
  The client returned by the `createMCPClient` function is a
223
282
  lightweight client intended for use in tool conversion. It currently does not
@@ -961,6 +961,12 @@ Called once when the full generation completes.
961
961
  type: 'FinishReason',
962
962
  description: 'Unified reason why the final step finished.',
963
963
  },
964
+ {
965
+ name: 'stoppedBy',
966
+ type: "'model' | 'stop-condition' | 'tool-without-execute' | 'approval' | undefined",
967
+ description:
968
+ 'Why the loop stopped. Unlike `finishReason`, it describes the whole loop, not the last model call. See [Loop Control](/docs/agents/loop-control#why-the-loop-stopped).',
969
+ },
964
970
  {
965
971
  name: 'usage',
966
972
  type: 'LanguageModelUsage',
@@ -86,6 +86,27 @@ fields. If AI SDK 5 is also installed, include its
86
86
  handle its warning array before accessing the options object used by AI SDK 6
87
87
  and 7.
88
88
 
89
+ #### Per-Call Warning Handler
90
+
91
+ You can pass `onWarning` to `generateText`, `streamText`, or `ToolLoopAgent` to
92
+ handle the warnings of a single call, e.g. to show them in a terminal UI instead
93
+ of writing them to stderr. When `onWarning` is set, the warnings of that call are
94
+ not sent to the global warning logger.
95
+
96
+ ```ts
97
+ const result = streamText({
98
+ model: __MODEL__,
99
+ prompt: 'Hello, world!',
100
+ onWarning: ({ warnings, provider, model }) => {
101
+ // Show the warnings in your UI
102
+ },
103
+ });
104
+ ```
105
+
106
+ `onWarning` receives the warnings of each step, including prompt deprecations
107
+ such as the legacy `image` content part. These are the same warnings as in
108
+ `step.warnings`, `result.warnings`, and the `start-step` stream part.
109
+
89
110
  ### Deprecation Warnings
90
111
 
91
112
  The default logger emits each deprecation code once per loaded SDK instance.
@@ -2022,6 +2022,13 @@ To see `generateText` in action, check out [these examples](#examples).
2022
2022
  },
2023
2023
  ],
2024
2024
  },
2025
+ {
2026
+ name: 'onWarning',
2027
+ type: '(options: { warnings: Warning[]; provider?: string; model?: string }) => void',
2028
+ isOptional: true,
2029
+ description:
2030
+ 'Callback that receives the warnings of the call, e.g. unsupported settings or deprecated prompt parts. When it is set, the warnings are not sent to the global warning logger (`AI_SDK_LOG_WARNINGS`).',
2031
+ },
2025
2032
  {
2026
2033
  name: 'onStepFinish',
2027
2034
  type: 'GenerateTextOnStepFinishCallback<TOOLS>',
@@ -2061,6 +2068,12 @@ To see `generateText` in action, check out [these examples](#examples).
2061
2068
  description:
2062
2069
  'The raw reason why the generation finished (from the provider).',
2063
2070
  },
2071
+ {
2072
+ name: 'stoppedBy',
2073
+ type: "'model' | 'stop-condition' | 'tool-without-execute' | 'approval' | undefined",
2074
+ description:
2075
+ 'Why the generation stopped its tool loop. Unlike `finishReason`, which describes the last model call, it tells whether the model, a stop condition, a tool without an `execute` function, or a tool approval ended the loop. See [Loop Control](/docs/agents/loop-control#why-the-loop-stopped).',
2076
+ },
2064
2077
  {
2065
2078
  name: 'usage',
2066
2079
  type: 'LanguageModelUsage',
@@ -2673,6 +2686,12 @@ To see `generateText` in action, check out [these examples](#examples).
2673
2686
  description:
2674
2687
  'The raw reason why the generation finished (from the provider).',
2675
2688
  },
2689
+ {
2690
+ name: 'stoppedBy',
2691
+ type: "'model' | 'stop-condition' | 'tool-without-execute' | 'approval' | undefined",
2692
+ description:
2693
+ 'Why the generation stopped its tool loop. Unlike `finishReason`, which describes the last model call, it tells whether the model, a stop condition, a tool without an `execute` function, or a tool approval ended the loop. See [Loop Control](/docs/agents/loop-control#why-the-loop-stopped). Always set by `generateText` and `ToolLoopAgent`.',
2694
+ },
2676
2695
  {
2677
2696
  name: 'usage',
2678
2697
  type: 'LanguageModelUsage',
@@ -1766,6 +1766,13 @@ retain the content their contracts require.
1766
1766
  },
1767
1767
  ],
1768
1768
  },
1769
+ {
1770
+ name: 'onWarning',
1771
+ type: '(options: { warnings: Warning[]; provider?: string; model?: string }) => void',
1772
+ isOptional: true,
1773
+ description:
1774
+ 'Callback that receives the warnings of the call, e.g. unsupported settings or deprecated prompt parts. When it is set, the warnings are not sent to the global warning logger (`AI_SDK_LOG_WARNINGS`).',
1775
+ },
1769
1776
  {
1770
1777
  name: 'onStepFinish',
1771
1778
  type: 'GenerateTextOnStepFinishCallback<TOOLS>',
@@ -1795,6 +1802,12 @@ retain the content their contracts require.
1795
1802
  description:
1796
1803
  'The raw reason why the generation finished (from the provider).',
1797
1804
  },
1805
+ {
1806
+ name: 'stoppedBy',
1807
+ type: "'model' | 'stop-condition' | 'tool-without-execute' | 'approval' | undefined",
1808
+ description:
1809
+ 'Why the generation stopped its tool loop. Unlike `finishReason`, which describes the last model call, it tells whether the model, a stop condition, a tool without an `execute` function, or a tool approval ended the loop. See [Loop Control](/docs/agents/loop-control#why-the-loop-stopped).',
1810
+ },
1798
1811
  {
1799
1812
  name: 'output',
1800
1813
  type: 'COMPLETE_OUTPUT | undefined',
@@ -2723,6 +2736,12 @@ retain the content their contracts require.
2723
2736
  description:
2724
2737
  'The raw reason why the generation finished (from the provider).',
2725
2738
  },
2739
+ {
2740
+ name: 'stoppedBy',
2741
+ type: "PromiseLike<'model' | 'stop-condition' | 'tool-without-execute' | 'approval' | undefined>",
2742
+ description:
2743
+ 'Why the generation stopped its tool loop. Unlike `finishReason`, which describes the last model call, it tells whether the model, a stop condition, a tool without an `execute` function, or a tool approval ended the loop. See [Loop Control](/docs/agents/loop-control#why-the-loop-stopped). Like `finishReason`, it rejects when the stream is aborted. Automatically consumes the stream.',
2744
+ },
2726
2745
  {
2727
2746
  name: 'usage',
2728
2747
  type: 'Promise<LanguageModelUsage>',
@@ -4023,6 +4042,12 @@ retain the content their contracts require.
4023
4042
  description:
4024
4043
  'The raw reason why the generation finished (from the provider).',
4025
4044
  },
4045
+ {
4046
+ name: 'stoppedBy',
4047
+ type: "'model' | 'stop-condition' | 'tool-without-execute' | 'approval' | undefined",
4048
+ description:
4049
+ 'Why the generation stopped its tool loop. See [Loop Control](/docs/agents/loop-control#why-the-loop-stopped).',
4050
+ },
4026
4051
  {
4027
4052
  name: 'totalUsage',
4028
4053
  type: 'LanguageModelUsage',
@@ -526,6 +526,13 @@ To see `ToolLoopAgent` in action, check out [these examples](#examples).
526
526
  description:
527
527
  "Callback invoked when an agent step that started fails before it produces a step result, i.e. when the provider call throws or rejects, or when the model stream ends without output. `onStepEnd` is not called for such a step. A provider `error` chunk does not fail the step: it still ends with `onStepEnd` and `finishReason: 'error'`. The event contains all properties of the `onStepStart` event of the step that failed, plus `error`. In `generate()`, aborts and timeouts also end the step here. In `stream()`, they end the step with `onAbort` instead. Only available in the constructor.",
528
528
  },
529
+ {
530
+ name: 'onWarning',
531
+ type: '(options: { warnings: Warning[]; provider?: string; model?: string }) => void',
532
+ isOptional: true,
533
+ description:
534
+ 'Callback that receives the warnings of the agent calls, e.g. unsupported settings, deprecated prompt parts, or reaching the default step limit. When it is set, the warnings are not sent to the global warning logger (`AI_SDK_LOG_WARNINGS`). Only available in the constructor.',
535
+ },
529
536
  {
530
537
  name: 'onError',
531
538
  type: '(event: { error: unknown }) => Promise<void> | void',
@@ -0,0 +1,65 @@
1
+ ---
2
+ title: createMCPTools
3
+ description: Convert MCP tool definitions into AI SDK tools without a connection.
4
+ ---
5
+
6
+ # `createMCPTools()`
7
+
8
+ Converts an array of MCP tool definitions into AI SDK dynamic tools without
9
+ `execute` functions. Use it when the model runs on your backend and tools execute
10
+ elsewhere, such as in a browser using
11
+ [`Experimental_WebMCPTransport`](/docs/ai-sdk-core/mcp-tools#webmcp-transport).
12
+
13
+ ```ts
14
+ import { createMCPTools } from '@ai-sdk/mcp';
15
+ import { convertToModelMessages, streamText } from 'ai';
16
+
17
+ // In your API route, after applying application-specific request policies:
18
+ const { messages, tools: definitions } = await request.json();
19
+ const tools = createMCPTools(definitions);
20
+
21
+ const result = streamText({
22
+ model,
23
+ messages: await convertToModelMessages(messages, { tools }),
24
+ tools,
25
+ });
26
+ ```
27
+
28
+ The browser obtains the definitions using `const { tools } = await client.listTools()`
29
+ and sends that array with the chat request. It handles returned calls through
30
+ `useChat.onToolCall` and submits results with `addToolOutput`. The helper does not
31
+ connect to a browser or create an MCP client.
32
+
33
+ ## Parameters
34
+
35
+ - **`definitions: unknown`** (required): an array in the format of
36
+ `listTools().tools`. Each item must contain `name` and `inputSchema` and can
37
+ include MCP fields such as `description`, `title`, `annotations`, and `_meta`.
38
+ Deserialized request data can be passed directly.
39
+
40
+ ## Returns
41
+
42
+ A record of tool names to AI SDK dynamic tools. The helper:
43
+
44
+ - Validates the MCP definition structure and rejects duplicate names.
45
+ - Converts input schemas using the same automatic schema conversion as
46
+ `client.tools()`, including defaulting `properties` to `{}` and setting
47
+ `additionalProperties: false`.
48
+ - Preserves titles, standard MCP annotations, MCP App metadata, and `_meta`.
49
+ - Adds `toModelOutput` to convert returned MCP text and image content into model
50
+ content. Pass `{ tools }` to `convertToModelMessages` to use this conversion
51
+ for browser tool results in chat history.
52
+ - Leaves `execute` unset. The application forwards calls and returns results.
53
+
54
+ As with `client.tools()` in automatic schema mode, declared MCP output schemas
55
+ are not used to validate results.
56
+
57
+ ## Errors
58
+
59
+ Throws `MCPClientError` for malformed definitions or duplicate names. API routes
60
+ can catch it and return HTTP 400. Validation checks the MCP definition structure;
61
+ it does not establish trust, enforce application limits, or fully validate JSON
62
+ Schema documents. Apply your own authentication and tool policies to requests.
63
+
64
+ To execute tools over an MCP connection in the same runtime as the model, use
65
+ [`client.tools()`](/docs/reference/ai-sdk-core/create-mcp-client) instead.
@@ -151,6 +151,9 @@ type TerminalPartDisplayMode =
151
151
  section appears, then collapse it.
152
152
  - `"hidden"`: Omit the section entirely.
153
153
 
154
+ A tool call that is waiting for an approval decision is always shown with its
155
+ input until the decision is made, regardless of the display mode.
156
+
154
157
  ### `ResponseStatisticsMode`
155
158
 
156
159
  Controls which response statistic is shown:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "7.0.179",
3
+ "version": "7.0.181",
4
4
  "type": "module",
5
5
  "description": "AI SDK by Vercel - build apps like ChatGPT, Claude, Gemini, and more with a single interface for any model using the Vercel AI Gateway or go direct to OpenAI, Anthropic, Google, or any other model provider.",
6
6
  "license": "Apache-2.0",
@@ -43,20 +43,20 @@
43
43
  }
44
44
  },
45
45
  "dependencies": {
46
- "@ai-sdk/gateway": "4.0.152",
46
+ "@ai-sdk/gateway": "4.0.154",
47
47
  "@ai-sdk/provider": "4.0.39",
48
48
  "@ai-sdk/provider-utils": "5.0.83"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@ai-sdk/amazon-bedrock": "5.0.146",
52
52
  "@ai-sdk/deepseek": "3.0.89",
53
- "@ai-sdk/google": "4.0.124",
53
+ "@ai-sdk/google": "4.0.125",
54
54
  "@ai-sdk/groq": "4.0.86",
55
55
  "@ai-sdk/huggingface": "2.0.95",
56
56
  "@ai-sdk/moonshotai": "3.0.95",
57
57
  "@ai-sdk/openai": "4.0.122",
58
58
  "@ai-sdk/test-server": "2.0.4",
59
- "@ai-sdk/xai": "5.0.48",
59
+ "@ai-sdk/xai": "5.0.49",
60
60
  "@edge-runtime/vm": "^5.0.0",
61
61
  "@smithy/eventstream-codec": "^4.3.3",
62
62
  "@smithy/util-utf8": "^4.3.3",
@@ -1,4 +1,5 @@
1
- import { logWarnings } from '../logger/log-warnings';
1
+ import { createLogWarnings } from '../logger/create-log-warnings';
2
+ import type { LogWarningsFunction } from '../logger/log-warnings';
2
3
  import type { StopCondition } from '../generate-text/stop-condition';
3
4
 
4
5
  /**
@@ -8,12 +9,14 @@ export function logDefaultStopConditionWarning({
8
9
  stepCount,
9
10
  provider,
10
11
  modelId,
12
+ onWarning,
11
13
  }: {
12
14
  stepCount: number;
13
15
  provider: string;
14
16
  modelId: string;
17
+ onWarning?: LogWarningsFunction;
15
18
  }): void {
16
- logWarnings({
19
+ createLogWarnings(onWarning)({
17
20
  provider,
18
21
  model: modelId,
19
22
  warnings: [
@@ -34,6 +37,7 @@ export function logDefaultStopConditionWarning({
34
37
  */
35
38
  export function createDefaultStopCondition(
36
39
  stepCount: number,
40
+ onWarning?: LogWarningsFunction,
37
41
  ): StopCondition<any, any> {
38
42
  return ({ steps }) => {
39
43
  if (steps.length !== stepCount) {
@@ -41,7 +45,12 @@ export function createDefaultStopCondition(
41
45
  }
42
46
 
43
47
  const { provider, modelId } = steps[steps.length - 1].model;
44
- logDefaultStopConditionWarning({ stepCount, provider, modelId });
48
+ logDefaultStopConditionWarning({
49
+ stepCount,
50
+ provider,
51
+ modelId,
52
+ onWarning,
53
+ });
45
54
 
46
55
  return true;
47
56
  };
@@ -40,6 +40,7 @@ import type {
40
40
  import type { ToolInputRefinement } from '../generate-text/tool-input-refinement';
41
41
  import type { ToolOrder } from '../generate-text/tool-order';
42
42
  import type { ToolsContextParameter } from '../generate-text/tools-context-parameter';
43
+ import type { LogWarningsFunction } from '../logger/log-warnings';
43
44
  import type { LanguageModelCallOptions } from '../prompt/language-model-call-options';
44
45
  import type { Instructions, Prompt } from '../prompt/prompt';
45
46
  import type { RequestOptions } from '../prompt/request-options';
@@ -273,6 +274,16 @@ export type ToolLoopAgentSettings<
273
274
  NoInfer<OUTPUT>
274
275
  >;
275
276
 
277
+ /**
278
+ * Callback that receives the warnings of the agent calls, e.g. unsupported
279
+ * settings, deprecated prompt parts, or reaching the default step limit.
280
+ * When it is set, the warnings are not sent to the global warning logger
281
+ * (`AI_SDK_LOG_WARNINGS`).
282
+ *
283
+ * Like `onStepError`, it can only be set here and not per call.
284
+ */
285
+ onWarning?: LogWarningsFunction;
286
+
276
287
  /**
277
288
  * Callback that is called when an error occurs. For `stream()` it receives
278
289
  * the errors of the stream, for `generate()` it receives the error before
@@ -147,7 +147,9 @@ export class ToolLoopAgent<
147
147
 
148
148
  const baseCallArgs = {
149
149
  ...settingsWithoutCallbacks,
150
- stopWhen: this.settings.stopWhen ?? createDefaultStopCondition(20),
150
+ stopWhen:
151
+ this.settings.stopWhen ??
152
+ createDefaultStopCondition(20, this.settings.onWarning),
151
153
  ...options,
152
154
  };
153
155