Tool Calls Fail Like APIs, Not Like Prompts
A production tool layer for AI agents should validate arguments, classify failures, budget retries, respect deadlines, and return useful observations instead of blindly asking the model to try again.
On this page
An agent can choose the correct tool and still fail repeatedly because the infrastructure around that tool is badly designed.
I see this as a backend problem more than an AI problem.
A tool call is an API call with one unusual caller: the arguments were proposed by a probabilistic model. Everything else is familiar. Requests can be invalid. Credentials expire. Dependencies throttle. Connections time out. Responses can be malformed. A write may succeed even when the caller never receives the response.
If the agent runtime treats all of those failures as “tell the model something went wrong and let it try again,” it will eventually build loops that are expensive, slow, and sometimes dangerous.
The example here is an IoT operations agent that can read a device state and request a configuration refresh. The details are different from a CRM or payment tool, but the recovery design is the same.
Validate before the network boundary
The cheapest failed API request is the one you never send.
If a tool accepts a device ID, timeout, and refresh mode, define that contract in application code.
import { z } from "zod";const RefreshDeviceInput = z.object({ deviceId: z.string().uuid(), mode: z.enum(["config", "firmware-metadata"]), timeoutMs: z.number().int().min(500).max(10_000),});type RefreshDeviceInput = z.infer<typeof RefreshDeviceInput>;Python:
from enum import Enumfrom pydantic import BaseModel, Fieldfrom uuid import UUIDclass RefreshMode(str, Enum): CONFIG = "config" FIRMWARE_METADATA = "firmware-metadata"class RefreshDeviceInput(BaseModel): device_id: UUID mode: RefreshMode timeout_ms: int = Field(ge=500, le=10_000)A model-generated deviceId: "all" should become a validation observation, not an HTTP request to a downstream service.
That distinction helps the model too. “Tool failed” is vague. “deviceId must be a UUID” gives the planner something it can correct once.
Failure type should decide the recovery
A 400, a 401, a 429, and a timeout are not four versions of the same problem.
I normally classify tool failures into a small set of operational categories:
type ToolFailureKind = | "invalid-input" | "unauthorized" | "forbidden" | "not-found" | "rate-limited" | "timeout" | "dependency-unavailable" | "invalid-response" | "unknown";type ToolFailure = { kind: ToolFailureKind; retryable: boolean; message: string; retryAfterMs?: number;};The mapping can be deterministic:
function classifyHttpFailure( status: number, body: string, retryAfterMs?: number,): ToolFailure { if (status === 400) { return { kind: "invalid-input", retryable: false, message: body }; } if (status === 401) { return { kind: "unauthorized", retryable: true, message: "credential expired" }; } if (status === 403) { return { kind: "forbidden", retryable: false, message: "action is not allowed" }; } if (status === 404) { return { kind: "not-found", retryable: false, message: "resource not found" }; } if (status === 429) { return { kind: "rate-limited", retryable: true, message: "dependency rate limited the request", retryAfterMs, }; } if (status >= 500) { return { kind: "dependency-unavailable", retryable: true, message: "dependency returned a server error", }; } return { kind: "unknown", retryable: false, message: body };}The model does not need to infer whether an HTTP 403 is worth trying again. The tool layer already knows.
Retry budgets belong outside the model loop
A retry policy should be boring enough to explain in one sentence.
For a read operation, I might allow two retries for a transient failure, with jittered exponential backoff and an overall deadline. For a write, I additionally require idempotency before retrying at all.
Here is a small TypeScript helper for retry-safe operations:
type RetryOptions = { maxAttempts: number; deadlineMs: number;};async function withRetry<T>( operation: () => Promise<T>, classify: (error: unknown) => ToolFailure, options: RetryOptions,): Promise<T> { const startedAt = Date.now(); for (let attempt = 1; attempt <= options.maxAttempts; attempt += 1) { try { return await operation(); } catch (error) { const failure = classify(error); const remaining = options.deadlineMs - (Date.now() - startedAt); if (!failure.retryable || attempt === options.maxAttempts || remaining <= 0) { throw failure; } const exponential = Math.min(250 * 2 ** (attempt - 1), 2_000); const jitter = Math.floor(Math.random() * 100); const requestedDelay = failure.retryAfterMs ?? exponential + jitter; const delay = Math.min(requestedDelay, remaining); await new Promise((resolve) => setTimeout(resolve, delay)); } } throw new Error("unreachable retry state");}Python:
import asyncioimport randomimport timefrom collections.abc import Awaitable, Callablefrom typing import TypeVarT = TypeVar("T")async def with_retry( operation: Callable[[], Awaitable[T]], classify: Callable[[Exception], ToolFailure], *, max_attempts: int, deadline_seconds: float,) -> T: started = time.monotonic() for attempt in range(1, max_attempts + 1): try: return await operation() except Exception as exc: failure = classify(exc) remaining = deadline_seconds - (time.monotonic() - started) if not failure.retryable or attempt == max_attempts or remaining <= 0: raise exponential = min(0.25 * (2 ** (attempt - 1)), 2.0) jitter = random.uniform(0, 0.1) requested = failure.retry_after_seconds or (exponential + jitter) await asyncio.sleep(min(requested, remaining)) raise RuntimeError("unreachable retry state")The important behavior is that retries are finite and constrained by a deadline. A tool wrapper should not be able to consume an unlimited part of an agent run just because the dependency is having a bad afternoon.
Authentication recovery is not the same as a retry
A 401 often has a specific recovery path: refresh the credential once, then retry the original request.
That should happen inside the connector, not through model reasoning.
The model should never be asked to decide whether an OAuth token needs refreshing. It should receive either the tool result or a clear observation that authorization could not be restored.
Similarly, a 403 is normally terminal for that action. Retrying it with the same identity wastes time and can become noisy security telemetry.
Return machine-readable observations to the agent
A tool failure should be structured just like a successful tool result.
type ToolObservation<T> = | { ok: true; value: T } | { ok: false; kind: ToolFailureKind; message: string; canRetryWithDifferentInput: boolean; };For invalid input, canRetryWithDifferentInput may be true. For forbidden actions, false. For a temporary outage after the retry budget is exhausted, the model can be told to choose another path or explain the limitation to the user.
That is much better than dropping a raw stack trace into context.
Raw dependency errors often contain headers, URLs, IDs, internal hostnames, or details the model does not need. Translate them at the tool boundary.
Timeouts need cancellation, not only impatience
This code is incomplete:
await Promise.race([ callTool(), timeout(5_000),]);It stops *waiting* after five seconds. It may not stop the underlying network request.
Use cancellation primitives so the work itself can be torn down.
async function fetchDevice( url: string, signal: AbortSignal,): Promise<Response> { return fetch(url, { signal });}async function withTimeout<T>( timeoutMs: number, fn: (signal: AbortSignal) => Promise<T>,): Promise<T> { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { return await fn(controller.signal); } finally { clearTimeout(timer); }}For Python HTTP clients such as httpx, use explicit connect/read/write/pool timeouts and propagate cancellation from the surrounding asyncio task.
Timeouts are a resource-management concern. They should stop work, not merely make the caller stop looking at it.
Response validation is part of tool reliability
The tool endpoint can return HTTP 200 and still break your agent.
An upstream API changes a field from temperature to temperatureC. A database wrapper returns null where the tool contract promised an array. A third-party service sends an HTML error page with status 200.
Validate tool responses before placing them into model context.
const DeviceStateSchema = z.object({ deviceId: z.string().uuid(), online: z.boolean(), lastSeenAt: z.string().datetime(),});function parseDeviceState(value: unknown) { const parsed = DeviceStateSchema.safeParse(value); if (!parsed.success) { throw new StructuredOutputError( "Device service returned an invalid response", parsed.error.issues, ); } return parsed.data;}An agent should not have to reason about whether a dependency's response shape changed. That is adapter code.
Writes need a different contract
Everything above is simplest for reads.
Once a tool sends an email, changes a device configuration, creates an invoice, or starts a deployment, retries carry side-effect risk.
For those tools I require three additional properties:
- an idempotency key tied to the agent's logical action;
- an audit record of the proposed arguments and actor identity;
- a clear distinction between “request failed before execution” and “execution outcome is unknown.”
The last state matters. A timeout after sending a write request does not prove the write failed. The correct recovery is often to query by idempotency key or operation ID before attempting anything again.
What the model should actually decide
After moving validation, authentication, retries, response parsing, deadlines, and side-effect safety into the tool layer, the model has a much smaller job.
It decides things like:
- should I use another tool?
- can I correct the arguments from the validation feedback?
- is there another way to answer the user?
- should I explain that the dependency is unavailable?
- should I request human help?
Those are reasoning questions.
“Should HTTP 429 be retried with exponential backoff?” is not.
Avoid building a generic retry monster
It is easy to over-abstract this into one universal executor with thirty flags.
I prefer a common failure vocabulary and a few shared primitives, then tool-specific policies where behavior differs. A read-only search tool, an email sender, and a deployment trigger do not have the same retry semantics just because all three are called by an agent.
Traditional distributed-systems rules still apply. The model does not get a special exemption from them.
If a tool call is unreliable, the right fix is usually not another prompt telling the agent to “be careful.” It is an explicit contract at the boundary: validate what goes out, validate what comes back, classify failures, retry only the failures that can improve, stop on a budget, and make writes safe to repeat before you ever repeat them.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article