Agents and tool use¶
An agent is a language model that chooses actions (tool calls) in a loop, reading each result before choosing the next, until it decides the goal is met. Everything hard about agents follows from that loop: errors compound across steps, context grows with every observation, and the model, not your code, now decides what happens next. The one idea: give the model as much autonomy as the task needs and no more, and engineer the loop's harness as carefully as the prompt.
10,000 ft
A bare language model can only emit text from what it absorbed in training. Tools give it exact computation, fresh information and the ability to act; a loop lets it use one tool's result to decide the next. The idea is old in AI (the agent and environment of reinforcement learning, the planners of classical AI), but it became practical between 2022 and 2024: MRKL and ReAct showed prompted models interleaving reasoning with actions, Toolformer showed models could learn when to call APIs, function calling arrived in the major APIs in mid-2023, and coding agents showed that an agent-computer interface matters as much as the model. By 2025 METR measured the length of software tasks frontier agents could complete doubling roughly every seven months. Agents rely on structured outputs and function calling, use retrieval as one of their tools, multiply into multi-agent systems, live or die by context engineering, connect to tools through MCP, and need guardrails because they act on untrusted input.
2,000 ft
The model sees a goal, a list of tools (names, descriptions, JSON schemas) and everything that has happened so far. It either answers or emits a tool call. Your harness validates the call, checks permissions and budgets, runs the tool, and appends the result (or the error) to the context. Repeat.
- Choose the autonomy level: a fixed workflow if the steps are known, an agent only if they are not.
- Design the tools as an interface for a model: few, well named, well described, returning compact, meaningful results and errors that teach.
- Run the loop with hard limits: steps, tokens, time, money.
- Gate side effects: read freely, write only with validation, idempotency and, where it matters, human approval.
- Evaluate outcomes and consistency (pass^k), not one lucky run.
Ground level¶
The loop, concretely¶
With a function-calling API, one turn of the loop is one model request. You send the conversation plus tool definitions; the response either contains text (done) or one or more tool calls, each a tool name and JSON arguments. You execute them and send the results back as tool-result messages tied to the call ids, then ask the model again. Everything else is harness: what the model sees, which calls are allowed, when to stop.
Simon Willison's one-line definition, after collecting hundreds of competing ones, is the most useful: "An LLM agent runs tools in a loop to achieve a goal." Each word matters. Tools: the model's only way to affect or observe the world. Loop: the result of one call informs the next. Goal: the model, not your code, decides when it has been met.
The Build-it section runs a complete loop with a scripted stand-in for the model. Its trace shows the three habits that separate working agents from demos: the tool error is returned to the model as an observation (not raised as an exception that kills the run), the error message says what valid input looks like, and the model corrects itself on the next step.
Workflows first: the autonomy spectrum¶
Anthropic's "Building effective agents" (Schluntz and Zhang, December 2024) draws the line that matters most in practice. Workflows are "systems where LLMs and tools are orchestrated through predefined code paths". Agents are "systems where LLMs dynamically direct their own processes and tool usage". Between a single call and a full agent sit five reusable workflow patterns:
| Pattern | Shape | Use when | Example |
|---|---|---|---|
| Prompt chaining | Call A's output feeds call B, with code checks between | The task splits into fixed steps | Outline → check outline → write sections |
| Routing | A classifier picks one of several specialised paths | Inputs fall into distinct types | Refund vs technical vs sales questions; cheap model for easy ones |
| Parallelisation | Independent calls at once: sectioning (different subtasks) or voting (same task, several samples) | Subtasks are independent, or you need confidence | Guardrail check in parallel with the answer; three reviewers of one diff |
| Orchestrator-workers | A model decomposes the task at run time and delegates | Subtasks are not known in advance | Change every file affected by an API rename |
| Evaluator-optimiser | One call generates, another critiques against criteria, loop | Clear criteria, and iteration measurably helps | Translation with a fluency critic |
| Agent | The model chooses every action and when to stop | Open-ended problems where the path cannot be predicted | Fix a failing test in an unfamiliar repository |
The advice that follows from the table: start with the simplest pattern that works, and move right only when evaluation shows you need to. Workflows are cheaper, faster, easier to test and easier to explain. An agent buys flexibility with latency, cost and unpredictability.
Where the ideas came from¶
- MRKL (Karpas et al., AI21 Labs, May 2022) proposed a "modular, neuro-symbolic" architecture: a language model routing to expert modules such as a calculator or a database.
- ReAct (Yao et al., October 2022) prompted a model to alternate Thought, Action and Observation lines. Interleaving let reasoning plan the next action and observations correct the reasoning: on HotpotQA and FEVER it reduced the hallucination and error propagation of pure chain-of-thought, and on ALFWorld and WebShop it beat imitation and RL baselines by 34 and 10 points of absolute success with only one or two in-context examples.
- Toolformer (Schick et al., February 2023) showed a model could teach itself where an API call helps, by keeping self-inserted calls that lowered its loss on the following tokens.
- Reflexion (Shinn et al., March 2023) added verbal self-critique between attempts, stored as memory, as a cheap substitute for weight updates.
- Function calling (OpenAI, June 2023, then every major provider) moved tool use from prompt formats into the API: the model was fine-tuned to emit JSON matching a schema.
- CodeAct (Wang et al., 2024) argued that the action should be code: one Python snippet can call several tools, loop and branch, and it beat JSON tool calls by up to 20% success on its benchmarks.
- SWE-agent (Yang et al., 2024) showed that the agent-computer interface (ACI), a set of commands designed for a model rather than a human (a file viewer that shows 100 lines at a time, an edit command with a built-in linter that shows the agent the errors it just introduced), raised performance substantially on SWE-bench.
The common thread is that the model is a capable but fallible policy, and most of the engineering goes into the environment you give it.
Designing tools for a model¶
A tool's name, description and schema are a prompt the model reads on every step, and its return value becomes context. Anthropic's guide "Writing effective tools for agents" (September 2025) and the SWE-agent paper converge on these rules:
- Fewer, higher-level tools. Rather than
list_users,list_eventsandcreate_event, offerschedule_event, which does the lookup internally. "More tools don't always lead to better outcomes": each tool costs context and is one more wrong choice. - Names and namespaces. Prefix by service and resource (
asana_search,jira_search) so the model can tell similar tools apart. Name parameters unambiguously:user_id, notuser. - Descriptions written for a new colleague. Say what the tool does, when to use it, when not to, what each parameter means with an example, and what comes back.
- Poka-yoke the arguments. Make mistakes hard to express. Anthropic's SWE-bench agent kept making errors with relative file paths, so they "changed the tool to always require absolute filepaths". Use enums instead of free strings, and strict schemas so malformed calls cannot be generated (see structured outputs).
- Return meaning, not identifiers. Resolve opaque ids to names; return the fields the next
decision needs. Offer a
response_formatof concise or detailed: in Anthropic's example the concise response was 72 tokens against 206 for the detailed one. - Bound the output. Paginate, filter and truncate with sensible defaults; Claude Code caps tool responses at 25,000 tokens by default. A tool that dumps a 2 MB log has just destroyed your context window.
- Errors that teach. "Error: unknown customer 'ACME'; known: ['acme']" lets the model fix itself; a stack trace or "400 Bad Request" does not.
- Evaluate tools like prompts. Run the agent on realistic tasks, read the transcripts, and look at where it chose the wrong tool or the wrong argument. Most fixes are to descriptions.
Wrapping your REST API one endpoint per tool
It feels thorough and it is usually the worst design. The model must chain several low-level calls (each a chance to err, each result bloating context) to do one thing a human would think of as a single action. Design tools around the tasks the agent performs.
Planning, reflection and parallel calls¶
Plain ReAct decides one step at a time. Three refinements trade flexibility for efficiency:
- Plan-and-execute. A planner writes a multi-step plan up front, executors carry it out, and the planner revises only when something fails. ReWOO (Xu et al., 2023) plans all tool calls with placeholders for their results before seeing any observation, saving the tokens of re-reading the history at each step.
- Parallel tool calls. Most APIs let the model emit several independent calls in one turn. LLMCompiler (Kim et al., 2023) builds a dependency graph of calls and executes independent ones concurrently, like a compiler scheduling instructions.
- Reflection. After a failure (a test fails, a validator rejects), the model writes a short critique that is kept in context or memory for the next attempt (Reflexion). This works when there is a real signal to reflect on; reflection without external feedback often just rationalises.
Reasoning models (see reasoning models) have absorbed much of explicit planning: they think before each tool call, and many APIs keep that reasoning across tool calls within a turn. The harness still owns budgets, permissions and termination.
Reliability: why long tasks are hard¶
If every step must be right and each is right with probability \(p\), an \(n\)-step task succeeds with probability \(p^n\). At \(p = 0.95\): 0.774 for 5 steps, 0.599 for 10, 0.358 for 20, 0.077 for 50. This is the core reason agent demos impress and agent products disappoint: demos are short.
The rescue is error recovery. Suppose a step goes wrong with probability \(e = 0.05\), but the agent notices (a test fails, a tool returns an error, a validator objects) and fixes it with probability \(r = 0.8\). Only unrecovered errors are fatal, so the effective per-step failure is \(e(1 - r) = 0.01\) and a 20-step task succeeds with probability \(0.99^{20} = 0.818\), not 0.358. Recovery turned a 95% agent into an effective 99% one. That is why the best agent environments are rich in verifiable feedback: compilers, tests, schema validators, read-back checks.
Consistency is a separate property. τ-bench (Yao et al., 2024) simulates a user talking to an agent that must follow a domain policy (airline or retail) using API tools, and grades the database state at the end against the goal. It introduced pass^k: the probability that all \(k\) independent trials of a task succeed. Coding benchmarks report pass@k, the probability that at least one succeeds, which measures capability; pass^k measures the reliability a customer experiences. With per-trial success 0.6, pass@8 is 0.9993 but pass^8 is 0.0168. The paper found gpt-4o succeeded on under 50% of tasks with pass^8 under 25% in retail.
Horizon is growing. METR (Kwa et al., 2025) measures the 50% time horizon: the length of task, timed on skilled humans, that a model completes half the time. Claude 3.7 Sonnet's was around 50 minutes in early 2025, and the horizon had doubled roughly every seven months since 2019. The paper attributes the gains mainly to better reliability and recovery from mistakes, which is exactly the \(r\) in the formula above. See computer-use and long-horizon agents for where this is going.
The harness: budgets, permissions and side effects¶
The model proposes; the harness disposes. A production harness enforces:
- Termination. A maximum number of steps, tokens, wall-clock time and money per task, and a clear outcome when a limit is hit ("stopped: budget exhausted", with what was done so far). Detect loops: the same call with the same arguments three times is a bug, not persistence.
- Validation. Parse every call against its schema; reject and explain rather than guess.
- Permissions. An allowlist of tools per task and per user. Reads are cheap to allow; writes, payments, emails and deletes need policy, and often a human approval step that shows the exact action.
- Side-effect hygiene. Idempotency keys so a retried call does not pay twice; a dry-run or preview mode; reversible actions where possible, with a recorded plan to undo them.
- Sandboxing. Code execution and browsing run in an isolated environment with no ambient credentials and limited network access.
- Observability. A trace of every step: the context the model saw, its call, the result, latency and tokens. You cannot debug an agent from its final answer.
- Untrusted input. Tool results (web pages, emails, documents) can contain instructions aimed at the model. Never combine access to private data, exposure to untrusted content and the ability to send data out in one agent without strong controls; see guardrails and security.
Cost and latency¶
Each step re-sends the whole context. With \(P\) tokens of system prompt and tool definitions and \(s\) tokens added per step (the call plus its result), step \(t\) reads \(P + (t-1)s\) tokens, so a \(T\)-step run reads
input tokens: quadratic in the number of steps. With \(P = 3{,}000\), \(s = 500\) and \(T = 30\), that is 307,500 input tokens for a task whose transcript ends at about 17,500. Prompt caching changes the economics: if each step re-reads the previous step's context from cache at 10% of the normal price, the price-equivalent falls to 46,500 tokens, 15% of the uncached cost (the Build-it code computes both). That is why production agents keep their context append-only and their prefix stable; see context engineering. Latency adds up the same way: 30 sequential model calls at a few seconds each is minutes, so parallel tool calls and smaller, faster models for simple steps matter.
Evaluating agents¶
Judge the outcome, then the path:
- End-state checks. Did the database, file system or repository end up right? τ-bench compares database state; SWE-bench (Jimenez et al., 2023) runs the repository's own tests after the agent's patch. Outcome checks are robust to the many valid paths an agent can take.
- Trajectory checks. Did it call a forbidden tool, exceed a budget, ask the user when it should have, leak data into a tool argument? These are assertions over the trace.
- Repeat. Run each task several times and report pass^k alongside the mean; agents are stochastic and users experience the variance.
- Cost and latency per solved task, not per call.
See evals in practice for building the task set and LLM judges.
Jarvis: an assistant that is deliberately not an agent by default
Finny's assistant answers questions about a member's financial plan with a fixed workflow: a routing call picks named slices of the plan and one deterministic operation, code computes every figure, a model phrases the answer and a code gate checks every number in it. The team chose this over a free tool-calling agent because, in their words, a free agent over raw data "degrades across turns" and produces "numbers from tokens". Their proposed extension for compound questions is a bounded, read-only agent that chains a few of the same deterministic capabilities through the same gate. The one route that does act, a scenario agent that writes a what-if goal into a scratch copy of the plan, runs it and resets it, was paused after a production incident: a backend change it did not know about left the scratch plan un-reset, and recovery needed a person. The lesson generalises: a write path needs a recorded marker before the first write, a reset that is verified, and a block on new runs until cleanup is proven. See the Jarvis case study.
First principles¶
An agent is a policy in a partially observable world. Formally, the environment has a hidden state \(s_t\) (the repository, the database, the web); the agent receives observations \(o_t\) (tool results) and emits actions \(a_t\) (tool calls or a final answer). A language model agent is a policy \(\pi_\theta(a_t \mid h_t)\) conditioned on the history \(h_t = (g, a_1, o_1, \ldots, o_{t-1})\), where \(g\) is the goal. The history is the agent's belief state, which is why context management is not an optimisation but the agent's memory. Unlike an RL agent, the policy is not trained on this environment: it is a prior over sensible actions learned from text and post-training, steered by the prompt and tool descriptions. This is the POMDP framing, and it explains both the power (a strong prior needs no environment-specific training) and the brittleness (the prior can be confidently wrong about an environment it has never seen).
Why tools at all? Three things a model cannot do from its weights: compute exactly (arithmetic and code are cheap and certain in an interpreter, expensive and uncertain in tokens), know what changed after training or what is private to you (retrieval and APIs), and change the world (writes). Each tool converts a probabilistic guess into an observation.
Why loops? Control theory distinguishes open-loop control (compute the whole plan, then execute blindly) from closed-loop control (measure, correct, repeat). Open-loop errors accumulate: the \(p^n\) curve. Closed-loop control uses feedback to cancel errors as they arise: the recovery curve. An agent loop is closed-loop control with a language model as the controller, and the quality of the feedback signal (tests, validators, informative errors) bounds how much it can correct.
Why not always an agent? Autonomy moves decisions from code you can test to a policy you can only sample. Every decision the model makes is one you must evaluate statistically rather than verify once. If you can write the decision as code, writing it as code is cheaper, faster and more reliable. This is the case for workflows, and for keeping agents' action spaces small.
The maths¶
Compounding and recovery. With per-step error probability \(e\) and recovery probability \(r\) (independent across steps), the probability that an \(n\)-step task has no unrecovered error is
The expected horizon before the first fatal error is \(1/\big(e(1-r)\big)\) steps: 20 steps at \(e = 0.05, r = 0\); 100 steps at \(r = 0.8\). Halving the unrecovered error rate doubles the horizon, which is the same "doubling" METR measures in human-time units.
pass@k and pass^k. For a task with per-trial success probability \(q\) and independent trials,
Over a task set, average each over tasks. Given \(n\) trials of which \(c\) succeeded, unbiased estimators are \(1 - \binom{n-c}{k}/\binom{n}{k}\) for pass@k (Chen et al., 2021, the Codex paper) and \(\binom{c}{k}/\binom{n}{k}\) for pass^k.
Token cost of a loop. With prefix \(P\), per-step growth \(s\) and \(T\) steps, uncached input tokens are \(TP + sT(T-1)/2\). With a cache-read price ratio \(\rho\) (around 0.1 on several providers as of 2026) and ignoring cache-write surcharges,
so caching cuts the quadratic term by the factor \(\rho\), leaving a linear term for genuinely new tokens.
Retries for transient errors. If a call fails transiently with probability \(f\) and you retry up to \(m\) times, the call eventually succeeds with probability \(1 - f^{m+1}\), and the expected number of attempts is \((1 - f^{m+1})/(1 - f)\). At \(f = 0.1\) and \(m = 2\): success 0.999, expected 1.11 attempts. Retry transient failures in the harness; return logical failures to the model.
Build it¶
A complete agent loop in plain Python, with a scripted function standing in for the model so it
runs without an API key. Swap fake_model for a real model call that returns either a tool call
or a final answer, and the harness is unchanged:
import json
# Tools: plain functions plus a JSON-schema-like spec the model would see.
INVOICES = {"acme": [{"id": "INV-7", "usd": 1200.0}, {"id": "INV-9", "usd": 450.0}]}
RATES = {("USD", "EUR"): 0.92}
def search_invoices(customer):
if customer not in INVOICES: raise ValueError(f"unknown customer '{customer}'; known: {list(INVOICES)}")
return INVOICES[customer]
def convert(amount, src, dst):
return round(amount * RATES[(src, dst)], 2)
TOOLS = {"search_invoices": search_invoices, "convert": convert}
def fake_model(messages):
"""Stands in for an LLM: reads the transcript, returns a tool call or a final answer."""
last = messages[-1]
if last["role"] == "user":
return {"tool": "search_invoices", "args": {"customer": "ACME"}} # a mistake
if last["role"] == "tool" and last["is_error"]:
return {"tool": "search_invoices", "args": {"customer": "acme"}} # self-corrects
if last["role"] == "tool" and last["name"] == "search_invoices":
total = sum(i["usd"] for i in json.loads(last["content"]))
return {"tool": "convert", "args": {"amount": total, "src": "USD", "dst": "EUR"}}
return {"final": f"Your two invoices total EUR {json.loads(last['content'])}."}
def run_agent(task, model, max_steps=6):
messages = [{"role": "user", "content": task}]
for step in range(1, max_steps + 1):
action = model(messages)
if "final" in action:
print(f"step {step}: FINAL {action['final']}"); return action["final"]
name, args = action["tool"], action["args"]
try:
result, err = json.dumps(TOOLS[name](**args)), False
except Exception as e: # errors go back to the model, not up the stack
result, err = f"Error: {e}", True
print(f"step {step}: {name}({args}) -> {result}")
messages.append({"role": "tool", "name": name, "content": result, "is_error": err})
return "Stopped: step budget exhausted."
run_agent("What do my ACME invoices total in euros?", fake_model)
step 1: search_invoices({'customer': 'ACME'}) -> Error: unknown customer 'ACME'; known: ['acme']
step 2: search_invoices({'customer': 'acme'}) -> [{"id": "INV-7", "usd": 1200.0}, {"id": "INV-9", "usd": 450.0}]
step 3: convert({'amount': 1650.0, 'src': 'USD', 'dst': 'EUR'}) -> 1518.0
step 4: FINAL Your two invoices total EUR 1518.0.
The reliability and cost arithmetic from this page, checked by simulation (NumPy):
import numpy as np
rng = np.random.default_rng(0)
# 1. Compounding: an n-step task where every step must succeed.
p = 0.95
for n in (1, 5, 10, 20, 50):
print(f"n={n:2} all steps right: {p**n:.3f}")
# 2. Recovery: a step fails with prob e; the agent notices and fixes it with prob r.
e, r, n = 0.05, 0.8, 20
analytic = (1 - e * (1 - r)) ** n
fails = rng.random((100_000, n)) < e
unrecovered = fails & (rng.random((100_000, n)) > r)
print(f"with recovery r={r}: analytic {analytic:.3f}, simulated {1 - unrecovered.any(1).mean():.3f}")
# 3. pass@k (any of k tries succeeds) vs pass^k (all k tries succeed), per-task success 0.6
q = 0.6
for k in (1, 2, 4, 8):
print(f"k={k} pass@k={1-(1-q)**k:.4f} pass^k={q**k:.4f}")
# 4. Tokens: history is re-sent every step. P = system+tools, s = tokens added per step.
P, s, T = 3000, 500, 30
ctx = P + s * np.arange(T) # input tokens at steps 1..T
total = ctx.sum()
cached = ctx[0] + (0.1 * ctx[:-1] + s).sum() # step t re-reads step t-1 from cache at 10%
print(f"T={T}: input tokens {total:,} (formula {T*P + s*T*(T-1)//2:,});"
f" price-equivalent with prefix caching {cached:,.0f} ({cached/total:.0%})")
n= 1 all steps right: 0.950
n= 5 all steps right: 0.774
n=10 all steps right: 0.599
n=20 all steps right: 0.358
n=50 all steps right: 0.077
with recovery r=0.8: analytic 0.818, simulated 0.818
k=1 pass@k=0.6000 pass^k=0.6000
k=2 pass@k=0.8400 pass^k=0.3600
k=4 pass@k=0.9744 pass^k=0.1296
k=8 pass@k=0.9993 pass^k=0.0168
T=30: input tokens 307,500 (formula 307,500); price-equivalent with prefix caching 46,500 (15%)
Things to try
- Replace
fake_modelwith a real model through any function-calling API. Give it the two tools with honest descriptions and run the same task ten times. How often does it pass"ACME"first, and does the error message always get it back on track? - Make the error message unhelpful (
"Error: 404") and rerun. Count the extra steps. - Add a
max_tokens_totalbudget torun_agentthat estimates tokens as characters ÷ 4 and stops cleanly when exceeded. - Add loop detection: stop if the same
(name, args)pair is called three times. - Add a
send_emailtool and require a humaninput()confirmation before it runs. Where should the confirmation text come from: the model's arguments, or your code's rendering of them? Why? - In the NumPy script, make errors correlated (a bad step raises the next step's error rate). How far does the analytic formula drift from the simulation?
In practice¶
- Start from a workflow and earn your way to an agent. Most "agent" products that work are a router plus a few chains, with one genuinely open-ended step.
- Prefer frameworks only when they save you code you understand. The loop is about 30 lines; the value of a framework is in tracing, durable state, retries and human-in-the-loop plumbing. Read what it sends to the model.
- Keep tool counts small (a handful to a few dozen); when you have hundreds, load tool definitions on demand (tool search, progressive disclosure, or code execution over MCP).
- Make the transcript your primary debugging artefact. Read dozens of traces before changing prompts; most failures are visible to a human in seconds.
- Ship with a kill switch and an audit log for any agent that writes.
Common misconceptions¶
- "Agents are a model capability." They are a system: model, tools, harness, context policy. The same model succeeds or fails depending on tool design and feedback.
- "More tools make an agent more capable." Past a point they make it worse: more context, more confusable choices.
- "Self-reflection fixes errors." Only when there is a signal to reflect on. Without external feedback, a model critiquing itself often confirms its own mistake.
- "pass@k shows the agent is reliable." It shows the agent can do the task. Users see pass^k.
Check yourself¶
What distinguishes a workflow from an agent, in one sentence?
In a workflow, code decides the sequence of steps and the model fills them in; in an agent, the model decides the next step and when to stop.
Why should a tool error be returned to the model rather than raised?
The error is an observation the model can act on (fix an argument, try another tool). Raising it ends the run on a mistake that is often trivially recoverable, and loses the recovery effect that makes long tasks feasible.
A 25-step task, 96% per-step accuracy, no recovery. Success probability? With 75% recovery?
\(0.96^{25} = 0.360\). With recovery the unrecovered error is \(0.04 \times 0.25 = 0.01\) per step, so \(0.99^{25} = 0.778\).
Your agent scores 90% pass@1 on 100 tasks. A customer runs each task four times and complains. What would you compute?
pass^4. If tasks were independent with \(q = 0.9\) each it would be \(0.9^4 = 0.656\); in reality success varies by task, so compute per task from repeated trials and average. The gap between pass@1 and pass^4 is the inconsistency the customer sees.
Why do agent costs grow quadratically with steps, and what are two mitigations?
Each step re-sends the whole history, which grows linearly, so the sum over steps is quadratic. Mitigations: prompt caching of the stable prefix (cuts the quadratic term by the cache price ratio); compaction or clearing of old tool results; delegating subtasks to sub-agents that return short summaries; fewer, more capable steps (parallel calls, code actions).
Hard: when would you choose CodeAct-style actions (the model writes Python that calls tools) over JSON tool calls, and what new risk does it bring?
When tasks need loops, branching, data transformation or many chained calls whose intermediate results need not pass through the model: one code action replaces many round trips and keeps large intermediate data out of context. The risk is executing model-written code: it needs a sandbox with no ambient credentials, resource limits and network policy, and its effects are harder to preview and approve than a single typed call.
Hard: frame a coding agent as a POMDP. What are the state, observations, actions and reward, and why is the history the belief state?
State: the repository, environment and test outcomes (largely hidden). Observations: file contents shown, command outputs, test results. Actions: commands, edits, the final submission. Reward: tests pass (often only at the end). The agent never sees the whole state, so its best estimate of it is everything it has observed so far: the conversation history is a sufficient (if bulky) belief state, which is why summarising it badly loses information the policy needs.
Go deeper¶
Papers
- ReAct: Synergizing Reasoning and Acting in Language Models — Yao et al., 2022. The Thought/Action/Observation loop; read the HotpotQA trajectories.
- MRKL Systems — Karpas et al., 2022. The modular "LLM routes to experts" architecture.
- Toolformer: Language Models Can Teach Themselves to Use Tools — Schick et al., 2023.
- Reflexion: Language Agents with Verbal Reinforcement Learning — Shinn et al., 2023.
- Executable Code Actions Elicit Better LLM Agents (CodeAct) — Wang et al., 2024.
- SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering — Yang et al., 2024. Section 2 on interface design is the part to read.
- τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains — Yao et al., 2024. pass^k and end-state grading.
- Measuring AI Ability to Complete Long Software Tasks — Kwa et al. (METR), 2025. The 50% time horizon and its seven-month doubling.
- An LLM Compiler for Parallel Function Calling — Kim et al., 2023.
- Cognitive Architectures for Language Agents (CoALA) — Sumers et al., 2023. A vocabulary for memory, actions and decision loops.
Videos and lectures
- How We Build Effective Agents — Barry Zhang (Anthropic), AI Engineer. The workflows-versus-agents talk from one of the post's authors.
- What's next for AI agentic workflows — Andrew Ng, Sequoia. Reflection, tool use, planning and multi-agent as design patterns.
- Stanford CS230, Lecture 8: Agents, Prompts, and RAG — Stanford Online, autumn 2025.
- Software Is Changing (Again) — Andrej Karpathy, YC. Partial autonomy and the "autonomy slider".
Articles and blog posts
- Building effective agents — Schluntz and Zhang (Anthropic), 2024. The five workflow patterns and when to use an agent.
- Writing effective tools for agents — Anthropic, 2025. Tool design, with numbers.
- A practical guide to building agents — OpenAI, 2025. Models, tools, instructions, orchestration and guardrails.
- LLM Powered Autonomous Agents — Lilian Weng, 2023. The classic survey of planning, memory and tool use.
- I think "agent" may finally have a widely enough agreed upon definition — Simon Willison, 2025.
Courses
- Hugging Face Agents Course — free, hands-on, framework by framework.
- Agentic AI — Andrew Ng, DeepLearning.AI. Reflection, tool use, planning and evaluation, taught as patterns.
Code
- openai-agents-python — a small agent SDK whose source is short enough to read in an afternoon.
- langchain-ai/langgraph — agents as explicit state graphs with durable checkpoints.
Where this leads¶
- Multi-agent systems and orchestration — when one agent's context is not enough.
- Context engineering and memory — managing the history that is the agent's belief state.
- MCP and tool protocols — connecting agents to tools through a standard.
- Guardrails and security — prompt injection, the lethal trifecta and permissions.
- Computer-use and long-horizon agents — the research frontier of autonomy.