Skip to content
Blog

Handling Tool Errors and Raising Recoverable Exceptions to the LLM

What the model actually sees when a tool fails, how to distinguish recoverable from terminal errors, writing error messages that produce a correct retry, sanitising output, and partial success patterns.

Published on • November 27, 2026

AI Assistant

A tool failure is not the end of a turn — it is information handed back to the model, which will decide what to do with it. Hand it a stack trace and the model improvises; hand it a precise, repairable description and the model does the thing you wanted: correct the call, choose another tool, or tell the user plainly.

This tutorial covers the mechanics (what the framework puts in front of the model when your function raises or returns an error), how to classify failures, and the message-writing discipline that turns errors into recoveries.

What the model sees

Two paths, both visible to the model:

1. You return an error dict. The tool completes normally, and your payload becomes the function response:

def get_invoice(invoice_id: str) -> dict:
    """Fetch an invoice by ID.

    Args:
        invoice_id (str): Invoice identifier, e.g. 'INV-4821'.
    """
    invoice = store.get(invoice_id)
    if invoice is None:
        return {'status': 'error', 'error_message': f'No invoice {invoice_id} exists.'}
    return {'status': 'success', 'invoice': invoice}

2. You raise. The framework catches it and puts an error result into the conversation so the model can react. The Gen AI SDK documents the same pattern explicitly: instead of raising the exception, you can let the model handle it — wrapping the exception text as {'error': str(e)}.

Which to choose? Return a dict for expected, domain-level failures (not found, permission denied, already processed). Raise for programming errors (bug, misconfiguration) that should surface to your error monitoring rather than into the conversation.

Either way, the model now holds an error and will act on it — which makes the content of that error a design surface.

Classify before you respond

ClassExampleWhat the model should doAction
Recoverable, user-fixableMissing/invalid argumentAsk the user or re-call with corrected argsReturn precise constraint text
Recoverable, retryable429, 503, timeoutRetry (or your tool already did)Return retryable: true, hint on delay
Recoverable, alternativeItem out of stock, no resultsOffer another tool/optionReturn why + available options
Terminal for this pathRecord doesn’t existStop; report honestlyReturn not-found; don’t imply otherwise
FatalBug, bad config, auth misconfiguredReport a real problemRaise; let your monitoring catch it

The last row is the one people get wrong: swallowing configuration errors into status: 'error' turns an obvious deploy bug into a model that politely apologises all day while nobody gets paged.

Error messages as repair instructions

A good tool error contains four things:

return {
    'status': 'error',
    'error_message': "urgency must be an integer from 1 to 5; got 'high'.",
    'error_code': 'INVALID_ARGUMENT',
    'retryable': False,
    'hint': 'Map the description to a number: low=1, normal=3, high=5.',
}
  1. What was wrong — the violated rule, not the exception class.
  2. What was given (when it’s safe to echo back).
  3. What correct looks like — format, range, or source to get it from.
  4. Whether retrying helps.

Rules of thumb:

  • Never say only “error”. The model will guess and often guess the same wrong way twice.
  • State provenance for IDs: "invoice_id must come from get_orders — INV-4821 is not a valid format" prevents fabrication better than any system-prompt sentence.
  • Keep terminal answers terminal. "No invoice exists" with retryable: false stops the loop; adding “please check the ID again” is fine, implying it might work next time is not.
  • Bound the loop. If the same tool fails identically three times, that’s a design bug — surface it to a callback layer rather than letting the model burn turns.

Sanitise: errors are an exfiltration path

Raw exceptions leak. Connection errors embed URLs with credentials; validation errors can echo user input (including injected instructions); stack traces reveal internals. Before an error reaches the model:

import logging, traceback

async def call_billing(**kwargs) -> dict:
    try:
        resp = await billing.post(**kwargs)
        return {'status': 'success', 'data': resp}
    except Exception:
        ref = uuid.uuid4().hex[:8]                 # correlation ID for humans
        logger.exception('billing tool failed ref=%s', ref)
        return {
            'status': 'error',
            'error_message': f'Billing service is unavailable (ref {ref}).',
            'retryable': True,
        }                                          # no URL, no token, no stack

Log the details for operators; return a correlatable, content-free message to the model. Note also that tool errors end up persisted in session events — anything you return is written down.

Partial success is usually the honest answer

Batch-shaped tools rarely fail all-or-nothing:

def import_contacts(rows: list[dict]) -> dict:
    """Import contacts from rows.

    Args:
        rows (list[dict]): Contact records with name and email fields.
    """
    ok, failed = [], []
    for i, row in enumerate(rows):
        try:
            contact = create_contact(row)
            ok.append(contact.id)
        except ValidationError as e:
            failed.append({'index': i, 'reason': str(e)})

    return {
        'status': 'success' if not failed else 'partial',
        'imported': len(ok),
        'failed': failed,
        'summary': f'Imported {len(ok)}/{len(rows)} contacts.'
                   + (f' Failed rows: {failed}.' if failed else ''),
    }

status: 'partial' lets the model report exactly what happened and decide whether to ask about the failed rows — without either pretending success or discarding the successful work.

Observability and hooks

Every tool failure deserves a metric: per-tool error rate, error code distribution, and the share that reach the model. A sudden rise in INVALID_ARGUMENT after a deploy means your schema or prompt changed and the model no longer understands the contract.

ADK’s callback and plugin layer lets you intercept tool execution — a before_tool hook can validate arguments early, and an after_tool/error path can normalise exceptions into your standard error envelope, so every tool in your codebase emits the same shape without duplicating try/except in fifty functions.

Takeaways

  • Errors reach the model either as a returned status: 'error' payload or as a raised exception the framework converts — pick by class: domain failures return, programming errors raise.
  • Write errors as repair instructions: violated rule, what was given, what correct looks like, and whether retrying helps.
  • Sanitise before returning — error text lands in the model’s context and in persisted session events.
  • Use partial status for batch work so partial progress is reported honestly.
  • Track per-tool error rates as a first-class metric; they’re your earliest signal of a broken contract.

Further reading