Exceptions & Retries

Handle tool errors with exceptions and automatic retries.

If after a tool call you need to provide feedback to the model to change its behavior or exit the tool call loop, you can raise one of the following exceptions:

  • RetryAgentRun: Use this exception when you want to provide instructions to the model for how to change its behavior and have the model retry the tool call. The exception message will be passed to the model as a tool call error, allowing the model to retry or adjust its approach in the next iteration of the LLM loop.
This does not retry the full agent run. It only provides feedback to the model within the current run.
  • StopAgentRun: Use this exception when you want to exit the model execution loop and end the agent run. When raised from a tool function, the agent exits the tool call loop, and the run status is set to COMPLETED. Session data persists only when a database and the appropriate session/storage configuration are present.
This does not cancel the agent run. It completes the run after the current tool batch, rather than preventing already-issued sibling calls.

Using RetryAgentRun

Raise RetryAgentRun to give the model feedback so it can adjust its behavior:

Before running these examples, install the dependencies in your Python environment and set your OpenAI key:

uv pip install -U agno openai sqlalchemy
export OPENAI_API_KEY="your-api-key"

On PowerShell, use $Env:OPENAI_API_KEY="your-api-key".

retry_in_tool_call.py
from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.exceptions import RetryAgentRun
from agno.models.openai import OpenAIResponses
from agno.utils.log import logger
from agno.run import RunContext


def add_item(run_context: RunContext, item: str) -> str:
    """Add an item to the shopping list."""
    if not run_context.session_state:
        run_context.session_state = {}

    if "shopping_list" not in run_context.session_state:
        run_context.session_state["shopping_list"] = []

    run_context.session_state["shopping_list"].append(item)
    len_shopping_list = len(run_context.session_state["shopping_list"])

    if len_shopping_list < 3:
        raise RetryAgentRun(
            f"Shopping list is: {run_context.session_state['shopping_list']}. Minimum 3 items in the shopping list. "
            + f"Add {3 - len_shopping_list} more items.",
        )

    logger.info(f"The shopping list is now: {run_context.session_state.get('shopping_list')}")
    return f"The shopping list is now: {run_context.session_state.get('shopping_list')}"


agent = Agent(
    model=OpenAIResponses(id="gpt-5.2"),
    session_id="retry_example_session",
    db=SqliteDb(
        session_table="retry_example_session",
        db_file="tmp/retry_example.db",
    ),
    # Initialize the session state with empty shopping list
    session_state={"shopping_list": []},
    tools=[add_item],
    markdown=True,
)
agent.print_response("Add milk", stream=True)
print(f"Final session state: {agent.get_session_state(session_id='retry_example_session')}")

In this example, when add_item is called with fewer than 3 items, it raises RetryAgentRun with instructions. The model receives this as a tool call error and can call add_item again with additional items to meet the requirement.

Using StopAgentRun

Raise StopAgentRun to exit the tool call loop:

stop_in_tool_call.py
from agno.agent import Agent
from agno.exceptions import StopAgentRun
from agno.models.openai import OpenAIResponses
from agno.run import RunContext


def check_condition(run_context: RunContext, value: int) -> str:
    """Check a condition and stop tool calls if met."""
    if value > 100:
        raise StopAgentRun(
            f"Value {value} exceeds threshold. Stopping tool call execution."
        )
    return f"Value {value} is acceptable."


agent = Agent(
    model=OpenAIResponses(id="gpt-5.2"),
    tools=[check_condition],
    markdown=True,
)

# When the model calls check_condition with value > 100,
# the tool call loop will exit and the run will complete
agent.print_response("Use the check_condition tool to check if 150 is acceptable", stream=True)

In this example, when check_condition is called with a value greater than 100, it raises StopAgentRun. The current tool batch finishes, then the model loop stops without another model iteration and the run completes with status COMPLETED. Already-issued sibling tools can still run. This example has no database, so it does not persist session data.

Make sure to set AGNO_DEBUG=True if you want to see the debug logs.

Developer Resources