stop_when parameter in generate_text and stream_text.
StopCondition Type
True to stop the loop, or False to continue.
Built-in Stop Conditions
step_count_is
Stop after a specific number of steps.Signature
int
required
The maximum number of steps to execute before stopping.
Example
has_tool_call
Stop when a specific tool is called.Signature
str
required
The name of the tool that triggers the stop.
Example
Custom Stop Conditions
You can create custom stop conditions by defining a function that matches theStopCondition signature:
Combining Conditions
Create compound stop conditions:Usage Pattern
Thestop_when parameter accepts any StopCondition:
Best Practices
Always use a stop condition with tools
Always use a stop condition with tools
When providing tools, always include a
stop_when condition to prevent infinite loops. Either use step_count_is(n) for bounded execution or has_tool_call("finish") for explicit completion.Design a completion tool
Design a completion tool
For complex agents, create a dedicated “finish” or “complete” tool that the AI calls when done. Use
has_tool_call("finish") to stop the loop.Combine with callbacks for monitoring
Combine with callbacks for monitoring
Use
on_step_finish alongside stop conditions to monitor progress and debug agent behavior.