Sub topic 9
Reporting tool errors so the model can recover
This chapter assumes you can read Python and JSON. You should also know the tool-calling message flow: the model proposes a call with an id, your code runs it, and you send back a tool message with the same id. The dispatcher from the earlier chapter is the starting point here.
Why errors belong in the conversation
A tool call can fail in many ways. The model may name a tool that does not exist. It may send arguments that do not match the schema. The tool itself may time out or raise an exception. The remote service may return "not found".
If your program crashes on any of these, the user sees a stack trace. If your program hides the failure, the model may invent an answer. A third option works better: turn the failure into a tool result that says what went wrong. The model reads it on the next turn and decides what to do. It can fix an argument, try another tool, ask the user a question, or explain that it cannot finish.
Every proposed call needs exactly one result message with the matching tool_call_id, even when the call failed. Most providers reject a conversation where a tool call has no matching result.
Kinds of failure
Different failures need different handling. The table groups them by who can fix the problem.
| Failure | Example | Can the model fix it? | What to return |
|---|---|---|---|
| Unknown tool | Model calls `get_wether` | Yes, by choosing a listed name | Error naming the valid tools |
| Bad arguments | Missing `city`, or `unit` is `"kelvin"` | Yes, by resending | Error naming the field and the allowed values |
| Arguments not valid JSON | Truncated or malformed argument text | Yes, by resending | Error saying the arguments could not be parsed |
| Expected domain failure | City not found, record missing | Often, by trying another input | Plain description of the problem |
| Transient failure | Timeout, rate limit, 503 | Sometimes, by retrying | Short message saying it may work later |
| Internal failure | Bug, database down, bad credentials | No | Generic message, details only in your logs |
The dispatcher from the earlier chapter
This is the dispatcher from the previous chapters. It already converts three kinds of failure into error results.
import json
def get_weather(city, unit="celsius"):
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:
return {"is_error": True, "content": "Unknown tool: " + str(call["name"])}
try:
result = fn(**call["arguments"])
except TypeError as exc:
return {"is_error": True, "content": "Bad arguments: " + str(exc)}
except Exception as exc:
return {"is_error": True, "content": "Tool failed: " + str(exc)}
return {"is_error": False, "content": json.dumps(result)}It works, but it has weaknesses.
- The unknown-tool message does not list the valid names, so the model must guess again.
- A
TypeErrorraised inside the tool body is reported as "Bad arguments", which is wrong and misleading. str(exc)from an arbitrary exception can leak file paths, SQL, hostnames, or secrets into the model's context.- Nothing checks argument values against the schema, so
unit="kelvin"runs.
Writing messages the model can act on
A good error message answers three questions: what failed, why, and what to do next. Compare these two results for the same bad call.
- Poor:
Error - Better:
Invalid argument "unit": "kelvin" is not allowed. Allowed values: celsius, fahrenheit. Call get_weather again with a valid unit.
The second message gives the model what it needs to correct itself in one step. Keep these habits:
- Name the field or tool that caused the problem.
- State the allowed values or the expected format when you know them.
- Say whether retrying is sensible.
- Keep it short. Long traces use context tokens and distract the model.
- Write in plain text or small JSON, the same style your successful results use.
A dispatcher that reports errors well
The version below separates the failure types. It parses string arguments, checks the required fields and enum values from a simple schema, keeps tool exceptions apart from argument problems, and logs the real exception server-side.
import json
import logging
logger = logging.getLogger("tools")
def get_weather(city, unit="celsius"):
if city.lower() == "atlantis":
raise LookupError("city not found")
return {"city": city, "temperature": 7, "unit": unit}
TOOLS = {
"get_weather": {
"fn": get_weather,
"required": ["city"],
"enums": {"unit": ["celsius", "fahrenheit"]},
"allowed": ["city", "unit"],
}
}
def error(message):
return {"is_error": True, "content": json.dumps({"error": message})}
def run_tool_call(call):
spec = TOOLS.get(call.get("name"))
if spec is None:
valid = ", ".join(sorted(TOOLS))
return error("Unknown tool '%s'. Available tools: %s." % (call.get("name"), valid))
args = call.get("arguments", {})
if isinstance(args, str):
try:
args = json.loads(args)
except json.JSONDecodeError:
return error("Arguments are not valid JSON. Send a JSON object.")
if not isinstance(args, dict):
return error("Arguments must be a JSON object.")
missing = [name for name in spec["required"] if name not in args]
if missing:
return error("Missing required argument(s): " + ", ".join(missing) + ".")
extra = [name for name in args if name not in spec["allowed"]]
if extra:
return error("Unexpected argument(s): " + ", ".join(extra) + ".")
for name, options in spec["enums"].items():
if name in args and args[name] not in options:
return error("Invalid '%s': %r. Allowed values: %s." % (name, args[name], ", ".join(options)))
try:
result = spec["fn"](**args)
except LookupError as exc:
return error("Not found: " + str(exc) + ". Check the spelling or try a different input.")
except TimeoutError:
return error("The service timed out. Retrying may work.")
except Exception:
logger.exception("Tool %s crashed", call["name"])
return error("The tool failed with an internal error. Do not retry with the same input.")
return {"is_error": False, "content": json.dumps(result)}
if __name__ == "__main__":
print(run_tool_call({"name": "get_wether", "arguments": {}}))
print(run_tool_call({"name": "get_weather", "arguments": {"city": "Oslo", "unit": "kelvin"}}))
print(run_tool_call({"name": "get_weather", "arguments": {"city": "Atlantis"}}))
print(run_tool_call({"name": "get_weather", "arguments": '{"city": "Oslo"}'}))The hand-written checks keep the example self-contained. In production, validate with a JSON Schema library against the same schema you sent to the model, so the two cannot drift apart.
What the recovery looks like
Here is a conversation where the model fixes its own mistake. The first result is an error, and the second call succeeds.
[
{"role": "user", "content": "Weather in Oslo in kelvin?"},
{"role": "assistant", "tool_calls": [
{"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo", "unit": "kelvin"}}
]},
{"role": "tool", "tool_call_id": "call_1", "content": "{\"error\": \"Invalid 'unit': 'kelvin'. Allowed values: celsius, fahrenheit.\"}"},
{"role": "assistant", "tool_calls": [
{"id": "call_2", "name": "get_weather", "arguments": {"city": "Oslo", "unit": "celsius"}}
]},
{"role": "tool", "tool_call_id": "call_2", "content": "{\"temperature\": 7, \"unit\": \"celsius\"}"},
{"role": "assistant", "content": "Kelvin is not supported. It is 7 degrees Celsius in Oslo."}
]The `is_error` flag
Some providers have a field on the result message, such as an is_error flag, that marks a result as a failure. Where it exists, set it. It tells the model the content is a failure and not data. Where it does not exist, make the content itself clear, for example by starting with {"error": ...}. The is_error key in the dispatcher's return value is your own bookkeeping. Map it to whatever your provider supports, and also use it for logging and metrics.
Retries: yours versus the model's
Decide who retries.
- Transient failures such as timeouts and 503 responses are best retried by your code, with a small limit (two or three attempts) and a short backoff. The model never needs to see them if a retry succeeds.
- Validation failures and not-found results need new input, so they go to the model.
- Internal failures should not be retried blindly. Tell the model so.
Only retry tools that are safe to repeat. Retrying send_email after a timeout may send two emails, because the first attempt might have succeeded. For tools with side effects, use an idempotency key or report the uncertainty to the model.
Preventing endless error loops
A model can repeat the same failing call. Your loop's max_steps limit is the final guard. You can add two cheaper ones.
- Count consecutive errors per tool. After a set number, stop the loop or return a message such as "This tool has failed 3 times. Do not call it again; tell the user."
- Detect an identical call (same name and arguments) that already failed, and return the earlier error without running it again.
Common mistakes
- Skipping the result message after a failure, which leaves a tool call unanswered and causes a provider error.
- Raising an exception out of the dispatcher so the whole request fails.
- Returning an empty string for "no results". The model cannot tell this from a failure. Return an explicit value such as
{"matches": []}. - Reporting every failure with the same text, so the model cannot choose a different action.
- Catching
TypeErroraround the whole tool call and calling it a bad-arguments error, which hides real bugs in the tool.
Exercise
A tool call to send_invoice times out. The first attempt may have reached the billing service. Should your dispatcher retry automatically and hide the timeout from the model? Explain what you would do instead.
Show answer
No, not blindly. send_invoice has a side effect, and the first attempt may have succeeded, so a retry could send a duplicate invoice. Either attach an idempotency key to the request so the billing service ignores a repeat, or return an error result saying the outcome is uncertain and that the invoice status should be checked before sending again. Automatic hidden retries are fine only for safe, repeatable calls such as reads.
Exercise
Your tool crashes with psycopg2.OperationalError: connection to server at "10.0.3.12" failed, password authentication failed for user "app". What do you log, and what do you return to the model?
Show answer
Log the full exception with the stack trace on your side. Return a short safe message such as {"error": "The tool failed with an internal error. Do not retry with the same input."}. The raw text exposes an internal IP address and a username and would enter the model's context and possibly the user's view.
Exercise
A model calls get_weather with {"city": "Oslo", "unit": "kelvin"}. Write an error message that lets it recover in one step.
Show answer
For example: Invalid 'unit': 'kelvin'. Allowed values: celsius, fahrenheit. Call get_weather again with one of these. It names the field, shows the rejected value, lists the allowed values, and says what to do next.