Skip to main content
Stop conditions determine when the agent’s tool execution loop should stop. Use them with the stop_when parameter in generate_text and stream_text.

StopCondition Type

A stop condition is a function that receives the current step result and returns 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 the StopCondition signature:

Combining Conditions

Create compound stop conditions:

Usage Pattern

The stop_when parameter accepts any StopCondition:

Best Practices

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.
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.
Use on_step_finish alongside stop conditions to monitor progress and debug agent behavior.