Systemsfor Aravinda
0 / 78 core
Week 8 · Modern systems

Agents and tool calling

2 hours · core path

Read first: Serving LLMs, Idempotency and the exactly-once myth, Retries, backoff, and circuit breakers

In one sitting

An agent is a loop: the model requests a tool, your runtime runs it, the observation goes back, until a stop. Tools that touch the world need an idempotency key, a timeout, and a sandbox, and the loop needs a step cap. Guardrails are allowlists and checks, and evals with a known outcome come before any prompt edit, especially when a retry would charge a card twice.

An agent is not a smarter request. It is a loop that can change the world between model calls: refund a charge, delete a bucket, send a message. The model picks the next action. Your runtime decides whether that action is allowed to happen, and whether it has already happened. If you skip that, the model will do the expensive thing twice and you will call it a prompt bug.

Core concepts

The loop is four beats.

  1. The model sees the task, the prior observations, and the tool list.
  2. It either stops with an answer or emits a tool call, a name plus arguments.
  3. Your runtime checks the call, runs it, and records what happened.
  4. The observation goes back to the model. Repeat until a stop, a step cap, or a deadline.

Each model call is an ordinary generation request. Serving LLMs still applies. The transcript grows by the tool call and the observation, so the next prefill is longer and the KV cache is larger. A loop that pastes a full log into the next turn becomes the long prompt that does not fit the batch. The step cap is a memory bound and a work bound, not a style preference.

Tools that touch the world need three properties before you expose them.

They are idempotent, or they carry an idempotency key. Idempotency means doing the operation twice has the same effect as doing it once. Setting “order 18 is refunded” can be natural idempotence if the write is a state, not a second insert. Charging a card or creating a refund is not naturally idempotent. A second call creates a second side effect. You impose idempotence with a key the runtime generates once per logical action, and a store that keeps the outcome. The model must not mint a fresh key on the retry. If it does, the store treats the retry as a new action and the charge runs again.

They have a timeout. A tool with no deadline holds a step open until the process dies. A timeout does not tell you the tool failed. It tells you the answer did not arrive. The charge may have succeeded. That ambiguity is why the key exists.

They run in a sandbox when they can affect machines, networks, or money. A tool that fetches a URL the model chose is an SSRF bug waiting for a prompt. A tool that runs code with production credentials is a remote shell with extra steps. The sandbox is the allowlist of hosts, the absence of those credentials, and a filesystem that is not your production disk.

Step cap. Pick a maximum number of model turns, and a maximum number of calls for the dangerous tools, and stop when you hit either. Without the cap, one confused task loops until something else falls over. Each turn is another prefill. Each call to a tool that charges is another chance to charge. The cap makes the worst case finite. Tasks that truly needed one more step fail visibly. That is the trade.

Guardrails are allowlists and checks, not a paragraph in the prompt. The allowlist is the set of tool names this task may call. A name that is not on it does not run, even if the model emits perfect arguments. The checks are argument types, ranges, and a tenant id that matches the caller. A post-check reads the model’s final claim and compares it to the tool log: if the answer says “refunded” and the log does not, you do not show the sentence. A system prompt that says “never refund twice” is not one of these. The model can ignore it. The allowlist cannot be ignored, because the runtime, not the model, dispatches.

Evals come before prompt edits. An eval is a set of tasks with a known outcome. “This transcript’s next action is one refund of order 18.” “This user asked to delete another tenant’s row, and the tool was not called.” When a run looks wrong, score the set. If the observation was already wrong, a prompt edit hides a tool bug. If the observation was right and the model called the wrong tool, then a prompt or a schema change is a candidate, and you re-run the whole set after one change. Starting from the wording, because one anecdote failed in chat, is how you collect a prompt nobody can explain.

Retries, backoff, and circuit breakers apply to the tool, not to the model’s mood. Retry only when the call is idempotent or keyed. Use exponential backoff with full jitter, and only if the attempts still fit the step deadline. If the provider is down, open the breaker and fail the step. Do not spend the step cap hammering it.

flowchart LR
  task[User task] --> model[Model]
  model --> gate[Allowlist check]
  gate --> key[Idempotency key]
  key --> tool[Sandboxed tool]
  tool --> obs[Observation]
  obs --> model
  model --> done[Stop at the step cap]

The key sits on the runtime’s side of the gate. The model never gets to choose it. The sandbox sits around the tool. The cap sits on the loop, including the path that would otherwise cycle through the model forever.

A worked example

The tool charges. The user says “refund order 18.” The model emits refund(order=18). You are the runtime.

