Skip to content
AI.info

Implementation Guides

Building Effective AI Agents: Six Patterns and When to Use Each

Anthropic's five workflow patterns and the agent loop, told through the production systems built on them: when each pays, what it costs, how to test it, and a short Python sketch of each, with the…

Building Effective AI Agents: Six Patterns and When to Use Each

Earn Every Step of Autonomy

When Anthropic first set a team of Claude agents loose on research questions, the agents could not tell an easy question from a hard one. Early versions spawned 50 subagents for simple queries, scoured the web endlessly for sources that did not exist, and distracted each other with excessive updates. The fix was a set of scaling rules written into the prompts: simple fact-finding gets one agent with 3 to 10 tool calls, a direct comparison 2 to 4 subagents with 10 to 15 calls each, and only complex research more than 10 subagents with clearly divided responsibilities.

The architecture earned its keep. A Claude Opus 4 lead directing Claude Sonnet 4 subagents outperformed a single Claude Opus 4 agent by 90.2% on Anthropic's internal research eval. It also burned through tokens: Anthropic measured multi-agent systems at about fifteen times the tokens of a chat interaction. Those three numbers frame every decision in agent design. Autonomy can buy a large gain, it costs real money, and without limits written down somewhere it runs away.

The vocabulary for those decisions comes from an earlier Anthropic engineering post, "Building effective agents," published on 19 December 2024 and still a widely cited reference on the subject. Its advice fits in one sentence: use the least autonomy that solves the problem, and pay for more only when a measurement says you must. Its five workflow patterns and one agent loop are a vocabulary, not a framework. The patterns held up; the post's own header now says that much of the tooling landscape it describes has changed.

When building applications with LLMs, we recommend finding the simplest solution possible, and only increasing complexity when needed. — Erik S. and Barry Zhang, "Building effective agents," Anthropic, 19 Dec 2024

Workflows and Agents

The post splits "agentic systems" into two kinds. In workflows, LLMs and tools are orchestrated through predefined code paths. In agents, the LLM dynamically directs its own process and tool use, keeping control over how it accomplishes the task. The difference is who holds the control flow: your code, or the model.

A workflow is predictable, testable and cheap to reason about, because you wrote the branches. An agent is flexible, and you pay for the flexibility in latency, tokens and the chance of drifting somewhere you did not plan for. OpenAI's "A practical guide to building agents" draws the same line from the other side: applications that integrate LLMs but do not use them to control workflow execution, such as simple chatbots, single-turn LLMs or sentiment classifiers, are not agents in its definition.

Before any pattern there is a baseline to beat: one well-prompted LLM call with retrieval and a few examples in context, which the Anthropic post says is usually enough for many applications. The building block under every pattern is the augmented LLM, a model with retrieval, tools and memory that can write its own search queries, choose its own tools and decide what to retain. Every box in the diagrams below is one of these.

The six patterns at a glance: prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer and the agent loop

The post recommends starting with LLM APIs directly, because many of the patterns take a few lines of code. The sketches in this guide take that literally. They are plain Python with no framework and no provider SDK, and they assume one helper that sends a prompt to whichever model you use and returns its text:

def call_model(prompt: str) -> str:
    """Send one prompt to your model provider and return the reply text."""
    raise NotImplementedError("wire this to your provider's API")

Prompt Chaining

Prompt chaining: three LLM calls in sequence with a programmatic gate between the first and second

Prompt chaining splits a task into a fixed sequence in which each LLM call consumes the previous output. Between any two steps you can place a programmatic check, a gate, that stops the run if the intermediate result is off track. The trade is explicit in the post: you accept more latency in exchange for accuracy, because every call faces an easier task.

It pays off when the task decomposes cleanly into stages that never change. The post's examples are writing marketing copy and then translating it, and writing an outline, checking it against criteria, then writing the document from the outline. It does not pay off when the stages depend on what earlier stages discover, or when one capable call already gets the answer right.

