techlist.io

Anthropic/Claude

8 posts

Anthropic2026-11-256 min readCurated summary

Migrating our Messages API to Rust

# Migrating the Claude Messages API from Python to Rust Using Production Traffic as the Verifier Anthropic migrated its Messages API from Python to Rust without taking the service offline or freezing feature work. The central problem was verification: Claude could write the new code in about a week, but there was no reliable definition of "correct" for a live system with undocumented customer behavior and a constantly changing Python baseline. The team turned production itself into an oracle, comparing the Rust and Python paths step by step on shadowed traffic, and used agents in layered verification loops to find and fix differences. The result was about 70% less CPU per request and roughly 20% lower median time to first token. ## Why a Full Rewrite - The Messages API began in 2023 as a thin Python request forwarder, but grew to validate, build prompts, tokenize, run safety classifiers, and parse streamed output, with each step adding Python overhead. - API traffic grew roughly 1,800x from early 2024 to fall 2026. - An incremental approach, moving only the output parser to Rust, cut CPU by 8 to 10%, but every token then crossed the Python/Rust boundary three times, adding overhead that offset the gains. - By May 2026, Claude wrote more than 80% of the code Anthropic merged, so generating the rewrite was no longer the bottleneck. Verifying it was. ## Why Existing Tests Were Not Enough - The team had about 700 integration tests, but they were coupled to the Python implementation: they ran the Python API in-process and mocked billing and rate limiting in Python memory. - Porting the tests introduced risk. An audit found more than 100 weakened assertions, so a passing test could hide wrong behavior. - The tests were incomplete. Twenty binary options alone yield over a million combinations, which would take about 12 days to run at one second each for a single model, before varying prompts. - Claude is nondeterministic, and it accepts nearly any prompt, so small prompt deviations often produce no error, just subtly different replies. ## Shadowing Production Traffic - Shadowing ran requests through both versions and compared results, but the usual assumptions did not hold. A request could not safely run twice, since it counted against customer limits and billing. Claude's nondeterminism meant outputs could differ legitimately. - The team ran the model once and replayed its output to the Rust path, so both versions worked from identical model output. They then compared every stage before and after the model call, requiring exact matches. - Customer requests and replies could not be read for privacy reasons, so the team recorded the shape of each difference rather than its content. - Initial results were sobering: the Rust API passed about 98% of its tests in April, yet only about a quarter of production inputs matched. Production also weighted bugs differently, since one common bug could trigger many mismatches. ## Two Techniques for Locating Differences - **Checkpointing:** Both versions pass each request through the same steps (accept or reject, resolve settings, build prompt). Comparing results step by step, and piece by piece within the prompt, pinpointed where the code diverged. - **Fingerprinting:** Each diff was summarized by where the first byte difference occurred and the length difference between versions. Bugs left consistent fingerprints across every request they affected, so errors could be grouped and triaged. - Each diff produced a small record, such as the step, the prompt piece, the first differing byte, and the fingerprint values for each version. ## Verification Loops - A script grouped the hundreds of thousands of near-identical diff records every 10 to 30 minutes by which fields differed. It alerted a coordinating agent only on new record types, which assigned a worker agent to each and opened a Slack thread for engineers to follow. - **Inner loop:** Agents ran in cloud sandboxes with both codebases and fast local checks. An input check built the prompts each version would send, without calling the model, in under a second. An output check ran both versions against a fake model with scripted replies. Agents hypothesized causes, reproduced them, and fixed the Rust until outputs matched, adding a regression test. Earlier, when agents had to wait for PR review and staging deployments, feedback took hours or days. - **Seam:** Fixes passed human PR review before moving to production. Engineers focused on questions verifiers could not answer, such as whether a difference was a bug or an intentional change. - **Outer loop:** Each fix was deployed and compared on shadowed production traffic, using request metadata such as model, caching, tools, and extended thinking to compare like with like. This caught cases the sandbox missed, since the local verifier was not configured exactly like production. - **Memory loop:** Reviewer decisions and agent lessons were saved as notes and rules that later agents read. One rejected shortcut for web search tool descriptions became a documented note, so agents later linked related records to the known bug instead of writing new workarounds. Other lessons became rules, such as porting Python's behavior exactly, and were encoded as tests, lints, and a merge check requiring matching Rust changes for Python edits. ## Lessons Learned - **Verification is the new bottleneck.** When writing code is cheap, the limiting factor is how quickly results can be verified, and ambition can scale as long as Claude has a reliable verifier. - **A production system can serve as a verifier** when formal proofs or tests are insufficient, but it rarely provides a useful failure signal by default. Much of the effort went into building one, through checkpoints and fingerprints. - **Verifiers can be gamed.** The web search shortcut matched outputs but was not a real fix, so human review remained an essential gate. - **Keep loops simple.** Humans defined what counted as correct, and agents chose hypotheses, reproductions, and fixes. Simple loops around strong verifiers scaled as Claude improved. - **Move engineers outward over time.** The team moved from working inside the inner loop, to steering at the seam, to writing the rules and checks agents operate within. The approach let the team build a new, equivalent service alongside the old one, shift traffic gradually, and keep both in step while the original kept changing.

