Fallbacks for failed models, tool timeouts and spent budgets
Handle invalid output, unavailable models, client disconnects, tool timeouts and budget exhaustion with a chosen fallback or escalation.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 12 minutes to read.
In short
Agent runs fail in predictable ways: the model returns invalid output, the model provider is down, the client disconnects, a tool times out, or the budget runs out. For each failure you choose a planned response in advance: retry, fail over to another model, stop, fall back to fixed RAG, or escalate to a person. The run must always end with a clear status, never a hang or a guess.
Explained simply
Agents depend on many moving parts: a model, a database, tools and a client waiting for the answer. Any of them can fail. Good design does not hope they will not. It decides in advance what happens for each kind of failure.
There are five common failures. The model returns output that does not match the schema. The model service is busy or down. The user closes the page before the answer is ready. A tool takes too long. Or the run uses up its budget of calls, tokens or time.
Each failure gets a planned response. Some are worth a quick retry. Some need a switch to a backup model. Some mean stopping straight away. And when the agent cannot finish, it can either fall back to plain fixed RAG, one search and one answer, or escalate to a person.
Whatever happens, the run must end with a clear status and a reason code. That makes failures visible in your logs and countable in evaluation, instead of hidden behind a vague answer.
Press Play on a diagram to walk through it one step at a time.
- Invalid model output
- Re-validate after one retry
- Then reject and escalate
- Model unavailable
- Retry 429 and 5xx with backoff
- Fail over to a backup model
- Client disconnected
- Cancel the run
- Log it, send nothing
- Tool timeout
- Per-tool timeout
- Continue without it or abstain
- Budget spent
- Fixed RAG fallback
- Or escalate with partial evidence
- One search, one answer call
- Cheap and predictable
- Still cites or abstains
- Good when evidence likely exists
- Hands over question and evidence
- Slower but safe
- Right for ambiguity or risk
- Needs a queue and an owner
- 1Request deadline
For example 20 s, set at the API
- 2Reserved fallback slice
For example 2 s kept back
- 3Agent loop
Uses what is left, checks before each step
- 4Model call timeout
Capped by time remaining
- 5Tool timeout
For example 3 s per search
In depth
Invalid output: retry once, then reject
Invalid output means the model's response fails your Pydantic validation: missing fields, an unknown route, a citation ID that is not in the evidence set. Treat it as a normal event, not an exception that crashes the run.
A single retry often fixes it. Send the validation error back in a short message, such as "route must be one of clarify, retrieve, lookup, abstain", and validate again. Count the retry against the budget. If the second attempt also fails, stop retrying: repeated invalid output usually means the prompt, schema or model is wrong, and more attempts just cost money. Reject the output and choose the fallback, usually escalation with the reason invalid_model_output. Log the raw invalid output with the request ID for debugging, keeping in mind it may contain sensitive text, so apply your logging redaction rules.
- Validate every model output with Pydantic
- One retry with the validation error, counted in the budget
- Second failure: reject and escalate
- Log reason invalid_model_output with the request ID
Unavailable models: retry, back off, fail over
Model APIs return temporary errors: 429 when you hit a rate limit and 5xx codes when the service has a problem, plus network timeouts. These can succeed on retry. Use exponential backoff with jitter, for example waits of about 1, 2 and 4 seconds with random variation, and stop when the next wait would pass the request deadline. If the provider sends a Retry-After header, respect it. Do not retry 400-type errors such as a bad request or invalid key; they will fail again.
If retries run out, fail over to a backup model, such as a second hosted model or a local one. Only use a backup that has passed the same evaluation suite, and record which model answered in the run record. If no backup is available, fall back to escalation with the reason model_unavailable.
- 1Call primary
Within remaining deadline
- 2429 or 5xx?
Back off with jitter, retry up to 3
- 34xx other?
Do not retry; reject
- 4Fail over
Evaluated backup model
- 5Escalate
Reason model_unavailable
Disconnects and tool timeouts
When the client disconnects, nobody will read the answer, so the right response is to cancel the run and stop spending. Detect it with request.is_disconnected() in the API layer, as in the service contract topic, and cancel the agent task. Log the run as cancelled with calls used so far; there is no one to send an error to.
Tool timeouts are different, because the client is still waiting. Give each tool its own timeout, smaller than the time left in the request, for example 3 seconds for search. On timeout, return a structured result such as ok false with reason tool_timeout to the agent loop instead of raising. The loop can then try another route, continue with the evidence it has, or abstain. Make sure the slow call is actually cancelled, not left running in the background.
- Disconnect: cancel the run, log it, send nothing
- Per-tool timeout smaller than the remaining deadline
- Timeout returns a structured result to the loop
- Cancel the slow call; do not leave it running
Budget exhaustion: fixed RAG or escalation
The budget is the run's limit on model calls, tool calls, tokens and time. When any part is spent, the loop must stop. You then have two planned endings. Fixed RAG fallback runs one search in the caller's scope and one answer call with citation checks. It is cheap, predictable and still abstains when evidence is weak, so it suits clear questions where the agent simply wandered. Reserve a small slice of the budget, such as one search, one call and two seconds, so the fallback can always run.
Escalation hands the request to a person with the question, the evidence IDs collected and the reason. It suits ambiguous questions, requests with risk, or runs where fixed RAG already failed. Compare both on your fixture cases that exhaust the budget and pick per case type.
- Reserve budget for the fallback before the loop starts
- Fixed RAG: clear questions, evidence likely exists
- Escalation: ambiguity, risk or fixed RAG already failed
- Reason codes: budget_exhausted plus the chosen path
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Retry or reject invalid output~35m
- 2Fail over when a model is unavailable~35m
- 3Stop work on client disconnect~35m
- 4Time out slow tools~35m
- 5Choose fixed RAG fallback or escalation~35m
Key points
- Decide the response to each failure type before it happens and write it down.
- Retry only failures that can succeed on retry, with a small limit and backoff with jitter.
- Every tool call has its own timeout inside the overall request deadline.
- When the budget is spent, fall back to fixed RAG or escalate; never keep going.
- Every outcome ends in a status and reason code that evaluation can count.
Key terms
Tap a card to flip it. 0/5 known
Examples
import asyncio
async def call_tool(tool, args, timeout_s: float):
try:
async with asyncio.timeout(timeout_s):
return {'ok': True, 'data': await tool(**args)}
except TimeoutError:
return {'ok': False, 'reason': 'tool_timeout'}
async def finish_when_budget_spent(question, scopes, evidence):
if evidence:
return await fixed_rag(question, scopes) # one search, one call
return {'status': 'escalated', 'reason': 'budget_exhausted'}A tool timeout becomes data the agent can act on; a spent budget ends the loop.
Walking one failing run
A staff user asks about the travel policy. Step 1: the model returns a route of "search_docs", which fails validation; one retry returns retrieve. Step 2: the search tool times out after 3 seconds and returns tool_timeout. Step 3: the agent tries the search again with a rewritten query, which succeeds. Step 4: the model call returns 503 twice; backoff waits about 1 then 2 seconds, and the third try succeeds. Step 5: the call budget is now spent before a final draft. The reserved slice runs fixed RAG, which finds the travel policy section and answers with one citation. Final status answered, with reason codes recorded for each event.
Retry with backoff and jitter inside a deadline
This helper retries only temporary errors and never sleeps past the deadline. TransientError stands for 429, 5xx and network timeouts in your model client wrapper.
import asyncio, random, time
class TransientError(Exception): ...
async def call_with_retry(fn, deadline_ts: float, max_tries: int = 3):
for attempt in range(max_tries):
try:
return await fn()
except TransientError:
wait = (2 ** attempt) * random.uniform(0.5, 1.5)
if attempt == max_tries - 1 or time.time() + wait >= deadline_ts:
raise
await asyncio.sleep(wait)Quick reference
- Invalid output: one retry with the validation error, then reject and escalate
- Retry 429 and 5xx with exponential backoff and jitter; never retry other 4xx
- Respect Retry-After; never sleep past the request deadline
- Fail over only to a model that passed the same evaluation suite
- Client disconnect: cancel the run and log it; nothing to return
- Per-tool timeout returns a structured tool_timeout result to the loop
- Reserve budget for fixed RAG fallback before the loop starts
- Every run ends with a status and a reason code
Common mistakes
- Retrying invalid output forever, or retrying 400 errors that will never succeed.
- Failing over to a model that has not passed the same evaluation suite.
- Catching every exception and returning a generic answer that hides the failure.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a table mapping each of the five failure types to its planned response and reason code.
- Exercise 2medium
Write validate_or_retry(call_model, schema) that validates output with Pydantic, retries once with the error message, and returns an escalation dict if both attempts fail.
- Exercise 3hard
Add fault injection to your model stub and mock tools (invalid output, 503, slow search, budget of 3 calls). Run 10 fixture cases with fixed RAG fallback and again with escalation as the budget ending. Compare correct answers, escalations and mean time.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How many retries are reasonable?
- Usually two or three for temporary errors, and one for invalid output. More retries rarely help and eat into the deadline and budget.
- Is falling back to fixed RAG safe?
- Yes, if it keeps the same scope filter and citation checks. It can still abstain, so it never forces an answer without evidence.
- Should the user see which fallback was used?
- They should see a clear status, such as answered or escalated. Internal details like retries and model failover belong in logs and traces.
- Do I need a paid backup model?
- No. For the lab, a second configuration of the deterministic stub or a local model works as the backup. In production, any backup must pass your evaluation suite first.