Assumptions:

  • 100,000 agent tasks a day. Smaller than a chat product, stated so the arithmetic stays about tasks and not about a model’s tokens per second.
  • The step cap is 8 model turns. That is a design choice, not a measured optimum.
  • A confused loop with the cap removed calls a tool every 5 seconds. Assumption, so you can see an unbounded day.
  • The refund provider times out sometimes after it has already accepted the refund. You do not get to assume the timeout means “nothing happened.”
1 day = 86,400 s
shortcut ≈ 100,000 s
100,000 tasks / 86,400 ≈ 1.16 tasks/s

assumption: step cap is 8, and a bad day uses the whole cap
model calls ≈ 1.16 × 8 ≈ 9.3/s

without a cap, one stuck task calls a tool every 5 s
calls in a day from that one task ≈ 86,400 / 5 = 17,280

Nine model calls a second is a serving problem you can size. Seventeen thousand calls from a single stuck task is a bug with a multiplier. If those calls are refunds, you have seventeen thousand refund attempts from one sentence. The cap stops the count. It does not, by itself, stop a double charge inside the cap. That is the key.

Walk the timeout. Stripe’s published pattern is the one to copy, and it is documented as an API behavior, not as a property of the model. The client, which in this system is your runtime, sends an idempotency key. The server stores the key with the outcome and, on a retry with the same key, returns the stored outcome instead of charging again. Keys in that guidance live on the order of 24 hours, long enough to cover retries, not a permanent archive. The same key with different parameters is an error, because the key is bound to a fingerprint of the arguments. Concurrent retries with the same key must lock, so two workers do not both run.

Put that on the refund tool.

  • The runtime derives one key for “this task, this refund, these arguments.” Order 18 and a specific amount. A second model call with the same arguments reuses the key. A call with a different amount and the same key is rejected as a fingerprint mismatch, not executed.
  • At the start, write a row: key, fingerprint, state starting. That row is the recovery point.
  • Call the provider with the key.
  • If the provider returns success, store the outcome and set state done. A later call returns that outcome and does not refund again.
  • If your client times out, you know only that the row says starting or, if the response was lost after the provider committed, that a reconciliation by key will find done. You do not start a second refund under a new key to “be safe.” Safe is the same key.

The model will still try to help. It sees a timeout observation and emits refund(order=18) again, sometimes with a key it invented. The runtime ignores the invented key, looks up the logical action, and returns the stored observation. The model can continue. The provider sees one refund.

Two workers can pick up the same task after a crash. The lock on the key is what stops both of them from passing starting and calling the provider. A local database transaction can roll back the row. It cannot roll back a refund that already left your process. Once you might have called out, the recovery point is the only memory that matters.

The sandbox version of the same story is quieter and as serious. A “fetch the invoice” tool takes a URL from the model. Without an allowlist, the model can be talked into fetching your metadata service or an internal admin host. The charge tool’s cousin is any tool with a credential. The allowlist of hosts and the absence of ambient credentials are the guardrail. The prompt line “only fetch invoice hosts” is not.

Evals, before anyone edits the prompt. Write tasks with known outcomes:

  • Refund order 18 once. The ledger shows one provider call. The answer says refunded.
  • The provider times out after success. Replay the same task. The ledger still shows one provider call. The stored outcome is what the model sees.
  • The user asks to refund someone else’s order. The allowlist check or the tenant check rejects it. The provider is not called.
  • The user asks a question the tools cannot answer. The model stops with no tool call, inside the step cap.

Run them. Suppose the timeout task shows two provider calls. The bug is the key, the lock, or a model-supplied key the runtime trusted. A prompt change that says “do not retry refunds” leaves the double charge in place the next time a worker replays the task. Suppose instead the ledger shows one call and the answer says the refund failed. Retrieval of the observation is fine, the tool is fine, and the model misread a success. That is when a prompt or a schema tweak is allowed, and you re-run all four tasks, not the one that annoyed you.

Serving still bounds the loop. Eight turns of a growing transcript can be the long prompt. If each observation is large, turn 8 may not fit beside the resident batch, and time to first token on that turn becomes queue time or a refusal. Cap the observation size you append, the same way you cap the steps. A tool that returns a megabyte of logs into the next prefill is a serving incident wearing an agent costume.

Tradeoffs