Anthropic2026-11-064 min readCurated summary

The components of agent memory

# Dreaming: How Claude Builds and Maintains Agent Memory Anthropic's post argues that agent memory works best when split into two processes, like the human brain's division between fast encoding and offline consolidation. Claude captures salient events during work, and a separate "dreaming" phase later replays logs, corrects mistakes, and reorganizes memory into representations that future sessions can use. The authors report that dreaming improves memory accuracy, that stronger models judge what is worth saving better when given freedom rather than fixed rules, and that the value of structures like wikis depends on the task. ### Memory as Prediction - Agent memory is defined as knowledge Claude gains from experience and retains across sessions, excluding weight updates, in-context learning, and compaction. - Writing a memory note is a prediction that the pattern will be relevant later. - On the CL-Bench 1.0 database task, models differed in how well they closed a learning loop: recording failures, testing theories, and turning results into rules. Sonnet 4.6 only generated untested guesses, while Opus 5 was the first to consistently write validated rules, answers, and warnings about traps. Opus 5.5 and Sonnet 5.5 also closed the loop, scoring about the same as Opus 5 with memory. ### Judging Salience - In a Pokémon Red evaluation, Sonnet 3.7 wrote 413 memory files across 225 folders, earned one badge, and wasted steps reorganizing outdated records. - Fable 5 wrote nine files in two folders plus a single `global.md` dashboard, and earned four badges. - The better approach stored information that couldn't be read from the screen, such as strategy, plans, and tested rules. One example was a note that varying the timing of inputs helped catch a Magikarp after repeated failures. ### Steering Memory Writes - Telling Claude what memory is for works better than prescribing how to use it. General guidance was enough for Opus 4.7 and Opus 5 to gain a noticeable performance boost. - Fixed rules such as "record only failures" removed much of the benefit for stronger models. - Older models benefit more from steering. Prompting Sonnet 4.6 to read memory and explicitly test its theories nearly doubled its benchmark score. Sonnet 5 reads memory on its own in 9 of 10 cases, compared with fewer than half for Sonnet 4.6. ### Correcting Memory Through Dreaming - Because notes are written from in-session judgment, errors can persist and be trusted later. - In a Mt. Moon navigation case, Claude recorded the Pokémon Center's location incorrectly, leading it to walk off a one-way ledge three times. Dreaming checked the note against the transcript, fixed it, and let Claude reach Cerulean City. The uncorrected run never got there. ### Building New Representations - Wikis are linked collections of pages Claude writes about a subject, acting as a navigable map of its memory. - On a 350,000-file internal corpus, 128 dreaming sessions raised accuracy on 25 questions from 13% to 48%. - Wiki plus search reached 61%, compared with 53% for search alone and 48% for the wiki alone, while saving about 20,000 tokens per question. - On merger questions requiring multi-document reasoning, the wiki raised scores from 73% to 87%. For tasks where a single-document text search was enough, the wiki gave no clear gain. In one case the wiki grew larger than the source documents and abstracted nothing. ### Promoting Notes and Focusing Goals - Dreaming can promote important notes to a small top layer that is loaded into every session. That layer must stay compact, since injected memories consume tokens and incorrect notes propagate. Claude Code's `MEMORY.md` loads only its first 200 lines or 25 KB for this reason. - Instructions for dreaming can be tuned to a task. In a contract-analysis benchmark, concurrent agents overwrote a shared table and the brief covered only 72% of facts. After the instructions were revised to give each contract its own page with verbatim terms, all criteria could be met. - Dreaming across sessions can also fill gaps. A second pass resolved nine broken links and added three pages, including an index. ### Open Questions - When to write memory is a tradeoff. Writing in the moment captures salience at the source but distracts from the task, while dreaming moves the work to the background but may not be immediately accessible. - Keeping memory current requires compute. The authors suggest focusing dreaming on information likely to change, or tuning its cadence based on access frequency. - Transcript search may serve as a foundation, with representations layered on top, but maintaining those representations requires ongoing effort to prevent errors from accumulating. The authors conclude that dreaming lets Claude look backward, organize memory, and correct mistakes, while acknowledging that much about memory system design remains to be learned.

