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.
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 toCOMPLETED. All session state, messages, tool calls, and tool results up to that point are stored in the database.
Using RetryAgentRun
This example shows how to use the RetryAgentRun exception to provide feedback to the model, allowing it to adjust its behavior:
1from kern.agent import Agent2from kern.db.sqlite import SqliteDb3from kern.exceptions import RetryAgentRun4from kern.models.openai import OpenAIResponses5from kern.utils.log import logger6from kern.run import RunContext789def add_item(run_context: RunContext, item: str) -> str:10 """Add an item to the shopping list."""11 if not run_context.session_state:12 run_context.session_state = {}13 14 if "shopping_list" not in run_context.session_state:15 run_context.session_state["shopping_list"] = []16 17 run_context.session_state["shopping_list"].append(item)18 len_shopping_list = len(run_context.session_state["shopping_list"])19 20 if len_shopping_list < 3:21 raise RetryAgentRun(22 f"Shopping list is: {run_context.session_state['shopping_list']}. Minimum 3 items in the shopping list. "23 + f"Add {3 - len_shopping_list} more items.",24 )25 26 logger.info(f"The shopping list is now: {run_context.session_state.get('shopping_list')}")27 return f"The shopping list is now: {run_context.session_state.get('shopping_list')}"282930agent = Agent(31 model=OpenAIResponses(id="gpt-5.2"),32 session_id="retry_example_session",33 db=SqliteDb(34 session_table="retry_example_session",35 db_file="tmp/retry_example.db",36 ),37 # Initialize the session state with empty shopping list38 session_state={"shopping_list": []},39 tools=[add_item],40 markdown=True,41)42agent.print_response("Add milk", stream=True)43print(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
This example shows how to use the StopAgentRun exception to exit the tool call loop:
1from kern.agent import Agent2from kern.exceptions import StopAgentRun3from kern.models.openai import OpenAIResponses4from kern.run import RunContext567def check_condition(run_context: RunContext, value: int) -> str:8 """Check a condition and stop tool calls if met."""9 if value > 100:10 raise StopAgentRun(11 f"Value {value} exceeds threshold. Stopping tool call execution."12 )13 return f"Value {value} is acceptable."141516agent = Agent(17 model=OpenAIResponses(id="gpt-5.2"),18 tools=[check_condition],19 markdown=True,20)2122# When the model calls check_condition with value > 100,23# the tool call loop will exit and the run will complete24agent.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 tool call loop exits immediately, and the run completes with status COMPLETED. All session state, messages, and tool calls up to that point are stored in the database.
Make sure to set AGNO_DEBUG=True if you want to see the debug logs.
Developer Resources
- View the RetryAgentRun schema
- View the StopAgentRun schema
- View Cookbook