Real systems use chains as their outer skeleton. Anthropic's Research feature ends with a fixed step: once the lead agent decides it has gathered enough, the system exits the research loop and hands every finding to a CitationAgent, which processes the documents and the report to locate the source for each claim. A harness Anthropic described in March 2026 for building whole applications is a three-stage chain of planner, generator and evaluator. The planner turns a one- to four-sentence prompt into a full product spec, and it survived when the post's author, Prithvi Rajasekaran, simplified the harness, because without the planner the generator under-scoped, started building without speccing its work, and produced a less feature-rich application.

def outline_then_write(brief: str) -> str:
    outline = call_model(f"Write a numbered outline of 5 to 8 points for:\n{brief}")
    points = [line for line in outline.splitlines() if line.strip()[:1].isdigit()]
    if not 5 <= len(points) <= 8:                       # gate 1: plain code, free
        raise ValueError(f"outline has {len(points)} points, expected 5 to 8")
    verdict = call_model(
        "Does this outline cover every requirement in the brief? Reply PASS or FAIL.\n"
        f"Brief:\n{brief}\nOutline:\n{outline}"
    )
    if not verdict.strip().upper().startswith("PASS"):  # gate 2: costs one call
        raise ValueError("outline failed the criteria check")
    return call_model(f"Write the document from this outline:\n{outline}")

The cost is arithmetic. Three sequential calls take roughly three calls' worth of latency, and each later call re-reads the earlier output as input tokens. A gate is cheap when it is code, such as a length check, a schema validation or a regex, and expensive when it is another model call.

To test a chain, test each link on its own. Collect twenty real inputs, run step one alone, and grade its output before you wire step two to it. Errors in a chain compound, so the earliest step deserves the most test cases.

Routing

Routing: a classifier sends each input to one of three specialised handlers

Routing classifies an input and sends it to a specialized follow-up: a different prompt, tool set or model. The gain is separation of concerns. Without it, tuning one prompt for one kind of input can quietly hurt every other kind.

Use it when inputs fall into distinct categories that deserve different handling and the classification itself is reliable. The classifier can be an LLM or a traditional classification model or algorithm. The post's examples are sending general questions, refund requests and technical support to different downstream processes, and sending easy or common questions to a smaller, cheaper model while hard or unusual ones go to a more capable one; its current text names Claude Haiku 4.5 for the first and Claude Sonnet 4.5 for the second.

Model routing has been measured. The RouteLLM paper (Ong and colleagues, June 2024) trained routers on human preference data to choose between a stronger and a weaker model at inference time, and reported that the approach cut costs by over 2 times in certain cases without compromising response quality. OpenAI's guide suggests how to find the split for your own task: build the prototype with the most capable model for every step to set a baseline, then swap in smaller models and see where they still meet the accuracy target. Its own customer-service example routes with a model: a triage agent reads a question about the delivery timeline of a recent purchase and hands the conversation to an order-management agent.

HANDLERS = {
    "refund": "You process refund requests. Order data:\n{context}\nRequest:\n{text}",
    "howto": "Answer using only these documentation excerpts:\n{context}\nQuestion:\n{text}",
    "bug": "Turn this report into a bug ticket with steps and logs:\n{context}\n{text}",
}

def route(text: str) -> str:
    label = call_model(
        "Classify the message as exactly one of: refund, howto, bug, unsure.\n"
        f"Reply with the label only.\nMessage:\n{text}"
    ).strip().lower()
    if label not in HANDLERS:                 # "unsure" or a malformed reply
        return escalate_to_human(text)        # your own safe fallback
    context = fetch_context(label, text)      # your own lookup per category
    return call_model(HANDLERS[label].format(context=context, text=text))

Skip routing when the categories blur, because a misrouted request gets a confidently wrong specialist answer. The extra cost is one classification call, usually a short one, plus the maintenance of every branch.

To test it, build a labeled set and measure the router alone: accuracy per category and, above all, the confusion between categories. Then test the fallback, because a router without an "unsure" branch has no safe failure mode.

Parallelization: Sectioning and Voting

Parallelization: sectioning runs different subtasks side by side, voting runs the same task several times, and an aggregator combines the results

Parallelization runs LLM calls at the same time and combines the outputs in code. It comes in two forms. Sectioning splits a task into independent subtasks. Voting runs the same task several times and aggregates the results.

