Why Tool Calls Fail: Six Failure Classes and the Executor That Survives Them
Six distinct failures sit between a model's tool call and its side effect. A Python executor that classifies each one, retries only what is safe, derives idempotency keys from intent, and survives a payment whose response never arrives.

A model asks to charge a customer 49.90. The executor sends the request, waits five seconds, hears nothing and reports a timeout. The model, being helpful, tries again. The customer is charged twice, and every component did what it was designed to do. Most writing about LLM tool calling errors concentrates on the model producing bad JSON, which is the cheapest failure on the list: it is detected before anything happens and it costs one round-trip. The expensive failures happen after the arguments were perfect.
The agent loop from the first article in this series turned every tool failure into an observation and moved on. That is the right contract for the loop, and too coarse for the layer underneath it. "The tool failed" covers at least six different situations, and the correct response to one of them is the worst possible response to another. This article builds that layer: a tool executor of about 250 lines of Python whose main job is to decide which of the six it is looking at.
Six classes of LLM tool calling errors
Follow a call from the model's output to the side effect and note each place it can stop.
Figure 1. The executor's path and the six classes that leave it. Only the last one leaves the state of the world unknown.
- Malformed. The call cannot be read at all: the arguments are not valid JSON, are not an object, or name a tool that does not exist. Nothing ran.
- Invalid. The call is readable but breaks the tool's schema: a string where an integer belongs, a missing required field, an extra one. Nothing ran.
- Unauthorised. The call is well-formed, and this caller may not make it. Nothing ran, and nothing should.
- Transient. The tool was reached, refused the work, and the refusal says nothing about the request itself: a rejected connection, a 429, a 503 returned before any processing. Nothing was applied, and the same call may succeed in a moment.
- Permanent. The tool answered, and the answer is no: the order does not exist, the card was declined, a business rule forbids it. Nothing was applied, and the same call will fail again.
- Ambiguous. No answer arrived. The request was sent and then the connection dropped, or the timeout expired. The side effect may have happened or not, and the caller has no way to tell from where it stands.
Five of the six have a known outcome. Classes 1 to 5 all end with "nothing was applied", and differ only in who can fix the problem: the model (1, 2), nobody in this conversation (3, 5), or time (4). Class 6 is different in kind. It is the only one where the executor does not know what state the world is in, and it is the one that a naive retry policy handles worst.
The classes are a small enum, and tools state which one applies by raising a typed error:
class Failure(str, Enum): MALFORMED = "malformed" # the call cannot be read: bad JSON, not an object, unknown tool INVALID = "invalid" # readable, but the arguments break the tool's schema UNAUTHORISED = "unauthorised" # well-formed, but this caller may not make it TRANSIENT = "transient" # failed, certainly NOT applied, and the same call may work later PERMANENT = "permanent" # failed, and will fail again with the same arguments AMBIGUOUS = "ambiguous" # no answer arrived: the effect may or may not have happened class ToolError(Exception): """Tools raise a subclass to state what kind of failure this is. Unclassified exceptions are guessed.""" failure = Failure.PERMANENT def __init__(self, message: str, retry_after_s: float | None = None): super().__init__(message) self.retry_after_s = retry_after_s class Transient(ToolError): failure = Failure.TRANSIENT # a promise: nothing was applied (refused connection, 429, 503 before work) class Unauthorised(ToolError): failure = Failure.UNAUTHORISED # the downstream system refused these credentials class Ambiguous(ToolError): failure = Failure.AMBIGUOUS # e.g. the connection dropped after the request was written
Transient is a promise made by the tool's author, not a description of an HTTP status. Raising it asserts that the operation was certainly not applied. A connection refused before any bytes were written qualifies. A connection reset while waiting for the response does not, and belongs to Ambiguous, even though many HTTP clients report both as the same exception type. The mapping from a client library's errors to these classes is the one piece of this design that has to be written per integration, by someone who has read how that library reports a failure during send as opposed to during receive.
What strict modes fix, and what they leave
Providers have attacked classes 1 and 2 directly. Anthropic's strict tool use constrains token sampling so that a tool's input matches its JSON Schema and its name is always one of the tools offered; OpenAI's function calling has a strict flag for the same purpose. These are real guarantees.
They do not remove the need to parse and validate, for three reasons that are visible in the SDKs themselves. In the OpenAI SDK (3.49.0) the arguments field of a function call is typed as str in both the Chat Completions and Responses APIs: the SDK hands over a JSON-encoded string and does not check it. In the Anthropic SDK (2.8.0) input is already a parsed object, but the documentation on stop reasons describes a response cut off by max_tokens whose last block is an incomplete tool call, and the remedy it gives is to repeat the request with a higher limit. And strict mode is opt-in per tool and restricted to a subset of JSON Schema, so a schema that uses anything outside that subset is back to best effort.
More to the point, constrained decoding guarantees shape. It cannot know that the caller lacks permission, that the payment service is restarting, or that a response was lost. Classes 3 to 6 are untouched by anything the model provider does.
The gate: authorise, parse, validate
Everything before dispatch is a gate that either lets a call through or rejects it with a class. Parsing and repair are two small functions:
def parse(call: RawCall) -> dict: """MALFORMED: the arguments are not one JSON object. Nothing downstream can be trusted to run.""" arguments = call.arguments if isinstance(arguments, str): try: arguments = json.loads(arguments) if arguments.strip() else {} except json.JSONDecodeError as exc: raise Rejected(Failure.MALFORMED, f"Arguments are not valid JSON ({exc.msg} at character {exc.pos}). " "Send the complete call again as one JSON object.") from None if not isinstance(arguments, dict): raise Rejected(Failure.MALFORMED, f"Arguments must be a JSON object, got {type(arguments).__name__}.") return arguments def coerce(arguments: dict, schema: dict) -> dict: """Lossless, schema-directed repair of top-level scalars. Everything else is left for validation.""" fixed = dict(arguments) for key, spec in schema.get("properties", {}).items(): value, want = fixed.get(key), spec.get("type") if not isinstance(value, str): continue if want == "integer" and re.fullmatch(r"-?(0|[1-9]\d*)", value): fixed[key] = int(value) elif want == "number" and re.fullmatch(r"-?(0|[1-9]\d*)(\.\d+)?", value): fixed[key] = float(value) elif want == "boolean" and value in ("true", "false"): fixed[key] = value == "true" return fixed
The parse error names the position of the fault because that is the detail a model can act on; a call truncated at character 9 is usually a call that ran out of output tokens, and saying so beats "invalid input".
coerce is deliberately narrow. It converts a string to the scalar the schema asks for only when the conversion is lossless and unambiguous: "1042" becomes 1042, while "1042.0", "01042" and "ten" are left alone and fail validation. The regular expressions do the work that int() would do too generously; Python's int(" 1_000 ") succeeds, and no one intended the model to be able to write that.
The gate itself runs in a fixed order:
def execute(self, call: RawCall) -> Observation: tool = self.tools.get(call.name) try: if tool is None: raise Rejected(Failure.MALFORMED, f"Unknown tool '{call.name}'. Available: {self._offered()}.") if tool.scope is not None and tool.scope not in self.scopes: raise Rejected(Failure.UNAUTHORISED, f"'{tool.name}' is not permitted for the current user.") arguments = parse(call) if tool.effect == "read": arguments = coerce(arguments, tool.schema) # writes are never repaired, only validated validate(arguments, tool.schema) except Rejected as exc: return self._error(call, exc.failure, str(exc)) key = intent_key(self.run_id, tool.name, arguments) if tool.effect == "write" else None return self._run(tool, call, arguments, key)
Two decisions here are easy to make differently and worse.
Authorisation runs before parsing. The taxonomy lists "unauthorised" third because such a call is sound in every other respect, but the check comes first in the code. A caller without the scope should learn that the tool is unavailable, and should not be able to probe its schema through validation messages. For the same reason the unknown-tool message lists only the tools this caller may use. The test for this sends a truncated JSON body to a tool the caller may not use and asserts that the answer is unauthorised, with no field name in it. The scope set comes from the session of the calling user and never from anything the model wrote; richer rules that depend on the arguments themselves need a policy layer, which a later article in this series builds.
Writes are validated but never repaired. Coercion is applied only to tools whose effect is read. For a read, turning "1042" into 1042 saves a round-trip and risks nothing. For a write, the arguments are a statement of intent that may be shown to a person for approval, written to an audit record, and hashed into an idempotency key. If the executor edits them, what was executed is no longer what the model said. A strict rejection costs one extra model call and keeps that equality intact.
Retries by class, not by exception
Once a call passes the gate and an attempt fails, the whole retry policy is one function of three inputs: the failure class, the tool's effect, and whether the tool accepts an idempotency key.
def next_action(tool: Tool, failure: Failure, attempt: int) -> str: """The whole retry policy. Returns "retry", "give_up" or "reconcile".""" if failure in (Failure.MALFORMED, Failure.INVALID, Failure.UNAUTHORISED, Failure.PERMANENT): return "give_up" # the same call cannot succeed; only the model or a person can change it unknown_write = failure is Failure.AMBIGUOUS and tool.effect == "write" if unknown_write and not tool.accepts_key: return "reconcile" # a retry could apply the effect twice; stop and find out if attempt < tool.max_attempts: return "retry" # safe: a read, a promise of "not applied", or the same key again return "reconcile" if unknown_write else "give_up"
Figure 2. The retry decision. The only path to a retry for an ambiguous write runs through an idempotency key.
The function is pure, so the policy is tested as a table of twelve rows rather than through twelve scenarios. Three rows carry the design. A transient failure on a write is retried even without a key, because Transient promised that nothing was applied. An ambiguous failure on a read is retried, because repeating a read is harmless. An ambiguous failure on a write without a key returns reconcile on the first attempt: the executor stops, records the call as unresolved, and does not try again, because a second attempt is a coin toss between fixing the problem and doubling it.
The loop around that decision handles time:
def _run(self, tool: Tool, call: RawCall, arguments: dict, key: str | None) -> Observation: kwargs = {**arguments, "idempotency_key": key} if tool.accepts_key else arguments started, attempt = self.clock(), 0 while True: attempt += 1 budget = self.deadline_s - (self.clock() - started) failure, payload, retry_after = self._once(tool, kwargs, min(tool.timeout_s, budget)) if failure is None: return Observation(call.id, call.name, render(payload), False, None, attempt, key) action = next_action(tool, failure, attempt) if action == "retry": ceiling = min(self.backoff_cap_s, self.backoff_base_s * 2 ** (attempt - 1)) delay = retry_after if retry_after is not None else self.rng.uniform(0, ceiling) # full jitter if self.clock() - started + delay < self.deadline_s: self.sleep(delay) continue action = "reconcile" if failure is Failure.AMBIGUOUS and tool.effect == "write" else "give_up" if action == "reconcile": self.unresolved.append({"run_id": self.run_id, "tool": tool.name, "arguments": arguments, "idempotency_key": key, "attempts": attempt}) advice = ("The outcome is unknown: the action may or may not have been applied. " + ("Repeating this exact call is safe; it reuses the same idempotency key." if tool.accepts_key else "Do NOT repeat it. Tell the user it needs to be checked before trying again.")) return self._error(call, failure, payload, attempt, key, advice) return self._error(call, failure, payload, attempt, key) def _once(self, tool: Tool, kwargs: dict, timeout_s: float) -> tuple[Failure | None, Any, float | None]: """One attempt. Returns (failure class or None, result or message, server-suggested wait).""" future = _pool.submit(tool.fn, **kwargs) try: return None, future.result(timeout=max(timeout_s, 0)), None except FutureTimeout: if future.cancel(): # still queued behind busy workers: it never started, so nothing was applied return Failure.TRANSIENT, f"Not started within {timeout_s:g}s: no free worker.", None return Failure.AMBIGUOUS, f"No response within {timeout_s:g}s.", None # running, and keeps running except ToolError as exc: return exc.failure, str(exc), exc.retry_after_s except Exception as exc: # unclassified: assume the worst the tool's effect allows guess = Failure.AMBIGUOUS if tool.effect == "write" else Failure.PERMANENT return guess, f"{type(exc).__name__}: {exc}", None
There are two clocks. timeout_s bounds one attempt; deadline_s bounds everything the call may consume, including waits between attempts. Without the second, three attempts of five seconds plus backoff can hold an agent step for far longer than anyone budgeted, and each layer above tends to add its own timeout that fires first and leaves the work running. A retry is scheduled only if the wait fits inside the deadline. In the tests, a 429 that suggests waiting 60 seconds against a 20-second deadline is returned to the model after one attempt and zero sleeps.
_once also narrows class 6 where it can. Future.cancel() returns true only for a call that never left the queue, which happens when every worker is busy. Nothing was sent in that case, so the timeout is reported as transient; a timeout on a call that had started stays ambiguous.
The wait itself is capped exponential backoff with full jitter: a uniform draw between zero and the current ceiling. The AWS Builders' Library article on this subject explains why retries need backoff and randomness, and makes a second point that matters more for agents than for ordinary services: retries are selfish, and they multiply across layers. Its example is a call stack five deep in which each layer retries three times, which raises load on the bottom layer 243-fold.
An agent has such a stack by construction. The executor retries, and then the model, shown an error, retries too; Anthropic's documentation notes that a model given an invalid-call error will typically try again two or three times with corrections. Three attempts in the executor under three in the model is nine calls against a service that is already struggling. This is why the error observation carries advice as well as a class:
{"error": {"class": "transient", "message": "503 Service Unavailable", "advice": "Already retried automatically. Do not call again now; continue without it or tell the user."}}
The class is for code and the advice is for the model. Retrying happens at one layer, the one that knows the failure class, and the other layer is told so in plain words. It is advice and not enforcement, which the next section takes seriously.
Unclassified exceptions need a default, and the default depends on the tool. A KeyError from a read is treated as permanent: retrying a bug is pointless. The same unexpected exception from a write is treated as ambiguous, because code that fails while decoding a provider's response has failed after the provider acted.
The ambiguous timeout and the duplicated charge
To test class 6 honestly the fixture has to do what real systems do: apply the effect and then fail to say so. The fake payment provider records the charge, and on request never returns:
class Payments: """Applies a charge, then (on request) never answers: the side effect happened, the caller cannot know.""" def __init__(self): self.charges: list[dict] = [] self.by_key: dict[str, tuple[dict, dict]] = {} self.lose_responses = 0 self.release = threading.Event() self._lock = threading.Lock() def charge(self, customer: str, amount_minor: int, idempotency_key: str | None = None) -> dict: params = {"customer": customer, "amount_minor": amount_minor} with self._lock: if idempotency_key is not None and idempotency_key in self.by_key: saved_params, saved_response = self.by_key[idempotency_key] if saved_params != params: raise ToolError("Idempotency key reused with different parameters.") return saved_response # the first result, not a second charge response = {"charge_id": f"ch_{len(self.charges) + 1}", **params} self.charges.append(response) # the money moves here if idempotency_key is not None: self.by_key[idempotency_key] = (params, response) lose, self.lose_responses = self.lose_responses > 0, max(self.lose_responses - 1, 0) if lose: self.release.wait(5) # the response is lost on the way back return response
Its idempotency behaviour is modelled on what Stripe documents for its v1 API: the result of the first request made with a key is saved once execution begins and returned for later requests with that key, and a request that reuses a key with different parameters is an error.
The first test runs the scenario from the opening paragraph against a tool with no key. The second runs it with one.
def test_without_a_key_the_executor_refuses_to_retry_but_cannot_stop_the_model(payments): payments.lose_responses = 1 executor, _ = make([charge_tool(payments, accepts_key=False)], scopes=frozenset({"payments:charge"})) first = executor.execute(RawCall("c1", "charge_card", CHARGE)) assert (first.failure, first.attempts, len(payments.charges)) == (Failure.AMBIGUOUS, 1, 1) assert "Do NOT repeat it" in error_of(first)["advice"] assert executor.unresolved[0]["arguments"] == CHARGE # handed to reconciliation, not dropped # The advice is only advice. A model that tries again anyway charges the customer twice. second = executor.execute(RawCall("c2", "charge_card", CHARGE)) assert not second.is_error and len(payments.charges) == 2 def test_with_an_intent_key_a_lost_response_and_a_reissued_call_still_charge_once(payments): payments.lose_responses = 1 executor, clock = make([charge_tool(payments, accepts_key=True)], scopes=frozenset({"payments:charge"})) first = executor.execute(RawCall("c1", "charge_card", CHARGE)) assert (first.is_error, first.attempts, len(clock.sleeps)) == (False, 2, 1) # timed out, retried, answered assert json.loads(first.content)["charge_id"] == "ch_1" and len(payments.charges) == 1 # The model repeats the call under a new call id, and with the keys in a different order. again = executor.execute(RawCall("c2", "charge_card", '{"amount_minor": 4990, "customer": "cus_9"}')) assert again.idempotency_key == first.idempotency_key assert json.loads(again.content)["charge_id"] == "ch_1" and len(payments.charges) == 1
The first test documents a limit, not a success. The executor behaves correctly: one attempt, no retry, an unresolved record, and an observation that says in capitals not to repeat the call. Then the test plays a model that repeats the call anyway, and the fixture holds two charges. An executor can refuse to retry; it cannot prevent the next call, because from where it sits a repeated call and a new instruction look the same. Wording in an observation is not a control.
Figure 3. The same lost response twice. The key turns a repeated request into a lookup.
The second test passes because of where the key comes from:
def intent_key(run_id: str, tool: str, arguments: dict) -> str: """One key per intended effect: stable across executor retries AND across the model re-issuing the call.""" canonical = json.dumps(arguments, sort_keys=True, separators=(",", ":"), ensure_ascii=False) return hashlib.sha256(f"{run_id}\x1f{tool}\x1f{canonical}".encode()).hexdigest()[:32]
The usual advice, including Stripe's, is to generate a random key such as a UUID per operation. That works when the retrying code holds the key in a variable for the life of the retry loop. It fails in an agent, because the second attempt may not come from the retry loop. It may come from the model, under a new tool call id, with the JSON keys in a different order, after the executor has already returned. A key derived from the tool call id, which is the obvious choice, is different on that second call and protects nothing.
So the key is derived from the intent: the run, the tool and the canonicalised arguments. Any repetition of the same request within the same task maps to the same key, whether it comes from the executor's loop, from the model, or from a worker that restarted and replayed the step. The test asserts exactly that: a re-issued call with a new id and reordered keys returns ch_1 and the fixture still holds one charge. The key is a hash, which also respects Stripe's advice to keep personal data out of idempotency keys.
The cost is real and should be chosen knowingly. Two deliberately identical writes in one run collapse into one. If a user asks an agent to send the same amount to the same account twice, the second call returns the first result. The remedy is to make whatever distinguishes the two operations an argument: an invoice number, a line reference, an explicit sequence field in the schema. A write whose arguments cannot distinguish two intended executions is under-specified with or without an agent in front of it; the general design of retry-safe APIs reaches the same conclusion from the server side.
What the model is told
The executor's output is an Observation with a failure class and attempt count for the caller's code, and a content string for the transcript. Provider formats differ here. Anthropic's tool_result block carries an is_error flag. The function_call_output item in OpenAI's Responses API has no such field in the SDK's types, so the failure must be legible in the output text itself. Encoding every error as a small JSON object with class, message and advice works for both.
Success output needs care as well. A result that exceeds the observation budget is truncated, and cutting a JSON array at an arbitrary character produces something the model has to guess at. The executor's render function cuts lists between items and wraps them with counts and an instruction; in the test, 500 rows against a 1,000-character limit come back as valid JSON with 15 items, "total": 500 and a note to narrow the query.
Production concerns
Reconciliation is a component, not a log line. Every reconcile outcome appends to unresolved with the run, tool, arguments and key. In a deployed system that list is a durable queue with a consumer that asks the downstream system what happened, by key where keys exist and by searching for a matching record where they do not, and then closes the item or raises it to a person. The same queue discipline that applies to any background work applies here: at-least-once delivery, idempotent handlers, a dead-letter path.
The abandoned attempt is still running. Python cannot kill a thread, so after a timeout the first request may still be in flight when the retry goes out. With a provider that locks on the key, the retry may be told that a request with this key is in progress; Stripe's documentation says such conflicting requests are not saved and may be retried. That response is class 4, and the integration's error mapping has to say so. A hung tool also holds a worker in the pool indefinitely, so network tools need their own client-side timeout set below the executor's.
Keys expire. Stripe states that v1 keys may be removed once they are at least 24 hours old, after which a reused key is treated as a new request. An intent key therefore protects a run for as long as the provider remembers it. A run that is paused for approval and resumed two days later must reconcile before it retries.
Timeouts are chosen, not guessed. The Builders' Library method is to decide what rate of false timeouts is acceptable and set the timeout at the matching latency percentile of the downstream call. A timeout below the service's normal tail manufactures class 6 failures out of requests that were about to succeed.
Measure the classes. The useful counters are per tool and per class. A rise in invalid is a schema or description problem. A rise in transient is a dependency problem, and belongs with the circuit breakers and bulkheads used for any remote dependency. Any non-zero count of ambiguous on a write without a key is a design defect waiting for its incident.
Testing each class
The suite has 32 tests in one file and runs in about a second and a half. Each class has at least one test asserting the class, the attempt count and the number of sleeps, which together pin down the behaviour. Backoff is tested with a virtual clock whose sleep advances time instantly, and the random generator is seeded.
Timeouts are the exception to virtual time. They are enforced by real threads with a 50 ms limit, and the payment fixture blocks on an event that the test releases at teardown, so the "lost response" is a response that really has not arrived when the executor gives up. The provider-shape test constructs real SDK objects: a Chat Completions tool call from the OpenAI SDK whose arguments string is truncated JSON, which the SDK accepts and the executor classifies as malformed, plus a Responses function call and an Anthropic ToolUseBlock.
Verification. All 32 tests pass on Python 3.13.18 with anthropic 2.8.0, openai 3.49.0, jsonschema 4.26.0 and pytest 9.2.0 (November 2026). No live model and no real payment API were called: the model is scripted, and the payment provider is a local fake that follows Stripe's documented v1 idempotency behaviour but is not Stripe. How often any particular model repeats a call after being advised not to was not measured, and neither was the behaviour of either provider's strict mode.
Common mistakes
One except Exception and one retry count for everything. It retries declined cards, gives up on blips after the same number of tries, and re-sends writes after timeouts.
Deriving the idempotency key from the tool call id or from a fresh UUID per attempt. Both produce a new key exactly when the old one was needed.
Treating a timeout as a failure. A timeout is the absence of an answer. Reporting it to the model as "failed" invites the retry that causes the duplicate.
Relying on the prompt or the observation to stop a repeat. Advice reduces how often the model re-issues a call. Only a key changes what happens when it does.
Engineering verdict
Use an executor of this shape whenever an agent can change state in another system. The classification costs little, and the retry table makes one question unavoidable for every write tool: what happens when no answer comes back? If the downstream API accepts idempotency keys, pass an intent-derived key and the question has a good answer; the same applies to any payment integration, with or without a model in front of it, as the production notes on integrating Stripe describe. If it does not accept keys, the choices are to add deduplication on a natural key in a wrapper you own, to require a person's approval for that tool, or to accept that the tool must not be retried and staff the reconciliation queue.
For an agent that only reads, most of this is unnecessary: parsing, validation, a timeout and a bounded retry with jitter are enough, and the write-specific half can be left out.
Before production, replace the thread pool with whatever gives real cancellation in your runtime, persist unresolved, write the error mapping for each client library by reading how it reports failures during send and during receive, and set timeouts from measured latency.
References
Related Articles
AI & Machine Learning14 min read
The Agent Loop Is Forty Lines. The Guards Around It Are the Engineering
A framework-free agent loop in Python, written as a state machine with five explicit exits: validated tool calls, errors returned as observations, step, token and time budgets, and stall detection, all tested with a scripted model and the real SDK.
Under the Hood · No. 01Backend Design10 min read
Idempotency Keys Are a Contract, Not a Header: Designing Retry-Safe Operations
A retry is only safe if the server has promised what happens the second time. This issue designs that promise end to end, from the key table to queue consumers and external calls.
Backend Design17 min read
Queue-Based Architecture for Reliable Processing
Build reliable message queue systems with Redis, RabbitMQ, and AWS SQS. Covers dead letter queues, idempotency, and real-world processing patterns.