Anthropic2026-04-084 min readCurated summary

Scaling Managed Agents with stable interfaces

Anthropic's Managed Agents is a hosted service that runs long-horizon agents through stable interfaces, so the underlying harness, sandbox, and session implementations can change without breaking callers. The design borrows from operating systems, which kept abstractions like `read()` stable while the hardware beneath them changed. Anthropic separates the agent into a session (a durable event log), a harness (the loop that calls Claude), and a sandbox (where code runs), so each can fail or be replaced independently. The result is faster startup, better reliability, and a stronger security boundary. ## Problems with the Coupled Container Design - The first version put the session, harness, and sandbox in a single container. This was simple and let file edits run as direct syscalls, but it treated the server as a "pet." If a container failed, the session was lost, and unresponsive containers had to be nursed back to health. - Debugging was hard. The WebSocket event stream could not show whether a failure came from the harness, a dropped packet, or a dead container. Engineers had to open a shell in the container, which often held user data. - The harness assumed all resources were in the same container. Connecting to a customer's VPC required peering networks or running the harness in the customer's environment. ## Decoupling the Brain, Hands, and Session - **Hands as tools:** The harness no longer runs in the container. It calls sandboxes like any other tool through `execute(name, input) → string`. If a container dies, the harness returns the error to Claude, which can request a new one with `provision({resources})`. - **Crash recovery:** The harness is also stateless. A new harness calls `wake(sessionId)`, retrieves the log with `getSession(id)`, and resumes from the last event. During the loop, it writes durable records with `emitEvent(id, event)`. - **Credential isolation:** Previously, generated code ran alongside credentials, so a prompt injection could expose tokens. Now tokens never enter the sandbox: - Git repositories are cloned during sandbox initialization with the token wired into the remote, so `push` and `pull` work without the agent seeing the token. - MCP tools are called through a proxy that takes a session-scoped token, fetches the real OAuth credentials from a vault, and makes the external call. The harness never sees credentials. ## The Session as an External Context Object - Long tasks exceed the context window, and common fixes like compaction, memory files, and context trimming are irreversible. Once content is discarded, the agent may later need it and be unable to recover it. - The session log stores the full history outside Claude's context window. The `getEvents()` interface lets the harness read positional slices, such as resuming from the last read position, rewinding to see what led up to an event, or rereading context before an action. - The harness can transform fetched events before they reach Claude's context, for example to improve prompt cache hit rates. Anthropic keeps storage in the session and context management in the harness, since future models may need different context strategies. ## Scaling to Many Brains and Many Hands - **Faster startup:** Previously, every session waited for a container to provision and repository to clone, even if it never used one. Now containers are provisioned only when a tool call requires them. Inference starts as soon as pending events are pulled from the log. This cut p50 time-to-first-token by about 60% and p95 by over 90%. - **Many brains:** Stateless harnesses can be started on demand and connected to hands only when needed. - **Many hands:** A brain can use multiple execution environments. Since each hand is just a tool with a name and input, the harness does not need to know whether the sandbox is a container, a phone, or an emulator. Brains can also pass hands to one another. ## Conclusion Managed Agents is a meta-harness: it does not prescribe a single harness design. Its interfaces are opinionated about the surrounding components, namely state (the session), computation (the sandbox), and scaling to many brains and hands, but not about the harness itself. This lets it support Claude Code, task-specific harnesses, and future designs without redesigning the system.

Anthropic2026-03-245 min readCurated summary

Harness design for long-running apps