Sectioning pays off when subtasks are truly independent and speed matters, or when a single prompt juggling many considerations performs worse than one call per consideration. The post's example is a guardrail: one model instance answers the user while another screens the request, which tends to perform better than one call doing both. OpenAI's Agents SDK builds that shape in by default: it runs guardrails concurrently with the primary agent, which the guide calls optimistic execution, and raises an exception when a guardrail trips. Speed is the other prize. Anthropic's early research agents ran their searches one after another, which the team called painfully slow; letting the lead agent start 3 to 5 subagents at once, each using 3 or more tools in parallel, cut research time by up to 90% for complex queries.

Voting pays off when a wrong answer is expensive. The post's examples are several prompts reviewing code for vulnerabilities, and several prompts judging whether content is inappropriate, with vote thresholds set to balance false positives and false negatives. The best-known measurement of voting is the self-consistency method of Wang and colleagues (2022): sample several reasoning paths and keep the most consistent answer. On arithmetic and commonsense reasoning benchmarks it boosted chain-of-thought prompting on GSM8K (+17.9%), SVAMP (+11.0%), AQuA (+12.2%), StrategyQA (+6.4%) and ARC-challenge (+3.9%).

from concurrent.futures import ThreadPoolExecutor

def answer_with_guardrail(message: str) -> str:            # sectioning
    with ThreadPoolExecutor() as pool:
        answer = pool.submit(call_model, f"Answer the user:\n{message}")
        screen = pool.submit(call_model, f"Is this request inappropriate? Reply YES or NO.\n{message}")
        if screen.result().strip().upper().startswith("YES"):
            answer.cancel()  # a call already running still finishes; use async to stop it at once
            return "Sorry, I can't help with that request."
        return answer.result()

REVIEWS = ["injection (SQL, shell, templates)", "authentication and access control",
           "handling of secrets and personal data"]

def flag_vulnerable(code: str, threshold: int = 1) -> bool:  # voting
    prompts = [f"Review this code only for {r}. Reply YES if you find a flaw, else NO.\n{code}"
               for r in REVIEWS]
    with ThreadPoolExecutor() as pool:
        votes = list(pool.map(call_model, prompts))
    return sum(v.strip().upper().startswith("YES") for v in votes) >= threshold

Neither form helps when the pieces depend on each other. Sectioning lowers wall-clock latency, but total tokens do not fall: N parallel calls cost N calls. Voting is a pure token multiplier that buys confidence with money, and the threshold is where you set the price of a false alarm.

To test it, measure what the extra calls bought. For voting, compare the single-call error rate with the voted error rate on the same labeled set. For sectioning, compare latency and quality with the single-prompt baseline. If the numbers match, remove the parallel branches.

Orchestrator-Workers

Orchestrator-workers: a central LLM decides at run time how many subtasks to create, hands them to workers and synthesises their results

In orchestrator-workers, a central LLM breaks the task down at run time, delegates the pieces to worker LLMs and synthesizes their results. The post separates it from parallelization by one property: the subtasks are not predefined, because the orchestrator decides them from the input.

It fits tasks where you cannot predict the subtasks. In the post's coding example, the number of files to change and the nature of each change depend on the request. Search that gathers and analyzes many sources is the other example, and Anthropic's Research feature, described in a June 2025 engineering post, is that example in production. Asked to identify all the board members of the companies in the Information Technology S&P 500, the multi-agent system found the correct answers by splitting the work among subagents; the single agent failed with slow, sequential searches. Anthropic's context-engineering post gives the shape of the hand-back: a subagent may use tens of thousands of tokens exploring, and returns a condensed summary, often 1,000 to 2,000 tokens.

The hard part is delegation. Anthropic's lead agent first gave short instructions such as "research the semiconductor shortage," and subagents misread the task or repeated each other's searches: one explored the 2021 automotive chip crisis while two others duplicated work on 2025 supply chains. The lesson the team drew is that each subagent needs an objective, an output format, guidance on the tools and sources to use, and clear task boundaries.

import json
from concurrent.futures import ThreadPoolExecutor

