Stop Conditions
Control multi-turn execution with stopWhen. Use built-in helpers or custom conditions to stop by step count, tool calls, cost, or tokens.
Basic Usage
Built-in Stop Conditions
stepCountIs(n)
Stop after a specific number of steps:
hasToolCall(name)
Stop when a specific tool is called:
maxTokensUsed(n)
Stop after using a certain number of tokens:
maxCost(amount)
Stop after reaching a cost threshold:
finishReasonIs(reason)
Stop on a specific finish reason:
Combining Conditions
Pass an array to stop on any condition:
Execution stops when any condition is met.
Custom Stop Conditions
Create custom conditions with a function:
StopConditionContext
Custom functions receive:
StepResult
Each step contains:
Advanced Patterns
Time-Based Stopping
Stop after a time limit:
Content-Based Stopping
Stop based on response content:
Quality-Based Stopping
Stop when results meet quality threshold:
Combination with Early Exit
Combine conditions for complex logic:
Migration from maxToolRounds
If you were using maxToolRounds, migrate to stopWhen:
Default Behavior
If stopWhen is not specified, the default is stepCountIs(5).
Best Practices
Always Set Limits
Always include a hard limit to prevent runaway execution:
Log Stop Reasons
Track why execution stopped:
Test Conditions
Verify conditions work as expected:
See Also
- Tools - Multi-turn orchestration
- Dynamic Parameters - Adaptive behavior
- nextTurnParams - Tool-driven modifications