# Anthropic's Three-Agent Harness for Long-Running Autonomous Coding and Frontend Design Prithvi Rajasekaran of Anthropic's Labs team describes a multi-agent approach that improves Claude's output on two hard problems: subjective frontend design and long autonomous full-stack coding. The core idea is to separate the agent doing the work from an evaluator agent that judges it, borrowing the generator-discriminator structure of GANs. A standalone evaluator, tuned to be skeptical, gives the generator concrete feedback to iterate against, which self-evaluation alone cannot provide. The post also shows that harness components should be continually stress-tested as models improve, since some scaffolding becomes unnecessary over time. ## Why Naive Implementations Fall Short - Models lose coherence on long tasks as the context window fills, and some (notably Claude Sonnet 4.5) show "context anxiety," wrapping up work early as they near what they believe is their limit. - Context resets, which clear the window and hand off state through a structured artifact, address this more fully than compaction, which summarizes history in place and leaves the anxiety intact. Resets add orchestration complexity, token overhead, and latency. - Agents reliably overpraise their own work, especially on subjective tasks like design where no binary test exists. - A separate evaluator is still an LLM and tends to be lenient, but tuning a standalone evaluator to be skeptical is far more tractable than making a generator self-critical. ## Making Subjective Design Quality Gradable - The team wrote four grading criteria given to both generator and evaluator: design quality, originality, craft, and functionality. Design quality and originality were weighted more heavily, since Claude already handled craft and functionality well by default. The originality criterion explicitly penalized "AI slop" patterns such as purple gradients over white cards. - The evaluator was calibrated with few-shot examples and detailed score breakdowns to align with the author's taste and reduce score drift. - The loop ran on the Claude Agent SDK. The evaluator used the Playwright MCP to navigate the live page, screenshot it, score each criterion, and write a critique. The generator chose each iteration to either refine its direction or pivot aesthetically. - Runs took 5 to 15 iterations and up to four hours. Scores generally improved before plateauing, and the criteria wording itself steered the output: even the first iteration beat a no-prompt baseline. - In one run, a Dutch museum site moved on iteration ten from a polished dark landing page to a spatial 3D gallery built with CSS perspective and doorway-based navigation. ## Scaling to Full-Stack Coding - **Architecture:** Three agents. A planner expands a 1–4 sentence prompt into a product spec, staying high-level to avoid cascading errors from wrong technical details. A generator works in sprints on a React, Vite, FastAPI, and SQLite (later PostgreSQL) stack and uses git. An evaluator tests the running app with Playwright. - **Sprint contracts:** Before each sprint, generator and evaluator negotiate what "done" means and how it will be tested. Communication happens through files. - **Evaluation:** Each criterion has a hard threshold. Failing any one fails the sprint and returns detailed feedback. Sprint 3 alone had 27 criteria for the level editor. - **Tuning the QA agent:** Out of the box, Claude was a poor QA agent. It found real issues, then talked itself into approving them, and tested superficially. The team tuned the evaluator's prompt over several rounds by comparing its judgments to their own. - **Cost comparison (retro game maker, Opus 4.5):** A solo run took 20 minutes and $9 but produced an app where the central feature did not work. The full harness took 6 hours and $200, producing a richer app with a functional play mode, though with physics and level-design rough edges. ## Simplifying the Harness - Every harness component encodes an assumption about what the model cannot do alone, and those assumptions go stale as models improve. The author follows the principle from "Building Effective Agents": use the simplest solution, adding complexity only when needed. - A first attempt to cut the harness radically failed to match the original performance and made it unclear which pieces were load-bearing. The team then removed one component at a time to measure its impact. - **Sprint construct removed:** Opus 4.6 could sustain longer coherent work, so the sprint decomposition was dropped. The planner stayed, since without it the generator under-scoped. The evaluator moved to a single pass at the end. - **Evaluator as a conditional:** The evaluator is worth its cost only for tasks beyond what the current model reliably does alone. On 4.6 that boundary moved outward, so the evaluator was unnecessary for some parts of a build but still helped at the edges. - The team also added prompting so the generator built proper tool-driven agents inside the apps, since this knowledge was thinly covered in training data. ## Results and Limits - A Digital Audio Workstation built with the simplified V2 harness took about 4 hours and $124.70. The build ran coherently for over two hours without sprints. - The QA agent still caught real gaps across rounds: clips could not be dragged, instrument and effect UIs were display-only, audio recording was a stub, and the EQ was numeric rather than graphical. - The final app had a working arrangement view, mixer, and transport, and the agent could compose a short snippet end to end through tools. The author acknowledges it is far from professional-grade, and that Claude cannot hear, which limits musical judgment in QA. ## Takeaways The author argues that as models improve, some scaffolding becomes obsolete, but the space of useful harness designs does not shrink; it shifts toward new combinations. Practical advice includes testing against the target model, reading its traces on realistic problems, decomposing complex tasks into specialized agents where useful, and re-examining the harness whenever a new model ships by removing components that no longer carry weight and adding new ones that unlock capabilities.