MAX_WORKERS = 10   # hard cap in code, whatever the plan asks for

def orchestrate(task: str) -> str:
    plan = call_model(
        "Split this task into the subtasks it needs. Return only a JSON list of objects "
        'with keys "objective", "output_format", "tools", "boundaries".\n' + task
    )
    subtasks = json.loads(plan)[:MAX_WORKERS]
    briefs = [f"Objective: {s['objective']}\nReturn: {s['output_format']}\n"
              f"Use: {s['tools']}\nStay out of: {s['boundaries']}" for s in subtasks]
    with ThreadPoolExecutor() as pool:
        results = list(pool.map(call_model, briefs))
    findings = "\n\n".join(f"[{i}] {r}" for i, r in enumerate(results, 1))
    return call_model(f"Task:\n{task}\nCombine these findings into one answer:\n{findings}")

Its cost is the highest of the workflows. The orchestrator spends tokens planning and synthesizing, each worker spends tokens working, and a vague delegation produces duplicated or missing work. Anthropic reported that agents typically used about four times the tokens of a chat interaction and multi-agent systems about fifteen times, and that in its analysis of the BrowseComp evaluation, token usage by itself explained 80% of the performance variance. The pattern works partly because it spends more, so it pays only where the task is valuable enough. The same post warns that domains where all agents must share the same context, or where agents depend heavily on each other, fit poorly today, and that most coding tasks involve fewer truly parallelizable pieces than research.

To test it, grade the outcome and the delegation separately. Did the final answer meet the rubric, and did each worker receive an objective, a format, tool guidance and boundaries? Count workers per task to catch over-spawning, the failure that opened this guide. For free-form output, Anthropic found that a single LLM judge with one prompt, scoring factual accuracy, citation accuracy, completeness, source quality and tool efficiency from 0.0 to 1.0 with a pass-fail grade, was the most consistent and the best aligned with human judgment, after experimenting with multiple judges. Human testers still caught what the judge missed: early agents consistently chose SEO-optimized content farms over authoritative but lower-ranked sources such as academic PDFs.

Evaluator-Optimizer

Evaluator-optimizer: a generator drafts, an evaluator scores the draft against criteria and returns feedback until it passes or a retry limit is reached

In evaluator-optimizer, one LLM call generates and another evaluates and gives feedback, in a loop. The post names two signs of a good fit: responses demonstrably improve when a human articulates feedback, and the model can articulate comparable feedback. Its examples are literary translation, where a critic catches nuances the first pass missed, and complex search, where the evaluator decides whether further searches are warranted.

The most detailed public account of the pattern is Prithvi Rajasekaran's March 2026 post on harness design at Anthropic. The starting problem was self-evaluation: asked to grade their own work, agents confidently praised it even when the quality was obviously mediocre. Separating generator from evaluator was the lever, with a caveat the post states plainly: the evaluator is still an LLM inclined to be generous to LLM output, but tuning a standalone evaluator to be skeptical proved far more tractable than making a generator critical of its own work.

For frontend design he wrote four criteria (design quality, originality, craft and functionality), weighted the first two, and gave the evaluator a browser through the Playwright MCP so it could click through the live page before scoring. Runs took 5 to 15 iterations and up to four hours. In one, asked for a website for a Dutch art museum, the generator had a polished dark-themed landing page by the ninth iteration; on the tenth it scrapped the approach and rebuilt the site as a 3D room with a checkered floor rendered in CSS perspective and doorway navigation between galleries. Progress was not linear: he regularly preferred a middle iteration over the last.

Out of the box, Claude is a poor QA agent. — Prithvi Rajasekaran, Anthropic Labs, "Harness design for long-running application development," Anthropic, 24 Mar 2026

On full applications the evaluator tested UI features, API endpoints and database states, and each criterion had a hard threshold that failed the sprint if missed. In early runs it found legitimate issues, then talked itself into approving the work anyway; it took several rounds of reading its logs and rewriting its prompt before it graded reasonably. Sprint 3 alone had 27 criteria, and one finding traced a 422 error to a FastAPI route for reordering animation frames that was defined after the /{frame_id} routes, so the framework parsed "reorder" as a frame id. The price was steep. Asked for a 2D retro game maker, a solo agent ran 20 minutes for $9 and the full harness 6 hours for $200, over 20 times the cost; the solo app's game was broken, the harness's was playable.

