Limit tool-calling loops
Set a hard upper bound on iterative tool execution.
AI Tools · Function
Creates a stop condition that ends a tool-calling loop when it reaches a specified number of steps. Use it with stopWhen in generateText or streamText.
stepCountIs creates a stop condition for tool-calling loops. Pass the desired maximum step count, then provide the resulting condition to stopWhen in generateText or streamText; the condition becomes true when that count is reached.
stepCountIs(count: number): StopCondition| Name | Type | Description |
|---|---|---|
count | number | The maximum number of steps to execute before stopping the tool-calling loop. |
A StopCondition function that returns true when the step count reaches the specified number.
import { generateText, stepCountIs } from 'ai';
const result = await generateText({
model: yourModel,
tools: yourTools,
stopWhen: stepCountIs(3),
});Runs generation with tools and stops the tool-calling loop after three steps.
Set a hard upper bound on iterative tool execution.
Allow a model to call tools and process their results for a controlled number of rounds.
Pair a step limit with another stopping rule so whichever occurs first ends execution.
stepCountIs creates a StopCondition that returns true when execution reaches the specified step count. It is supplied to stopWhen in generateText or streamText.
Follow-up: How would you stop on either a step limit or a tool call? Use an array such as [stepCountIs(10), hasToolCall('finalAnswer')].
The count argument is the maximum number of steps allowed before the tool-calling loop stops. For example, stepCountIs(3) permits up to three steps.
Follow-up: What happens with stepCountIs(1)? It limits the loop to one step, which is also the default behavior for agents.
Pass the condition through stopWhen, for example stopWhen: stepCountIs(5), in a generateText or streamText call. This enables the model to continue after tool results until the condition is met.
Follow-up: How can multiple stopping rules be expressed? Provide an array of conditions; the loop stops when any condition becomes true.
stopWhengenerateTextstreamTexthasToolCallStopCondition