Workflow patterns
Most working systems are not one autonomous loop. They are a handful of well-understood control-flow patterns, composed deliberately, with memory added only where it earns its cost.
4.1Workflows and agents are different things
The distinction that organises this chapter comes from Anthropic's practitioner guidance. A workflow is a system where models and tools are orchestrated through predefined code paths. An agent is a system where the model dynamically directs its own process and tool usage, deciding at run time what to do next. Both are compound systems and both call models repeatedly, so the difference is not complexity but who holds control of the sequence.
Three consequences follow, and they are what make the distinction worth drawing. Debugging is local in a workflow and global in an agent: when a fixed pipeline produces a wrong answer you can identify the stage that failed, whereas when an agent produces a wrong answer the cause may be a decision made twenty steps earlier. Cost is predictable in a workflow and long-tailed in an agent, because a fixed path has a fixed number of calls while a loop has whatever number the model chooses. And errors compound differently — a workflow's stages fail somewhat independently, while an agent's early mistake conditions everything after it.
The base building block underneath both is the augmented model: a language model given retrieval, tools, and memory. Most of the value in practice comes from getting that augmentation right rather than from the orchestration above it. A model with a well-designed tool interface and good retrieval, called once, outperforms an elaborate multi-stage arrangement built on poor primitives.
The guidance for choosing between them is to find the simplest arrangement that meets the requirement and add complexity only when it demonstrably improves outcomes. Agents trade latency and cost for better performance on open-ended tasks; workflows are preferable when the task decomposes predictably. Many systems described as agents are workflows with a model in one branch, and the description costs nothing until someone tries to debug it.
| WORKFLOW | AGENT | |
|---|---|---|
| Control of sequence | Your code | The model, at run time |
| Debugging | Local to a stage | Global across the trajectory |
| Cost profile | Predictable | Long-tailed |
| Right when | The task decomposes predictably | Steps cannot be enumerated in advance |
4.2The five composable workflow patterns
Five arrangements cover most of what production systems need, and naming the pattern before writing the scaffold saves considerable rework. Each addresses a specific failure and introduces its own.
Prompt chaining decomposes a task into fixed ordered steps, with each call working on the previous output and optional programmatic gates between them. It applies when the decomposition is known in advance and stable. Its characteristic failure is that errors compound down the chain, since nothing downstream can recover information a earlier step discarded.
Routing classifies the input and directs it to a specialised follow-up. It applies when inputs fall into distinct categories that benefit from different handling, and it lets you use a cheap model for common cases and an expensive one for hard cases. Its characteristic failure is coverage at the boundaries: inputs that sit between categories get routed somewhere adequate rather than correct.
Parallelisation has two distinct forms that are frequently conflated. Sectioning splits a task into independent subtasks run concurrently — different aspects of a document reviewed separately. Voting runs the same task several times to get diverse outputs and aggregates them. Sectioning buys latency; voting buys confidence. Both multiply cost, and voting only helps when the errors across runs are somewhat independent.
Orchestrator–workers has a central model decompose the task dynamically and delegate to workers. The boundary against parallelisation is precise: in parallelisation you know the subtasks when you write the code, and in orchestrator–workers you do not. It applies when the decomposition depends on the input. Its characteristic failure is a planner that overruns its budget or decomposes into subtasks that do not reassemble.
Evaluator–optimiser has one model generate and another critique in a loop. It applies when you have clear criteria and iteration measurably helps — literary translation, or search that needs several rounds. Its characteristic failure is an optimiser that learns to satisfy a weak evaluator rather than the underlying goal.
| PATTERN | APPLIES WHEN | CHARACTERISTIC FAILURE |
|---|---|---|
| Prompt chaining | The decomposition is fixed and known | Errors compound down the chain |
| Routing | Inputs fall into distinct categories | Coverage gaps at category boundaries |
| Parallelisation, sectioning | Subtasks are independent | Cost multiplies; results may not compose |
| Parallelisation, voting | Confidence is worth the extra cost | Correlated errors survive the vote |
| Orchestrator–workers | Subtasks are unknown until run time | The planner overruns or misdecomposes |
| Evaluator–optimiser | Clear criteria and iteration helps | The optimiser games a weak evaluator |
4.3Agent loops: ReAct, plan-and-execute, reflection
ReAct is the reference architecture for the agent loop. Its proposal is that a model should generate reasoning traces and actions in an interleaved manner rather than doing all of one and then all of the other. The stated reason is specific: reasoning traces help the model induce, track, and update plans, while actions let it gather information from external sources that the reasoning can then incorporate.
The experimental design isolates that claim by comparing against two ablations — reasoning with no external interaction, and acting with no interleaved reasoning. On interactive decision-making the gains are large: ReAct reaches 71 per cent average success on ALFWorld against 45 per cent for acting alone and 37 per cent for an imitation-learning baseline, using only one or two in-context examples, and about ten points absolute on WebShop.
The knowledge-intensive results deserve more care, because they run the other way. On HotpotQA exact match with a 540-billion-parameter model, ReAct scores 27.4 against chain-of-thought's 29.4. It loses. Grounding constrains the model toward what was retrieved as well as away from what it would have invented, and when retrieval returns something unhelpful the constraint hurts. The strongest results combine the two — around 34 to 35 exact match — rather than choosing between them.
Plan-and-execute inverts the ordering. The model produces a complete plan first and a cheaper executor carries out each step. Expensive reasoning happens once rather than at every step, the plan is a legible artefact a human can inspect before any action is taken, and execution becomes predictable. The cost is that the plan is written against the initial state, so any divergence between what was assumed and what is encountered goes unnoticed unless a replanning trigger exists.
Reflection asks a model to critique its own output and revise. One constraint determines whether it does anything: the critique must be grounded in a signal the generator did not already have. A test result, a type error, a schema violation, a compiler message, a retrieved passage that contradicts a claim. A model asked to critique its own work with no new evidence tends to agree with itself, or to churn — producing changes that differ without improving.
The diagnostic before shipping a reflection loop is straightforward. Take a held-out set, record outputs before and after revision, and measure the win rate of the revision against the original on your real metric. A win rate near fifty per cent means the loop is noise, and the correct response is to remove it or to find a genuine external signal to feed it.
Every loop needs a termination policy with more in it than a step limit. Four conditions are worth implementing together: success, where a verifiable check passes and the task is actually done; budget exhaustion against step, token, and wall-clock caps; stagnation, where consecutive states are similar enough that further iteration is unlikely to help; and oscillation, where the agent cycles between states it has already visited.
| BENCHMARK | BASELINE | REACT | NOTE |
|---|---|---|---|
| ALFWorld success | Act 45%, imitation 37% | 71% | About 34 points absolute |
| WebShop success | Prior methods | +10 points | With one or two examples |
| HotpotQA exact match | Chain-of-thought 29.4 | 27.4 | ReAct alone trails; grounding costs accuracy |
| HotpotQA, combined | Act 25.7 | 34.2 – 35.1 | Best results combine internal and external knowledge |
4.4Skills as a workflow pattern
The patterns above live in orchestration code. Skills move a specific kind of content — procedural knowledge — out of code and out of the system prompt into files that load on demand. A skill is a directory containing a markdown file whose frontmatter carries a name and a description, followed by instructions. The directory may also bundle reference files and executable scripts. The published analogy is an onboarding guide for a new hire: the procedure an experienced person would follow, written down.
What makes this more than a naming convention is progressive disclosure, operating at three levels. At startup only each skill's name and description enter the system prompt, a few dozen tokens each — enough for the model to judge relevance and nothing more. When the model decides a skill applies, it loads the body. Bundled files load at a third level, only when a scenario requires that specific material. Because an agent with a filesystem can read bundled content without pulling all of it into context, that content is effectively unbounded in size.
Behind the design sits a budget argument about a shared finite resource. Suppose a capability's full instructions run two thousand tokens while its name and description run fifty. Thirty capabilities loaded eagerly consume sixty thousand tokens before the user has said anything; under progressive disclosure the same thirty cost fifteen hundred at startup, with the two or three that apply loading on demand. The saving is not only about fitting in the window. Long contexts degrade attention to any individual instruction, so a prompt holding thirty procedures follows each less reliably than one holding the two that are relevant.
Set this against the alternatives for teaching an agent a procedure. Fine-tuning bakes behaviour into weights, which is expensive, static, and needs retraining whenever the procedure changes — the wrong shape of fix when a checklist changes on a Tuesday. Putting everything in the system prompt is the eager approach priced out above. Retrieval over documentation scales better on context but depends on the retriever surfacing the right passage for a query that may not resemble it lexically, and retrieved prose carries no executable component, so a deterministic step must be re-derived in tokens each time.
The relationship between skills and tools is compositional rather than competitive. A tool is a function the model can call, defined by a name, a schema, and an implementation. A skill is knowledge about how to accomplish a task, frequently including which tools to use and in what order. A tool tells the model that a deployment interface exists and what arguments it takes. A skill tells the model that deployment runs a migration check first, then staging, then a smoke test, then promotion, and that a failed smoke test means rolling back rather than retrying.
Choosing between the abstractions is a practical judgement. Reach for a tool when the agent lacks a capability — an external action, or a computation that token generation performs badly. Reach for a skill when it has the capabilities but not your procedure for combining them, particularly when that procedure is long and applies only sometimes. Reach for a subagent when the work needs its own context window. Reach for a better prompt when the guidance is short and applies to every request, since on-demand loading buys nothing for content that is always needed and adds a relevance judgement that can go wrong.
Skills used in production need the discipline code gets. They belong in version control, because a change to a skill changes agent behaviour as surely as a change to a function. They need review, since a skill body is instructions an agent will follow and an unreviewed instruction is an unreviewed code path. They need tests covering both whether the skill fires when it should and whether the resulting behaviour is correct. And a skill that bundles scripts is executable content arriving through a channel that may lack the scrutiny a package manager applies.
The description deserves particular care, because it is the only part the model reads when deciding relevance. A description written as a topic label gives the model nothing to match against a request. One that names the task and its triggering conditions gives concrete signals. Put the key use case first — the listing truncates the combined description text at around fifteen hundred characters, and anything past that is not read at selection time. The two failure modes are complementary and both measurable: too narrow and the skill never fires, too broad and it fires on unrelated requests, consuming context every time.
---
name: deploy-payments
description: Deploys the payments service to production with
migration checks and staged rollout. Use when the user asks
to deploy, release, or ship payments.
---
1. Run scripts/check_migrations.py. Stop if it reports drift.
2. Deploy to staging; wait for the health endpoint to return 200.
3. Run scripts/smoke.sh staging.
4. On pass, promote to production at 10%, then 50%, then 100%.
5. On any smoke failure, roll back. Never retry a failed smoke.SHOULD_FIRE = ["ship payments to prod", "deploy payments"]
SHOULD_NOT = ["deploy the docs site", "what does payments do?"]
def test_skill_selection():
for q in SHOULD_FIRE:
assert "deploy-payments" in skills_invoked(q), q
for q in SHOULD_NOT:
assert "deploy-payments" not in skills_invoked(q), q
# Too narrow: never fires. Too broad: fires on everything.| APPROACH | CONTEXT COST | UPDATE COST | EXECUTABLE STEP |
|---|---|---|---|
| Fine-tuning | None at inference | A full retraining run | No |
| Everything in the prompt | Linear in capabilities, always paid | Edit the prompt | No |
| Retrieval over docs | Only retrieved chunks | Reindex the corpus | No |
| Skills | Description only until invoked | Edit a file and commit | Yes, via bundled scripts |
4.5Memory as a policy stack
Memory is not a storage choice. It is five decisions — what gets written, how it is indexed, when it is read back, when it expires, and how much of the context budget it may occupy — and each is separately evaluable and separately capable of failing.
Four tiers answer different questions. Working memory holds the current task and recent observations, and is bounded by the window. Episodic memory holds what happened in past sessions. Semantic memory holds durable facts and preferences. Procedural memory holds how a task was successfully done before. A system needing all four and implementing one feels subtly broken in a way that is hard to attribute.
The write policy determines everything downstream. A system that writes every observation accumulates a store whose retrieval precision falls as it grows, because the proportion of entries relevant to any given query shrinks. Summarising the trajectory rather than storing the transcript, and tagging each entry with its source and time, costs more at write time and repays it at every subsequent read.
The read policy is where uncapped memory does its damage. Recalled entries compete with task instructions and fresh observations for the model's attention, and that competition is zero-sum within a fixed window. A tier that returns twenty passages when three would do has not helped the turn; it has displaced the instructions that would have made the turn correct. Cap the memory budget as a fraction of context and enforce it, rather than returning whatever the retriever ranked highest.
Expiry is the policy most often omitted, and its absence produces the characteristic failure where a system confidently recalls something the user corrected months ago. Volatile state should decay by recency. Preferences should be superseded on contradiction, with the old entry retired rather than left in place to compete. Hard constraints should not decay at all. Applying one policy uniformly across these fails in one of three directions.
| TIER | HOLDS | READ WHEN |
|---|---|---|
| Working | The current task and recent observations | Every turn, by construction |
| Episodic | What happened in past sessions | The task references prior work |
| Semantic | Durable facts and preferences | A stable claim is needed |
| Procedural | How a task was done successfully | A similar task recurs |
Instrument memory decisions
Take an agent that already works without memory. Add exactly one memory tier. Log every write and every read. Report the change in task success, token cost, and the number of recalls that were never used — that last number is the one that tells you whether the tier earns its place.