import json

MAX_ROUNDS, PASS_SCORE = 4, 8

def refine(task: str, criteria: list[str]) -> str:
    rubric = "\n".join(f"- {c}" for c in criteria)
    draft = call_model(f"Task:\n{task}\nIt will be judged on:\n{rubric}")
    for round_no in range(1, MAX_ROUNDS + 1):
        review = json.loads(call_model(
            "You are a strict reviewer. Score the draft 0-10 on each criterion. Return only "
            'JSON: {"scores": {"<criterion>": <int>}, "feedback": "<what to fix>"}\n'
            f"Criteria:\n{rubric}\nDraft:\n{draft}"
        ))
        if min(review["scores"].values()) >= PASS_SCORE:
            return draft                                   # stop: every criterion passes
        if round_no == MAX_ROUNDS:
            break                                          # stop: no revision we won't judge
        draft = call_model(f"Task:\n{task}\nDraft:\n{draft}\n"
                           f"Revise it to address this feedback:\n{review['feedback']}")
    raise RuntimeError(f"no draft passed after {MAX_ROUNDS} rounds; send to a human")

The pattern fails when the evaluator is no better than the generator, or when the criteria are vague, because the loop then polishes noise. Every round costs at least two calls and grows the context, and the stop condition belongs in code: a pass score, a maximum number of rounds, or both. When Opus 4.6 arrived, Rajasekaran cut the per-sprint grading to a single evaluator pass at the end of the run and concluded that the evaluator is worth the cost when the task sits beyond what the current model does reliably on its own. A browser-based music workstation built that way still took 3 hours 50 minutes and $124.70, with three build rounds and three QA rounds; in the first, QA flagged that clips could not be dragged on the timeline and that effect editors were missing.

To test it, plot quality against round number on a held-out set. If round three is no better than round one, cap at one. Where the criteria can be tested by code, prefer the code: a compiler or a test suite is a more honest evaluator than a second model.

Autonomous Agents and the Loop

The agent loop: the model chooses an action, a tool runs it, the environment returns ground truth, and a stop check decides whether to continue

The post's definition of an agent is plain.

They are typically just LLMs using tools based on environmental feedback in a loop. — Erik S. and Barry Zhang, "Building effective agents," Anthropic, 19 Dec 2024

The model picks an action, a tool executes it, and the environment returns a result that the model reads before choosing again. The post stresses that at each step the agent must gain "ground truth" from the environment, such as tool call results or code execution, and recommends stopping conditions such as a maximum number of iterations. OpenAI's guide describes the same loop as a "run" that continues until an exit condition is reached: a tool call, a certain structured output, an error, or a maximum number of turns.

Anthropic's SWE-bench agent shows how little scaffolding a capable loop needs. The upgraded Claude 3.5 Sonnet reached 49% on SWE-bench Verified, beating the previous state of the art of 45%, with a prompt, a Bash tool and an edit tool. The loop kept sampling until the model decided it was finished or exceeded its 200k context length. One example task took 12 steps; some took more than 100 turns, many successful runs took hundreds of turns and more than 100k tokens, and in some the model kept trying until it ran out of context. Those expensive runs are the reason a cap belongs in the code.

Long tasks expose a subtler failure: the agent stops too early. In a post published in November 2025, Anthropic's Justin Young reported that even Opus 4.5, running in a loop across many context windows, fell short of a production-quality web app when given only a high-level prompt such as "build a clone of claude.ai." The agent tried to one-shot the app, ran out of context mid-feature, and later instances looked around, saw progress and declared the job done. The fix was environmental. An initializer agent wrote a list of more than 200 features, all marked failing, in JSON, because the model was less likely to tamper with JSON than with Markdown, and every later session worked on one feature, committed to git and updated a progress file. Browser automation through the Puppeteer MCP, testing as a human user would, dramatically improved results. The limit was perception: Claude could not see browser-native alert modals through the Puppeteer MCP, and features that relied on them stayed buggier.