Anthropic2025-06-135 min readCurated summary

How we built our multi-agent research system

Anthropic's engineering team describes how they built the multi-agent Research feature for Claude, where a lead agent plans a query and spawns parallel subagents that search simultaneously. Their internal evaluation found the multi-agent setup (Claude Opus 4 lead, Sonnet 4 subagents) outperformed a single Opus 4 agent by 90.2%, mainly because it spends more tokens on hard, parallelizable problems. The post argues that this gain comes with roughly 15× the token cost of chat, so it only suits high-value, breadth-first tasks. Moving these systems to production, they add, is much harder than building a prototype. ## Why Multi-Agent Systems Help Research - Research is open-ended and path-dependent, so the steps can't be hardcoded in advance, and a linear pipeline can't handle it. - Subagents compress information by working in parallel, each with its own context window, and returning only the most important findings to the lead agent. - Token usage explained about 80% of performance variance on the BrowseComp evaluation, with tool calls and model choice explaining most of the rest, so distributing work across agents adds reasoning capacity. - Agents use about 4× the tokens of chat, and multi-agent systems about 15×, so they fit only tasks valuable enough to justify the cost. - Coding tasks, which have fewer parallelizable subtasks and need shared context, are a poor fit today. ## Architecture: Orchestrator-Worker Pattern - The lead agent analyzes the query, develops a strategy, and spawns subagents that iteratively search and return condensed results. - Unlike static RAG, which fetches chunks similar to the query once, this design runs multi-step searches that adapt to new findings. ## Prompt Engineering Principles - **Simulate the agents:** Running the exact prompts and tools step by step revealed failure modes such as agents continuing after they already had enough results, using overly verbose queries, or picking the wrong tools. - **Delegate with detail:** Vague instructions caused duplicated work and gaps. Each subagent needs an objective, an output format, tool guidance, and clear task boundaries. - **Scale effort to complexity:** Simple fact-finding uses 1 agent with 3–10 tool calls, comparisons use 2–4 subagents with 10–15 calls each, and complex research uses more than 10 subagents. Without these rules, early versions overinvested in simple queries. - **Design tools deliberately:** Each tool needs a distinct purpose and clear description, and agents should examine available tools first and match tool choice to user intent. - **Let Claude improve its own tools:** A tool-testing agent that rewrote flawed MCP tool descriptions reduced task completion time by 40%. - **Start wide, then narrow:** Agents should begin with short, broad queries and refine from there, instead of starting with long, specific ones. - **Use extended thinking as a scratchpad:** The lead agent plans and sets subagent roles, and subagents evaluate tool results with interleaved thinking. - **Parallelize:** The lead agent spins up 3–5 subagents in parallel, and subagents use 3+ tools in parallel, cutting research time by up to 90% on complex queries. ## Evaluating Multi-Agent Systems - Agents can reach the same correct answer by different valid paths, so evaluations should judge outcomes and reasonable process rather than fixed steps. - Start with about 20 representative queries. Early changes have large effects, so small samples reveal them. - An LLM judge using a single prompt that outputs 0.0–1.0 scores and a pass/fail grade agreed best with human judgment. It scores factual accuracy, citation accuracy, completeness, source quality, and tool efficiency. - Human testing caught problems automation missed, such as early agents favoring SEO-optimized content farms over authoritative academic PDFs or personal blogs. Adding source-quality heuristics fixed this. ## Production Reliability Challenges - **Stateful errors compound:** Agents run for long periods, so the system checkpoints and resumes from the failure point rather than restarting, combining model adaptability with retry logic. - **Debugging is hard:** Because agents are non-deterministic, the team added full production tracing and monitors decision patterns, without reading individual conversation contents, to protect privacy. - **Deployment is delicate:** Agents may be mid-process during updates, so rainbow deployments gradually shift traffic between old and new versions while both run. - **Synchronous execution is a bottleneck:** Lead agents wait for each subagent batch to finish and can't steer subagents mid-task. Asynchronous execution would add parallelism but complicates result coordination, state consistency, and error propagation. ## Conclusion The authors conclude that multi-agent research systems can run reliably at scale, but only with careful engineering, extensive testing, detailed prompt and tool design, and close collaboration across research, product, and engineering. Users reported finding business opportunities, navigating healthcare options, fixing technical bugs, and saving days of research work. ## Appendix Tips - **End-state evaluation:** For agents that change persistent state, judge whether the final state is correct, using checkpoints for complex workflows. - **Long-horizon memory:** Agents summarize completed phases, store essential information externally, and hand off to fresh subagents when context limits approach. - **Filesystem artifacts:** Subagents store outputs such as code, reports, or data visualizations in external systems and pass lightweight references to the coordinator, which avoids information loss and reduces token overhead.