Choice What you gain What you spend
Runtime-owned idempotency key A retry, a timeout, and a second model call share one outcome A store, a fingerprint, and a lock
Model-supplied key Less code in the runtime The model mints a new key and the charge runs again
Natural idempotent write Simple when the tool sets state Does not fit “create a refund” or “send this email”
Step cap Worst-case model calls and tool calls stay finite A task that needed one more step fails closed
Sandbox and host allowlist A bad argument cannot reach production or an internal URL Plumbing, and tools that are less convenient to write
Prompt sentence as the only guard Fast to type The model can ignore it, and the tool still runs
Eval set before a prompt edit You learn whether the tool, the check, or the model was wrong You have to write tasks with known outcomes and keep them

Exactly-once across your database and a payment provider is not a checkbox you turn on. At-least-once delivery plus a keyed handler is the shape you can actually build. Stripe’s idempotency writeup is worth copying for the recovery point, and it is still your job to make the agent runtime the client that holds the key.

Pitfalls

  • Letting the model generate the idempotency key. A retry looks like a new refund. The ledger shows two charges and the prompt says you were careful.
  • Treating a timeout as proof the tool did not run. The provider may have committed. A second call without the stored key commits again.
  • An unbounded loop. One stuck task issues a tool call every few seconds and, if the tool charges, keeps charging. The step cap is what makes 17,280 a number you refused.
  • A guardrail that lives only in the system prompt. The allowlist and the argument checks are the guardrail. The sentence is decoration.
  • Two workers and no lock. Both read starting and both call the provider. The key without the lock is a log of the double charge, not a prevention.
  • Editing the prompt because one refund looked wrong in a demo, with no task whose expected ledger you can re-score.
  • Appending the raw tool output forever. The next prefill does not fit the batch. Time to first token collapses, and the step cap arrives as a serving error rather than a clean stop.
  • A URL-fetch tool with ambient network access. The model will eventually be given a URL that is not an invoice. Allowlist the hosts or do not ship the tool.
  • Retrying a non-keyed tool with backoff as if jitter made it safe. Jitter spaces the double charges. It does not merge them.

In the interview

Describe the loop in one pass: model, tool, observation, stop. Then go straight to the tool that charges. The runtime owns the idempotency key, stores the outcome, locks concurrent retries, and treats a timeout as unknown rather than as failure. Name the step cap and what it bounds. Say guardrails are an allowlist and checks. Say you would reproduce the bug on an eval task before changing the prompt.

Skip a tour of agent frameworks. Skip a claim of exactly-once across a third party. You do not have that property. You have a key and a recovery point.

The question that usually follows is the timeout after a successful charge, or the model calling the tool twice because it did not believe the first observation. You answer with the same key and the stored outcome. If they ask how you know a prompt change helped, say you froze the tool results, re-ran the task set, and looked at the ledger rather than the tone of the answer.

Check yourself

The refund provider accepts the charge and the response is lost. The model calls the tool again. What has to be true so the customer is not refunded twice?

The second call must carry the same idempotency key as the first, with the same argument fingerprint, and the provider or your store must return the recorded outcome instead of creating a new refund. The runtime owns that key. A key the model samples on the second call is a new action. A timeout is not evidence the first call failed.

Why is a system prompt that says never refund twice not a guardrail?

The model can ignore the sentence and emit the tool call anyway. A guardrail is the allowlist that decides which names can run, the argument and tenant checks, the idempotency store, and the post-check that the final claim matches the tool log. Those run in code on the runtime side of the loop. The prompt is not on that side.

With no step cap, one stuck task calls a charging tool every 5 seconds. How many calls is that in a day, and what did you assume?

A day is 86,400 seconds. Divided by 5 seconds, that is 17,280 calls from one task, under the assumption that the loop keeps that pace and nothing else stops it. The step cap is what replaces that open-ended count with a number you chose, such as 8 turns. The cap still needs the idempotency key, because two calls inside the cap are enough to double-charge.

An eval task times out and the ledger shows two provider calls. A teammate wants to edit the prompt first. What do you run instead, and why?

You already have a task with a known outcome: one provider call. The ledger contradicts it, so the bug is in the key, the lock, or the runtime accepting a model-supplied key. A prompt edit does not merge two charges that already happened, and it will not stop a second worker from replaying the task. Fix the handler, then re-run the whole task set, including the cases that should refuse another tenant’s order.

Each tool observation is large and the loop is on turn 8. The model server starts refusing the next turn. What resource ran out?

The transcript became a long prompt. Prefill and the KV cache grow with that length, and turn 8 no longer fits beside the resident batch. The step cap and a cap on observation bytes are what keep a later turn inside the memory you sized. Raising the cap without bounding the bytes makes the next refusal later and more expensive.

Based on: Stripe Idempotency-Key and recovery points, Brandur Leach; Idempotent handlers and at-least-once delivery; Serving constraints on prefill and the KV cache.