import json

MAX_STEPS = 30
TOOLS = {"bash": run_in_sandbox, "read_file": read_file, "edit_file": edit_file}  # your own

def run_agent(task: str) -> str:
    transcript = [f"Task: {task}\nTools: {', '.join(TOOLS)}"]
    for _ in range(MAX_STEPS):
        reply = call_model("\n".join(transcript) + '\nReply with JSON only: '
                           '{"tool": "<name>", "args": {...}} or {"done": "<summary>"}')
        try:
            action = json.loads(reply)
            if "done" in action:
                if tests_pass():                  # your test suite: ground truth, not the model's word
                    return action["done"]         # stop: model says done and checks agree
                result = "Not done: the test suite still fails."
            else:
                result = str(TOOLS[action["tool"]](**action["args"]))[:4000]
        except Exception as exc:                  # bad JSON, unknown tool, tool crash
            result = f"ERROR: {exc}"
        transcript.append(f"Action: {reply}\nResult: {result}")
    raise RuntimeError(f"stopped after {MAX_STEPS} steps without passing tests")

Use an agent for open-ended problems where the number of steps cannot be predicted and a fixed path cannot be hardcoded, in an environment you trust. The post warns that autonomy means higher costs and the potential for compounding errors, and recommends extensive testing in sandboxed environments with guardrails.

To test it, run it against tasks with a verifiable end state. Anthropic's January 2026 post on agent evals puts it concretely: a flight-booking agent may say the flight is booked, but the outcome is whether a reservation exists in the environment's SQL database. Measure consistency as well as success. If an agent succeeds 75% of the time per trial, the chance it passes three trials in a row is (0.75)³, about 42%, which matters for customer-facing agents. Audit the eval before trusting it: Opus 4.5 first scored 42% on CORE-Bench until an Anthropic researcher found rigid grading (it penalized "96.12" when expecting "96.124991…"), ambiguous specs and stochastic tasks, and after the fixes and a less constrained scaffold it scored 95%. Isolate the trials too, since in some internal evals Claude gained an unfair advantage by reading the git history of previous trials. Track steps, tool errors, tokens and cost per task alongside the success rate.

Choosing: Start With the Simplest Thing, Then Measure

The decision is a ladder, and each rung needs evidence before you step up.

First, a single call with good instructions, retrieval and examples. If an evaluation set shows it fails, find out how it fails. A formatting failure wants a gate, not an agent.

Second, a workflow, when you can name the steps. Chain fixed stages, route distinct categories, parallelize independent checks. Each is a few lines of ordinary code on a plain API call, and the post suggests starting there rather than with a framework, because frameworks add layers that obscure the underlying prompts and responses and make debugging harder. If you use one, understand the code underneath: the post calls incorrect assumptions about what is under the hood a common source of customer error.

Third, orchestrator-workers or an evaluator loop, when subtasks are unpredictable or quality improves measurably with feedback.

Fourth, an autonomous agent, when the path cannot be predicted at all and the task has a checkable result.

OpenAI's guide, listed on OpenAI's site with a date of 15 January 2026, reaches the same order: maximize a single agent's capabilities first, since more agents add complexity and overhead. It names two multi-agent shapes, a manager that calls specialized agents as tools and decentralized agents handing off to one another, and gives a concrete trigger for splitting: some implementations manage more than 15 well-defined, distinct tools while others struggle with fewer than 10 overlapping ones, so similarity between tools matters more than their number.

Pattern Who owns the control flow Latency Token cost Best test
Prompt chaining Your code, fixed steps Sum of the steps Each step re-reads the last Grade each link alone, earliest first
Routing Your code; the model only labels One short extra call One classification call Per-category accuracy and confusion matrix
Parallelization Your code Slowest branch N calls for N branches or votes Voted vs single-call error on the same set
Orchestrator-workers The model plans, your code runs Planning + slowest worker + synthesis Highest of the workflows Outcome rubric plus delegation quality and worker count
Evaluator-optimizer Model judges, your code caps the rounds Grows with each round At least 2 calls per round Quality by round on a held-out set
Agent loop The model Unbounded without a cap Unbounded without a cap Verifiable end state, pass rate over repeated trials

