Sub topic 9
Reporting tool errors so the model can recover
This chapter assumes you can read JSON, write basic Python, and have seen the tool-calling loop: the model proposes a call, your code runs it, and the result goes back tagged with the call's id.
Why errors go back to the model
A tool call can fail in several ways. The model may name a tool that does not exist. It may send arguments that do not fit the schema. The function itself may raise an exception or time out.
If your code crashes on these failures, the user sees a stack trace. If your code instead returns the error as a tool result, the model can read it and try again. A model that sees "Unknown unit: kelvin" can retry with a valid unit. A model that sees nothing cannot.
The rule is simple. Every tool call gets exactly one result message with the matching id, even when the call failed.
Three kinds of failure
| Failure | Typical cause | Useful message |
|---|---|---|
| Unknown tool | Model invents a name | Name the bad tool and list valid ones |
| Bad arguments | Missing field, wrong type, value outside an enum | Say which argument and what is allowed |
| Tool failure | Network error, missing record, timeout | Say what happened and whether retrying can help |
Writing messages the model can act on
The model recovers only if the message tells it what to change. Compare these two results.
{"is_error": true, "content": "Error"}{"is_error": true, "content": "Bad arguments: unit must be 'celsius' or 'fahrenheit', got 'kelvin'"}The second names the argument, the allowed values, and the bad value. Keep messages short and factual. Do not include stack traces, file paths, connection strings, or secrets. The model may repeat them to the user, and they may reveal your system.
Code: turning failures into results
This dispatcher catches each failure type separately and returns a readable message. Note that TypeError covers wrong argument names, and the broad Exception handler catches everything else.
import json
def get_weather(city, unit="celsius"):
if unit not in ("celsius", "fahrenheit"):
raise ValueError("unit must be 'celsius' or 'fahrenheit', got " + repr(unit))
return {"city": city, "temperature": 7, "unit": unit}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call):
fn = TOOLS.get(call["name"])
if fn is None:
valid = ", ".join(sorted(TOOLS))
return {"is_error": True,
"content": "Unknown tool: " + str(call["name"]) + ". Valid tools: " + valid}
try:
result = fn(**call["arguments"])
except TypeError as exc:
return {"is_error": True, "content": "Bad arguments: " + str(exc)}
except ValueError as exc:
return {"is_error": True, "content": "Invalid value: " + str(exc)}
except Exception as exc:
return {"is_error": True, "content": "Tool failed: " + str(exc)}
return {"is_error": False, "content": json.dumps(result)}
print(run_tool_call({"name": "get_weather", "arguments": {"city": "Oslo", "unit": "kelvin"}}))
print(run_tool_call({"name": "get_forecast", "arguments": {}}))The first call prints an error naming the bad unit. The second prints the unknown tool and the list of valid ones.
Marking the error
Some providers have an explicit error flag on the tool result, such as is_error. Others have no flag, so you put the error in the content text. In both cases, make the text start with a clear word like "Error" or "Bad arguments" so the model does not mistake it for data.
Common mistakes
- Dropping the result. If a call fails and you send no tool message, many APIs reject the next request because a call has no matching result.
- Retrying forever. A model can repeat the same bad call. Keep a step limit, covered in a later chapter, and consider a message like "This failed twice; ask the user instead."
- Hiding retryable status. Say whether trying again can help. A timeout may succeed later. A missing record will not.
- Leaking internals. Return a summary, and log the full exception on your side.
Exercise
A model calls get_weather with city "Oslo" and unit "kelvin". Your function raises ValueError. What should your code send back, and why not simply crash?
Show answer
Send a tool result with the matching call id, marked as an error, with a message such as "Invalid value: unit must be 'celsius' or 'fahrenheit', got 'kelvin'". The model can read this and retry with a valid unit. Crashing ends the loop, shows the user a failure, and leaves the call without a result.
Exercise
Why should an error message avoid including the full stack trace?
Show answer
Stack traces can expose file paths, library versions, queries, or secrets. The model may repeat them to the user. Log the trace privately and return a short summary.