Loop Control
You can control both the execution flow and the settings at each step of the agent loop. The loop continues until:- A finish reasoning other than tool-calls is returned, or
- A tool that is invoked does not have an execute function, or
- A tool call needs approval, or
- A stop condition is met
stopWhen for defining stopping conditions and prepareStep for modifying settings (model, tools, messages, and more) between steps.
Stop Conditions
ThestopWhen parameter controls when to stop execution when there are tool results in the last step. By default, agents stop after 20 steps using stepCountIs(20).
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.
Use Built-in Conditions
The AI SDK provides several built-in stopping conditions:Combine Multiple Conditions
Combine multiple stopping conditions. The loop stops when it meets any condition:Create Custom Conditions
Build custom stopping conditions for specific requirements:Prepare Step
TheprepareStep 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.
Dynamic Model Selection
Switch models based on step requirements:Context Management
Manage growing conversation history in long-running loops:Tool Selection
Control which tools are available at each step:Message Modification
Transform messages before sending them to the model:Access Step Information
BothstopWhen and prepareStep receive detailed information about the current execution:
Forced Tool Calling
You can force the agent to always use tools by combiningtoolChoice: 'required' with a done tool that has no execute function. This pattern ensures the agent uses tools for every step and stops only when it explicitly signals completion.
toolChoice: 'required': Forces the model to call a tool at every step instead of generating text directly. This ensures the agent follows a structured workflow.donetool withoutexecute: A tool that has noexecutefunction acts as a termination signal. When the agent calls this tool, the loop stops because there’s no function to execute.- Accessing results: The final answer is available in
result.staticToolCalls, which contains tool calls that weren’t executed.
Manual Loop Control
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.
Implementing a Manual Loop
Build your own agent loop when you need full control over execution:- Message history management
- Step-by-step decision making
- Custom stopping conditions
- Dynamic tool and model selection
- Error handling and recovery