Tools and the Agent-Computer Interface

The post's second appendix makes the claim most developers underweight: tool definitions deserve as much prompt engineering as the prompts. Its rule of thumb is that the effort teams put into human-computer interfaces should be matched by effort on the agent-computer interface, the ACI.

While building our agent for SWE-bench, we actually spent more time optimizing our tools than the overall prompt. — Erik S. and Barry Zhang, "Building effective agents," Anthropic, 19 Dec 2024

Its example is the one to remember. The model made mistakes with relative file paths after the agent had moved out of the root directory, so the team changed the tool to require absolute paths, and the model then used it flawlessly. The technique is called poka-yoke: change the arguments so the mistake is harder to make. The post also advises formats close to text the model has seen on the internet, no formatting overhead such as counting lines in a diff or escaping code inside JSON, and room for the model to think before it commits. A good definition includes example usage, edge cases, input format requirements and clear boundaries from other tools.

Anthropic's later tool posts are full of small changes with large effects. When it launched Claude's web search tool, Claude was needlessly appending "2025" to its queries, biasing the results; a better tool description fixed it. In the multi-agent research post, a tool-testing agent that used a flawed MCP tool dozens of times and then rewrote its description cut task completion time by 40% for the agents that used the new description. A "concise" response format for a Slack tool returned 72 tokens where the detailed one returned 206. The September 2025 post on writing tools reports that Claude 3.5 Sonnet reached state-of-the-art performance on SWE-bench Verified after precise refinements to tool descriptions.

What Changed in the Two Years Since

Anthropic's later engineering posts keep the patterns and rewrite the practice around them.

Model Context Protocol. Anthropic open-sourced MCP on 25 November 2024, about three weeks before the post. On 9 December 2025 it donated MCP to the Agentic AI Foundation, a directed fund under the Linux Foundation co-founded by Anthropic, Block and OpenAI. Anthropic's announcement reported more than 10,000 active public MCP servers and adoption by ChatGPT, Cursor, Gemini, Microsoft Copilot and Visual Studio Code. For the augmented LLM, MCP is now the common way to attach tools.

Multi-agent research (13 June 2025). Orchestrator-workers went to production. The team started evaluating with about 20 queries representing real usage rather than waiting for a large suite, because early changes had large effects: a prompt tweak might lift success from 30% to 80%.

Writing effective tools (11 September 2025). The ACI advice became a method: prototype, generate realistic evaluation tasks, run them in a simple loop, read the transcripts, and let an agent refactor the tools. It recommends consolidating chained operations into one tool, namespacing similar tools, returning meaningful names instead of opaque identifiers, and capping responses. Claude Code restricts tool responses to 25,000 tokens by default.

Context engineering (29 September 2025). The unit of design moved from the prompt to the whole set of tokens the model sees. The post describes context rot, the loss of recall as context grows, and offers three techniques for long tasks: compaction, structured note-taking outside the window, and sub-agents with clean contexts. Its example of note-taking is Claude playing Pokémon, keeping tallies across thousands of game steps and reading its own notes after context resets.

Claude Agent SDK (29 September 2025). The Claude Code SDK was renamed the Claude Agent SDK, with the loop spelled out as gather context, take action, verify work, repeat. The original post lists the SDK among frameworks; its advice to understand the code beneath still applies.

Code execution with MCP (4 November 2025). Presenting tools as code on a filesystem, so the agent loads only the definitions it needs, cut one example from 150,000 tokens to 2,000, a 98.7% saving.

Evals for agents (9 January 2026). Anthropic describes three grader types, code-based, model-based and human, and separates capability evals from regression evals that should hold a pass rate near 100%. It suggests 20 to 50 simple tasks drawn from real failures as a starting set, and warns that a frontier model can beat the eval as written: Opus 4.5 "failed" a τ2-bench flight-booking task by finding a loophole in the policy that served the user better.

