You can control both the execution flow and the settings at each step of the agent loop. 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.
The stopWhen parameter controls when to stop execution when there are tool results in the last step. By default, agents stop after a single step using stepCountIs(1).
When you provide stopWhen, the agent continues executing after tool calls until a stopping condition is met. When the condition is an array, execution stops when any of the conditions are met.
The AI SDK provides several built-in stopping conditions:
import { Experimental_Agent as Agent, stepCountIs } from 'ai';
const agent = new Agent({
model: "anthropic/claude-sonnet-5.5",
tools: {
// your tools
},
stopWhen: stepCountIs(20), // Stop after 20 steps maximum
});
const result = await agent.generate({
prompt: 'Analyze this dataset and create a summary report',
});
The prepareStep callback runs before each step in the loop and defaults to the initial settings if you don't return any changes. Use it to modify settings, manage context, or implement dynamic behavior based on execution history.
Both stopWhen and prepareStep receive detailed information about the current execution:
prepareStep: async ({ model, // Current model configuration stepNumber, // Current step number (0-indexed) steps, // All previous steps with their results messages, // Messages to be sent to the model}) => { // Access previous tool calls and results const previousToolCalls = steps.flatMap(step => step.toolCalls); const previousResults = steps.flatMap(step => step.toolResults); // Make decisions based on execution history if (previousToolCalls.some(call => call.toolName === 'dataAnalysis')) { return { toolChoice: { type: 'tool', toolName: 'reportGenerator' }, }; } return {};},
For scenarios requiring complete control over the agent loop, you can use AI SDK Core functions (generateText and streamText) to implement your own loop management instead of using stopWhen and prepareStep. This approach provides maximum flexibility for complex workflows.