Anthropic2025-03-203 min readCurated summary

The "think" tool for complex tool use

# The "Think" Tool for Claude Agents Anthropic found that giving Claude a dedicated "think" tool, a scratchpad it can write to mid-response, improves agentic tool use. The tool helps with following policies, making consistent decisions, and handling multi-step problems, and it requires little implementation effort. The post notes that extended thinking now covers most of these cases, so the dedicated tool is recommended mainly for specific scenarios. The benefits come from giving Claude room to reason about new information gathered from tool outputs, not from extended reasoning before it acts. ## How the "Think" Tool Differs from Extended Thinking - Extended thinking happens before Claude generates a response and plans its approach in advance. - The "think" tool happens during response generation, letting Claude pause after receiving tool results to check whether it has what it needs to continue. - The tool suits complex tool calls, long tool-call chains, policy-heavy environments, and sequential decisions where mistakes are costly. - Extended thinking suits simpler tool use, non-sequential calls, and tasks like coding, math, and physics that don't involve tools. - The tool is defined with a single `thought` string input. It doesn't obtain new information or change any state. It only logs the thought. ## Results on τ-Bench τ-bench simulates customer service conversations and measures pass^k, the probability that all k trials of a task succeed, which captures consistency. - **Airline domain (the hardest):** The "think" tool with an optimized prompt reached 0.570 pass^1, versus 0.370 for the baseline, a 54% relative improvement. The prompt included worked examples of how to reason about policies. The tool alone and extended thinking performed similarly, both better than baseline but well behind the combined approach. - **Retail domain (easier):** The "think" tool alone reached 0.812 pass^1, versus 0.783 for the baseline, with no extra prompting needed. - Gains held up across k=1 to k=5, which points to better handling of edge cases and more consistent policy adherence. ## Results on SWE-Bench - A "think" tool with a description tailored to software debugging was added to the SWE-bench setup for Claude 3.7 Sonnet, which contributed to a state-of-the-art score of 0.623. - The isolated effect was a 1.6% average improvement, statistically significant (Welch's t-test, p < .001). ## Implementation Guidance - **Use it for:** tool output analysis that may require backtracking, policy-heavy environments requiring compliance checks, and sequential decisions where each step depends on the last. - **Skip it for:** single or parallel tool calls, and simple instruction following where default behavior is already adequate. - **Prompting:** Domain-specific examples help the most on difficult tasks. Examples cover the expected level of detail, how to break instructions into steps, decision trees, and checks for missing information. - **Placement:** For long or complex guidance, put instructions in the system prompt rather than the tool description. - **Costs and risks:** The tool adds prompt length and output tokens. It doesn't change external behavior unless Claude calls it, so it's low-risk to add. The post concludes that the "think" tool is not a universal fix, but for the right workloads it offers meaningful reliability gains with minimal implementation work. The authors also note that the results generalize to Claude 3.5 Sonnet (New).

Anthropic2024-12-196 min readCurated summary

Building effective AI agents