Managed Agents (8 April 2026). The post that the original now points to argues that harnesses encode assumptions about what the model cannot do, and those go stale. Claude Sonnet 4.5 wrapped up tasks prematurely as it sensed its context limit approaching, so the harness added context resets; on Claude Opus 4.5 the behavior was gone and the resets had become dead weight. Anthropic's hosted service separates the session log, the harness and the sandbox. After decoupling the brain from the hands, median time to first token fell roughly 60% and the 95th percentile over 90%.

Common Pitfalls

A loop with no stop condition. Every loop in this guide, whether the evaluator-optimizer cycle or the agent loop, needs a limit in code. Set the maximum before the first run, log which condition ended each run, and alert on runs that hit the cap. OpenAI's guide adds a human trigger: when an agent exceeds its retry or action limits, for example failing to understand a customer's intent after several attempts, escalate to a person.

No ground truth from the environment. An agent that never reads real tool output is guessing, and one that grades itself praises itself. Give it a test run, a query result or a browser session to react to at every step. Where a rule can verify the work, as a linter can, the Agent SDK post calls that excellent rules-based feedback.

Scaling before evaluating. Add agents only after a small evaluation set shows the simpler version failing. A multi-agent system uses about fifteen times the tokens of a chat, so every worker you add should buy a measured gain.

Flaky or wide tools. If the trace shows wrong arguments or repeated calls, fix the tool before the prompt: rename the parameter, narrow it, require the absolute path, cap the response.

Trusting a loop with real side effects. Run new agents in a sandbox with narrow permissions, and keep a human checkpoint before irreversible actions. OpenAI's guide lists canceling user orders, authorizing large refunds and making payments as actions that should trigger human oversight until confidence in the agent grows.

A harness nobody re-examines. Scaffolding added for one model can be dead weight on the next. Remove one component at a time and keep only what still changes the result.

A Starting Checklist

  1. Write ten to twenty real tasks with checkable outcomes before any architecture.
  2. Measure a single call with retrieval and examples.
  3. Add the smallest workflow that fixes the measured failure: a gate, a router or a parallel check.
  4. Move to orchestrator-workers or an evaluator loop only when subtasks are unpredictable or feedback measurably helps.
  5. Give every loop a code-enforced stop condition and log why it stopped.
  6. Spend your tuning time on the tools: names, parameters, examples, response size.
  7. Re-run the evaluation set on every model change and delete harness code the model no longer needs.

Sources

  1. Anthropic Engineering: Building effective agents (19 Dec 2024) anthropic.com
  2. Anthropic Engineering: How we built our multi-agent research system (13 Jun 2025) anthropic.com
  3. Anthropic Engineering: Writing effective tools for AI agents (11 Sep 2025) anthropic.com
  4. Anthropic Engineering: Effective context engineering for AI agents (29 Sep 2025) anthropic.com
  5. Anthropic: Building agents with the Claude Agent SDK (29 Sep 2025) anthropic.com
  6. Anthropic Engineering: Code execution with MCP (4 Nov 2025) anthropic.com
  7. Anthropic Engineering: Effective harnesses for long-running agents (26 Nov 2025) anthropic.com
  8. Anthropic Engineering: Demystifying evals for AI agents (9 Jan 2026) anthropic.com
  9. Anthropic Engineering: Harness design for long-running application development (24 Mar 2026) anthropic.com
  10. Anthropic Engineering: Scaling Managed Agents (8 Apr 2026) anthropic.com
  11. Anthropic Engineering: Raising the bar on SWE-bench Verified with Claude 3.5 Sonnet anthropic.com
  12. Anthropic: Introducing the Model Context Protocol (25 Nov 2024) anthropic.com
  13. Anthropic: Donating MCP to the Agentic AI Foundation (9 Dec 2025) anthropic.com
  14. OpenAI: A practical guide to building agents openai.com
  15. OpenAI: A practical guide to building agents (PDF) cdn.openai.com
  16. Ong et al., RouteLLM: Learning to Route LLMs with Preference Data (arXiv, 2024) arxiv.org
  17. Wang et al., Self-Consistency Improves Chain of Thought Reasoning in Language Models (arXiv, 2022) arxiv.org

Companies in this story

Related stories

Explore

More articles