Sub topic 13
Returning errors the model can act on
This chapter assumes you know the tool-calling loop, can read JSON Schema, and can read short Python examples. It covers what a tool should send back when a call fails, and why the wording of that message decides whether the model recovers.
Why error messages are part of the design
When a tool call fails, the model reads your error text as the next input. It has no stack trace, no logs, and no access to your code. The message is the only evidence it has about what went wrong. A model that gets a vague error will usually do one of three things: retry with the same arguments, guess at a change, or give up and tell the user something went wrong.
A message that names the problem and the next step turns a failed call into a short detour. Treat each error as a small instruction written for the model.
Two kinds of failure
Separate failures into two groups, because they need different handling.
- Tool errors the model can fix. The arguments were malformed, an ID did not exist, a date was in the wrong format, or a value was out of range. The model can change its next call, so the message should say how.
- Failures the model cannot fix. The database is down, a downstream API timed out, or the user lacks permission. Retrying with new arguments will not help. The message should say so, so the model stops guessing and reports the problem or offers an alternative.
Protocol-level errors, such as invalid JSON in the request, are different again. Many APIs reject those before your code runs. This chapter is about errors your tool code produces.
What a good error message contains
A recoverable message has four parts. Not every error needs all four, but check each one.
- What was wrong. Quote the bad value so the model can see exactly what it sent.
- What is expected. Give the format, range, or allowed values.
- What to do next. Name a different tool, a different argument, or the user as the source of missing information.
- Whether retrying can help. Say if the failure is temporary or permanent.
Compare these two responses to the same bad call.
| Response | Problem |
|---|---|
| `{"is_error": true, "message": "Invalid input"}` | Says nothing about which field, what format, or what to try. |
| `{"is_error": true, "message": "Invalid order_id '1001'. IDs look like 'ord_1001'. If you do not have an ID, call search_orders first."}` | Names the value, the format, and the next tool. |
The second message lets the model fix the call without asking the user anything.
Example: validating on the server
The get_order function below checks its argument on the server and returns messages in the shape described above. It does not trust the model to send a well-formed ID.
ORDERS = {
"ord_1001": {"id": "ord_1001", "status": "shipped", "total": 42.5},
}
def get_order(order_id: str) -> dict:
if not isinstance(order_id, str) or not order_id.startswith("ord_"):
return {
"is_error": True,
"message": (
f"Invalid order_id {order_id!r}. IDs look like 'ord_1001'. "
"If you do not have an ID, call search_orders first."
),
}
order = ORDERS.get(order_id)
if order is None:
return {
"is_error": True,
"message": f"No order found with id {order_id!r}. Check the ID with the user or use search_orders.",
}
return {"is_error": False, "order": order}Notice that the two failure paths give different advice. A malformed ID points to search_orders because the model probably lacks a real ID. A well-formed ID that does not exist suggests checking with the user, because the model may have copied a wrong ID from the conversation.
Signal the error in the protocol, not only in the text
Most tool-calling APIs let you mark a tool result as an error. In Anthropic-style APIs, a tool_result block has an is_error field. Other APIs have no such field, so you put the error in the result content. The is_error key in the Python example above is a convention inside the returned data. When your API supports a native error flag, set it as well, so the model and any logging layer can tell failures from successes without parsing prose.
Whatever the mechanism, keep the shape consistent across all your tools. If one tool returns {"error": ...} and another returns {"is_error": true, "message": ...}, the model has to learn two conventions.
Distinguish "no results" from "error"
An empty search is not a failure. If search_orders finds nothing, return a normal result with an empty list, and say what the empty list means.
def search_orders_result(orders: list, customer_id: str) -> dict:
if not orders:
return {
"is_error": False,
"orders": [],
"note": f"No orders matched for customer {customer_id}. Try removing the status or date filter.",
}
return {"is_error": False, "orders": orders}If you return an error for an empty result, the model may conclude that its call was wrong and keep changing arguments that were fine. If you return a bare empty list with no note, the model may not know whether the filters were too narrow. A short note resolves both problems.
Common mistakes
- Leaking internals. Do not return raw exceptions, stack traces, SQL, file paths, or credentials. They waste tokens, can expose secrets, and give the model nothing to act on. Log the details on your side and return a short, safe summary.
- Blaming the wrong party. If the failure is on your side, say so. A message like "Invalid input" for a server timeout makes the model change arguments that were correct.
- Silent coercion. If you quietly round a limit of 500 down to 50, the model believes it received 500 results. Either reject the value with a message, or clamp it and say you did so in the result.
- Unbounded messages. An error that echoes a large input back can cost thousands of tokens. Truncate echoed values.
- Advice that cannot be followed. Do not tell the model to call a tool that is not in its tool list for this request.
- Endless retry loops. If a failure is permanent, say "do not retry". Also cap retries in your own loop, because a model can repeat the same bad call.
Temporary failures
For failures the model cannot fix, give it a clear choice. The message should tell it whether to retry and what to say to the user.
def temporary_failure(service: str) -> dict:
return {
"is_error": True,
"message": (
f"The {service} service is temporarily unavailable. "
"Retrying the same call once may work. If it fails again, "
"tell the user the lookup is unavailable right now. Do not guess the answer."
),
}The last sentence matters. Without it, a model that cannot get data may fill the gap with a plausible invention.
Make error handling testable
Errors are part of tool behavior, so test them like any other behavior. Add cases to your evaluation set that start from a bad call and check what the model does after reading your message. For example, send a malformed ID and check that the next call is to search_orders, not a repeat of the same call. If the model repeats itself, the message is unclear. Rewrite it and run the same cases again.
Summary of rules
- Say what was wrong, what is expected, and what to do next.
- Quote the offending value, truncated if it is long.
- Return an empty result as a normal result with a note.
- Say whether a retry can help.
- Use one error shape across all tools, and set the protocol's error flag when it exists.
- Keep internals out of the message.
Exercise
A tool create_event(date) receives date = "next Friday" and currently returns {"is_error": true, "message": "Bad date"}. Rewrite the message so the model can recover without asking the user, and explain which of the four parts of a good error message each sentence covers.
Show answer
For example: "Invalid date 'next Friday'. Use YYYY-MM-DD, for example '2026-12-04'. Convert relative dates using today's date, then call create_event again." The first sentence says what was wrong and quotes the value. The second says what is expected. The third says what to do next. Retrying with a corrected date is expected to work, which the third sentence implies. A fuller version could add "Retrying with a valid date will succeed."
Exercise
search_orders returns {"is_error": true, "message": "Not found"} when a customer has no orders. Why is this a problem, and how would you change it?
Show answer
An empty result is not a failure, so the model may think its call was wrong and keep changing arguments. Return is_error: false with an empty orders list and a note such as "No orders matched for customer cus_4821. Try removing the status or date filter." Reserve errors for calls that actually failed, such as an unknown customer ID.