This post, from Anthropic, argues that the most effective LLM agent systems are built from simple, composable patterns rather than complex frameworks. It distinguishes predefined workflows from autonomous agents and advises starting with the simplest solution, adding complexity only when measured results justify it. The authors cover five workflow patterns, when to use full agents, and how to design tools for them. ### Workflows Versus Agents - Workflows orchestrate LLMs and tools through predefined code paths. - Agents let the LLM dynamically direct its own processes and tool usage, keeping control over how it accomplishes tasks. - Both are grouped as "agentic systems," but the distinction is architecturally important. ### When to Use Agents and Frameworks - Agentic systems often trade latency and cost for better task performance, so the tradeoff must be justified. - Workflows suit well-defined tasks that need predictability, while agents suit open-ended problems that need flexibility and model-driven decisions at scale. - Many applications only need a single LLM call optimized with retrieval and in-context examples. - Frameworks such as the Claude Agent SDK, Strands Agents SDK, Rivet, and Vellum simplify setup, but their abstractions can hide prompts and responses, making debugging harder and tempting developers to add unnecessary complexity. - The authors recommend starting with LLM APIs directly, and understanding the framework's underlying code if you do use one. ### The Augmented LLM Building Block - The foundation of agentic systems is an LLM enhanced with retrieval, tools, and memory, which it can use actively by generating search queries, selecting tools, and deciding what to retain. - Key considerations are tailoring these capabilities to the use case and exposing them through a clear, well-documented interface. - The Model Context Protocol is one way to integrate third-party tools using a simple client implementation. ### Core Workflow Patterns - **Prompt chaining:** Decomposes a task into sequential LLM calls, with optional programmatic "gates" between steps. It trades latency for accuracy. Examples include writing marketing copy and then translating it, or drafting an outline, checking it against criteria, and then writing the document. - **Routing:** Classifies an input and sends it to a specialized follow-up task, which separates concerns and allows specialized prompts. Examples include directing customer service queries to different processes, or sending simple questions to a smaller model like Claude Haiku 4.5 and hard ones to Claude Sonnet 4.5. - **Parallelization:** Runs LLM calls simultaneously and aggregates the outputs programmatically, in two variations: - *Sectioning* splits a task into independent subtasks, such as running a guardrail model alongside the core response model, or evaluating different aspects of a model's output separately. - *Voting* runs the same task multiple times for diverse outputs, such as several prompts reviewing code for vulnerabilities. - **Orchestrator-workers:** A central LLM dynamically breaks down a task, delegates subtasks to worker LLMs, and synthesizes the results. Unlike parallelization, subtasks aren't predefined. This suits coding tasks where the required file changes depend on the input, and multi-source search. - **Evaluator-optimizer:** One LLM generates a response while another evaluates it and provides feedback in a loop. This works best when evaluation criteria are clear and iterative refinement measurably helps, as with literary translation or multi-round search. ### Agents in Production - Agents begin with a command or interactive discussion with the user, then plan and operate independently, checking "ground truth" from the environment, such as tool results or code execution, at each step. - They can pause for human feedback at checkpoints or blockers, and should include stopping conditions, such as a maximum number of iterations. - Structurally, agents are often just LLMs using tools in a loop, so the design of toolsets and their documentation is critical. - Agents suit open-ended problems where the number of steps is unpredictable, but their autonomy raises costs and the risk of compounding errors, so extensive sandbox testing and guardrails are essential. - Anthropic's own examples include a coding agent for SWE-bench tasks and the "computer use" reference implementation. ### Combining Patterns and Guiding Principles - The patterns are not prescriptive. They are starting points to shape and combine for specific use cases. - Success depends on measuring performance and iterating. Added complexity should only be kept when it demonstrably improves outcomes. - The authors suggest three principles for agents: keep the design simple, make planning steps transparent, and carefully craft the agent-computer interface (ACI) through thorough tool documentation and testing. ### Agents in Practice - **Customer support:** Suits agents because conversations need external data (customer records, order history, knowledge base articles), actions like refunds can be handled programmatically, and success is measurable through user-defined resolutions. Some companies charge only for successful resolutions. - **Coding agents:** Suit agents because solutions can be verified with automated tests, agents can iterate on test feedback, and output quality can be measured objectively. Anthropic's agent can solve real GitHub issues from SWE-bench Verified based on the pull request description alone, though human review remains essential. ### Prompt Engineering Your Tools - Tool definitions deserve as much prompt-engineering effort as the main prompts, since Claude invokes tools through structured tool-use blocks in the API. - Some formats are much harder for LLMs to produce than others. For example, diffs require counting lines in chunk headers before writing code, and code inside JSON requires escaping newlines and quotes. - Format guidelines: - Give the model enough tokens to reason before committing to an output. - Stick to formats common in internet text. - Avoid formatting overhead like line counting or string escaping. - Designing the agent-computer interface deserves as much care as the human-computer interface. Put yourself in the model's shoes, write documentation like a docstring for a junior developer (with examples, edge cases, and input requirements), test the tools on many inputs, and "poka-yoke" them so mistakes are harder to make. - In the SWE-bench agent, the team spent more time on tools than on the prompt. Requiring absolute file paths eliminated errors that occurred after the agent changed directories. ### Practical Takeaway Start with the simplest prompts and direct API calls, and measure results carefully. Add workflows or autonomous agents only when simpler approaches fall short, and invest heavily in tool design and testing, since they largely determine whether an agent succeeds.

Anthropic2024-09-194 min readCurated summary

Contextual retrieval in AI systems

# Contextual Retrieval: Improving RAG Accuracy by Adding Chunk Context The post argues that traditional RAG systems lose critical information when documents are split into chunks, causing retrieval failures. Its proposed fix, Contextual Retrieval, prepends chunk-specific explanatory context to each chunk before embedding and BM25 indexing. Combined with BM25 and reranking, this cuts the top-20-chunk retrieval failure rate from 5.7% to 1.9%, a 67% reduction. ## When Simple Prompting Is Enough - If the knowledge base is under about 200,000 tokens (roughly 500 pages), it can be placed directly in the prompt without RAG. - Prompt caching makes this approach faster and cheaper, with latency reduced by more than 2x and costs by up to 90%. - Larger knowledge bases still need a retrieval system. ## How Traditional RAG Works and Where It Falls Short - Documents are split into chunks of a few hundred tokens, converted to vector embeddings, and stored in a vector database for semantic search. - Embeddings can miss exact matches, such as an error code like "TS-999." BM25, a lexical ranking function built on TF-IDF, handles these well. - Combining embeddings and BM25 with rank fusion improves results, but chunks often lose context. A chunk like "The company's revenue grew by 3% over the previous quarter" doesn't name the company or the time period. ## Contextual Embeddings and Contextual BM25 - Each chunk is prepended with a short, 50–100 token context situating it within the whole document before embedding and BM25 indexing. - Claude (Claude 3 Haiku in the post) generates this context from the full document and the chunk, using a prompt that asks for a succinct explanation to improve search retrieval. - Manually annotating millions of chunks is impractical, so the model automates the process. - Other context-adding approaches, such as generic document summaries, hypothetical document embeddings, and summary-based indexing, showed limited gains in the authors' tests. ## Keeping Costs Down with Prompt Caching - The full document is cached once and referenced for every chunk, so it isn't resent each time. - With 800-token chunks, 8k-token documents, and 100 tokens of context per chunk, the one-time cost is about $1.02 per million document tokens. ## Experimental Results - Tests covered codebases, fiction, ArXiv papers, and science papers, across several embedding models and retrieval strategies. - Using Gemini Text 004 and top-20 retrieval, contextual embeddings alone reduced the failure rate by 35% (5.7% → 3.7%). - Contextual embeddings combined with contextual BM25 reduced it by 49% (5.7% → 2.9%). - Adding reranking brought the failure rate down to 1.9%, a 67% reduction. ## Implementation Considerations - Chunk size, boundaries, and overlap all affect retrieval performance. - Gemini and Voyage embeddings performed best among the models tested, though contextualization helped every model. - Custom contextualizer prompts, such as ones that include a glossary of domain terms, may improve results further. - Passing 20 chunks to the model outperformed 5 or 10, though more chunks can also distract the model. - Evaluate on your own use case, and consider clearly separating the context from the chunk text during response generation. ## Reranking - Initial retrieval fetches a larger candidate set (the authors used the top 150). - A reranking model, such as Cohere's, scores each chunk against the query, and the top 20 go to the generator. - Reranking improves accuracy and lowers the cost and latency of generation, but it adds a small amount of latency itself. The number of chunks to rerank is a trade-off between accuracy and speed. ## Practical Takeaway The authors recommend combining contextual embeddings (using Voyage or Gemini), contextual BM25, reranking, and passing the top 20 chunks to the model. They provide a cookbook for implementing the approach.