AI Wiki中文/EN

Agent workflows: fixed code paths around model calls

智能体工作流

Treat prompt chaining, routing, parallel voting, orchestrator-workers and evaluator-optimizer loops as reliability arithmetic; simulate each with seeded step success rates and compare them with an open-ended agent loop.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Who decides the next step: your code or the model?

A support team wants to answer incoming tickets with a language model. One design is a single prompt: “read the ticket and reply”. Another classifies the ticket first and sends billing questions, technical questions and account questions to separate prompts. A third lets the model decide, step by step, which tools to call and when it is done. All three are called “agents” in casual use, but they behave differently under failure, cost different amounts, and need different tests.

Anthropic’s post of December 2024, “Building effective agents”, draws a line that this article uses throughout. Workflows are systems in which language models and tools are orchestrated through predefined code paths; agents are systems in which the model dynamically directs its own process and tool use. Definitions The post recommends finding the simplest solution first, noting that agentic systems often trade latency and cost for task performance, and that for many applications a single optimized call with retrieval and examples is enough. When to use agents

The post then names five workflow patterns: prompt chaining, routing, parallelization (sectioning and voting), orchestrator-workers, and evaluator-optimizer. Workflow patterns This article treats each as a small piece of reliability arithmetic: given how often each model call succeeds, how does the structure change end-to-end success, the rate of undetected errors and the number of calls? The comparison baseline is the non-agentic option the post itself recommends trying first: one well-built prompt.

Five patterns as reliability formulas

Throughout, a “call” is one model invocation, pp is the probability that a call produces a correct output for its step, and errors are assumed independent unless stated otherwise. That assumption is the weakest part of every formula below, and the program tests one way it fails.

Prompt chaining splits a task into fixed sequential steps, each consuming the previous output; the post suggests adding programmatic checks, called gates, between steps, and frames the pattern as trading latency for accuracy by making each call easier. Prompt chaining Without gates, a chain of nn steps succeeds only if every step does. Suppose a gate detects a bad output with probability rr (its recall) and the workflow retries the step once. Then:

Pchain=∏i=1npi,pi′=pi+(1−pi) r pi(one retry after a caught error).P_{\text{chain}}=\prod_{i=1}^{n}p_i,\qquad p_i'=p_i+(1-p_i)\,r\,p_i\quad\text{(one retry after a caught error)}.

Gates also change what failure looks like. If the workflow stops at the first caught error instead of retrying, the fraction of items that finish with an undetected error is the probability of never being caught minus the probability of being fully correct:

Psilent=(p+(1−p)(1−r))n−pn.P_{\text{silent}}=\bigl(p+(1-p)(1-r)\bigr)^{n}-p^{n}.

Routing classifies an input and sends it to a specialized follow-up; the post says it works when categories are distinct and classification is accurate. Routing Let the classifier have accuracy aa, a specialized handler succeed with probability ss on its own category and mm on a misrouted one, and a single general prompt succeed with probability gg. Routing helps only if:

a s+(1−a) m>g⟺a>g−ms−m.a\,s+(1-a)\,m>g\quad\Longleftrightarrow\quad a>\frac{g-m}{s-m}.

Parallelization runs calls simultaneously and aggregates them in code. Sectioning gives independent subtasks to separate calls; voting runs the same task several times. Parallelization For a binary decision with nn independent voters, each correct with probability pp, majority voting is correct with probability:

Pmaj=∑k>n/2(nk)pk(1−p)n−k.P_{\text{maj}}=\sum_{k>n/2}\binom{n}{k}p^{k}(1-p)^{n-k}.

Independence is essential. If a fraction hh of items is “hard” for every voter at once, no number of voters can do better than 1−h1-h on the whole set.

Orchestrator-workers uses a central model to break the task down at run time, delegate pieces to worker calls and synthesize results. The post distinguishes it from sectioning by flexibility: subtasks are not predefined but decided from the input, as in code changes whose number of files depends on the task. Orchestrator-workers

Evaluator-optimizer alternates a generator call with an evaluator call that gives feedback, in a loop; the post lists two signs of fit: responses improve demonstrably when a human articulates feedback, and a model can provide that kind of feedback. Evaluator-optimizer If the evaluator wrongly passes a bad response with probability ff, the loop’s quality is capped below 1 however many rounds it runs. Starting from a bad response, each round either stops wrongly (probability ff) or produces a fix (probability (1−f) pfix(1-f)\,p_{\text{fix}}), which the evaluator then accepts; summing the geometric series gives the eventual fix probability:

P(eventually fixed∣bad start)=(1−f) pfix1−(1−f)(1−pfix).P(\text{eventually fixed}\mid\text{bad start})=\frac{(1-f)\,p_{\text{fix}}}{1-(1-f)(1-p_{\text{fix}})}.

Finally, an agent in the post’s sense is a model using tools in a loop on environmental feedback, ideally getting “ground truth” from tool results at each step, with stopping conditions such as a maximum number of iterations. The post warns that autonomy brings higher cost and compounding errors and recommends sandboxed testing and guardrails. Agents

The cookbook notebooks that accompany the post implement chaining, parallelization and routing in a few lines each and label them sample implementations, not production code. Notebook header Two details in those samples show where workflow engineering effort goes. The router reads the model’s chosen label from an XML tag and indexes a dictionary with it; a label outside the dictionary, or a missing tag (the extraction helper returns an empty string), has no fallback path. Route function The evaluator-optimizer loop repeats until the evaluator outputs exactly “PASS”, with no iteration limit. Loop function Neither is a defect for a teaching notebook; both are exactly the code a production workflow must add.

Simulating the patterns with seeded step outcomes

The program replaces every model call with a seeded random event that succeeds with an assumed probability. It calls no model and no network; it measures only how structure combines step reliabilities and how many calls each structure spends. All probabilities are arbitrary illustrative settings, not measurements of any model, and none comes from either source (the post reports no such rates):

  • chain: four steps with p=0.95p=0.95; gates with recall r=0.8r=0.8, either stopping or retrying once;
  • routing: three categories, specialized handlers s=0.95s=0.95, misrouted m=0.5m=0.5, general prompt g=0.80g=0.80; classifier accuracy 0.6, 0.7 and 0.9; and a variant where 2% of classifier outputs are labels outside the route table and there is no fallback;
  • voting: five voters with p=0.7p=0.7, independent or with 20% of items hard for all voters;
  • decomposition: tasks need 1 to 6 subtasks uniformly; a fixed workflow always runs three workers plus one synthesis call; an orchestrator spends one planning call, underestimates the count by one with probability 0.1, then runs one worker per planned subtask plus synthesis; an agent loop does one subtask per call and decides after each whether it is done, stopping too early with probability 0.05 per call and capped at 8 calls; each subtask call succeeds with probability 0.95;
  • evaluator-optimizer: first draft good with probability 0.3, each fix succeeds with probability 0.4, evaluator false-pass rate f=0.1f=0.1, round limits 0, 1, 3 and 10.
"""Original synthetic workflow study. No language model or network is called.

Every 'model call' is a seeded random event with an assumed success rate, so the
program measures how workflow structure combines step reliabilities and call counts.
"""
import math
import random


def chain(rng, steps=4, p=0.95, gate_recall=0.0, retries=0):
    calls, ok = 0, True
    for _ in range(steps):
        for attempt in range(retries + 1):
            calls += 1
            good = rng.random() < p
            caught = (not good) and rng.random() < gate_recall
            if good or not caught or attempt == retries:
                break
        if not good:
            ok = False
            if caught:
                return False, calls, True
    return ok, calls, False


def route(rng, accuracy, routes=3, special=0.95, mismatch=0.5, unknown_rate=0.0, fallback=True):
    true = rng.randrange(routes)
    if rng.random() < unknown_rate:
        if not fallback:
            return None, 1
        return rng.random() < 0.80, 2
    label = true if rng.random() < accuracy else (true + rng.randrange(1, routes)) % routes
    return rng.random() < (special if label == true else mismatch), 2


def vote(rng, voters=5, p=0.7, shared=0.0):
    hard = rng.random() < shared
    yes = sum((rng.random() < p) and not hard for _ in range(voters))
    return yes > voters // 2


def evaluator_loop(rng, max_rounds, p_fix=0.4, false_pass=0.1, p0=0.3):
    good, calls = rng.random() < p0, 1
    for _ in range(max_rounds):
        calls += 1
        verdict = good or rng.random() < false_pass
        if verdict:
            return good, calls
        calls += 1
        good = rng.random() < p_fix
    return good, calls


def decompose(rng, mode, p=0.95, fixed=3, under=0.1, early_stop=0.05, max_iter=8):
    need = rng.randint(1, 6)
    if mode == 'fixed':
        planned, calls = fixed, fixed + 1
    elif mode == 'orchestrator':
        planned = need - 1 if rng.random() < under else need
        calls = planned + 2
    else:
        planned, calls = 0, 0
        while planned < max_iter:
            calls += 1
            planned += 1
            if planned >= need or rng.random() < early_stop:
                break
    done = min(planned, need) == need
    return done and all(rng.random() < p for _ in range(min(planned, need))), calls


def rate(results):
    return sum(results) / len(results)


def main(seed=0, n=20000):
    rng = random.Random(seed)
    print('items per experiment', n, 'seed', seed)
    for label, recall, retries in [('no gate', 0.0, 0), ('gate stops', 0.8, 0), ('gate + 1 retry', 0.8, 1)]:
        runs = [chain(rng, gate_recall=recall, retries=retries) for _ in range(n)]
        ok, flagged = rate([r[0] for r in runs]), rate([r[2] for r in runs])
        print('chain %-15s success %.4f  flagged %.4f  silent %.4f  calls/item %.3f' % (
            label, ok, flagged, 1 - ok - flagged, sum(r[1] for r in runs) / n))
    print('chain analytic: 0.95^4 = %.4f, silent with stop-gate 0.96^4-0.95^4 = %.4f, retry (0.95+0.05*0.8*0.95)^4 = %.4f'
          % (0.95 ** 4, 0.96 ** 4 - 0.95 ** 4, (0.95 + 0.05 * 0.8 * 0.95) ** 4))
    general = rate([rng.random() < 0.80 for _ in range(n)])
    print('single general prompt success %.4f' % general)
    for acc in (0.6, 0.7, 0.9):
        print('route accuracy %.1f success %.4f analytic %.4f' % (
            acc, rate([route(rng, acc)[0] for _ in range(n)]), acc * 0.95 + (1 - acc) * 0.5))
    print('route break-even accuracy (0.80-0.50)/(0.95-0.50) = %.4f' % ((0.80 - 0.50) / (0.95 - 0.50)))
    crashes = sum(route(rng, 0.9, unknown_rate=0.02, fallback=False)[0] is None for _ in range(n))
    print('route with 2%% unknown labels and no fallback: unhandled %d of %d' % (crashes, n))
    for shared in (0.0, 0.2):
        print('vote shared_hard=%.1f single %.4f majority-of-5 %.4f' % (
            shared, rate([vote(rng, voters=1, shared=shared) for _ in range(n)]),
            rate([vote(rng, shared=shared) for _ in range(n)])))
    print('vote analytic majority-of-5 at p=0.7: %.4f' % sum(
        math.comb(5, k) * 0.7 ** k * 0.3 ** (5 - k) for k in range(3, 6)))
    for mode in ('fixed', 'orchestrator', 'agent-loop'):
        runs = [decompose(rng, mode) for _ in range(n)]
        print('decompose %-12s success %.4f calls/item %.3f' % (
            mode, rate([r[0] for r in runs]), sum(r[1] for r in runs) / n))
    for rounds in (0, 1, 3, 10):
        runs = [evaluator_loop(rng, rounds) for _ in range(n)]
        print('evaluator-optimizer max_rounds=%2d quality %.4f calls/item %.3f' % (
            rounds, rate([r[0] for r in runs]), sum(r[1] for r in runs) / n))


if __name__ == '__main__':
    main()

The recorded output is:

items per experiment 20000 seed 0
chain no gate         success 0.8157  flagged 0.0000  silent 0.1843  calls/item 4.000
chain gate stops      success 0.8110  flagged 0.1523  silent 0.0367  calls/item 3.759
chain gate + 1 retry  success 0.9515  flagged 0.0063  silent 0.0422  calls/item 4.147
chain analytic: 0.95^4 = 0.8145, silent with stop-gate 0.96^4-0.95^4 = 0.0348, retry (0.95+0.05*0.8*0.95)^4 = 0.9529
single general prompt success 0.7992
route accuracy 0.6 success 0.7718 analytic 0.7700
route accuracy 0.7 success 0.8162 analytic 0.8150
route accuracy 0.9 success 0.9067 analytic 0.9050
route break-even accuracy (0.80-0.50)/(0.95-0.50) = 0.6667
route with 2% unknown labels and no fallback: unhandled 421 of 20000
vote shared_hard=0.0 single 0.7067 majority-of-5 0.8328
vote shared_hard=0.2 single 0.5588 majority-of-5 0.6670
vote analytic majority-of-5 at p=0.7: 0.8369
decompose fixed        success 0.4503 calls/item 4.000
decompose orchestrator success 0.7548 calls/item 5.392
decompose agent-loop   success 0.7487 calls/item 3.224
evaluator-optimizer max_rounds= 0 quality 0.3006 calls/item 1.000
evaluator-optimizer max_rounds= 1 quality 0.5530 calls/item 2.628
evaluator-optimizer max_rounds= 3 quality 0.7652 calls/item 4.091
evaluator-optimizer max_rounds=10 quality 0.8431 calls/item 4.756

Chaining. Four steps at 0.95 each succeed together only 81.6% of the time, and without gates every one of the 18.4% failures leaves the workflow looking normal. A gate that stops on detected errors does not raise success (81.1%), but it converts most failures into flagged ones: only 3.7% remain silent, close to the formula’s 3.5%. Adding one retry raises success to 95.2%, matching the formula’s 95.3%, for 4.15 calls per item instead of 4. Silent errors rise slightly, to 4.2%, because items that previously stopped at a flagged error now continue and can fail undetected later. A gate is a detection device first and an accuracy device only when paired with a retry or a fallback.

Routing. With these settings, routing beats the general prompt (79.9%) only above 66.7% classifier accuracy: at 0.6 it loses (77.2%), at 0.7 it barely wins (81.6%), at 0.9 it wins clearly (90.7%). Separately, a 2% rate of labels outside the route table leaves 421 of 20,000 tickets with no handler at all when no fallback exists. In the cookbook-style router this would surface as a lookup error; in production it needs a default route.

Voting. Five independent voters at 0.7 reach 83.3% by majority, near the formula’s 83.7%. When 20% of items are hard for every voter, a single voter drops to 55.9% and five voters reach only 66.7%, against a ceiling of 80%. Voting buys robustness against independent noise, not against shared blind spots in the prompt, the model or the data.

Decomposition. The fixed three-worker workflow succeeds on 45.0% of tasks, because tasks needing four or more subtasks cannot be completed by a path decided in advance. The orchestrator reaches 75.5% at 5.39 calls per task; the agent loop reaches 74.9% at 3.22 calls. In this toy the agent loop is cheaper because it has no separate planning and synthesis calls; with a higher early-stop rate or more expensive per-step context, the ranking would change. The structural result is the robust part: when the number of steps cannot be predicted, a fixed path fails in proportion to how often the prediction is wrong.

Evaluator-optimizer. Quality rises from 30.1% with no evaluation to 55.3% with one round (the formula gives 0.3 + 0.7 × 0.9 × 0.4 = 0.552), 76.5% with three and 84.3% with ten, at 4.76 calls per item. The ceiling from the 10% false-pass rate is 0.3 + 0.7 × 0.36/0.46 ≈ 0.848, so ten rounds are already close to it. An unbounded loop cannot exceed that ceiling; it can only spend more calls on the items that never pass.

Assumptions that real workflows break

Every success probability in the program is a constant chosen for illustration. Real step reliabilities vary by input, correlate across steps (a confusing ticket confuses every step), and change when a prompt or model version changes. The formulas are useful for reasoning about structure and for sanity-checking measured end-to-end numbers, not for predicting them.

Gates and evaluators are modeled with fixed recall and false-pass rates, independent of the error. In practice, the errors a gate misses are not random: a schema check catches malformed JSON and misses a well-formed wrong value. Measure gate recall on realistic failures before trusting the silent-error arithmetic.

Latency is not simulated. Sectioning and voting run in parallel, so their wall-clock time is roughly that of one call plus aggregation, while chains and loops add latency per step. Cost depends on tokens per call, not only on the number of calls; orchestrators and agents often carry growing context, which this program ignores.

The two sources are a practitioner guide and sample code, not controlled studies. The post reports experience from working with customers and building agents; it does not provide measurements for the patterns’ benefits. Introduction The live page as accessed on 2026-12-02 carries later edits, including a note that its tooling landscape has changed and updated framework and model names; this article relies on an archived January 2025 copy for the definitions and patterns and uses none of the later additions.

Exercises

  1. Classify each system as a workflow or an agent in the post’s sense, and explain: (a) code calls a model to extract fields, then a second call to translate them, then validates the result against a schema; (b) a model receives a bug report and a set of file and test tools and decides which files to open, what to edit and when to stop.

    Answer: (a) is a workflow, specifically prompt chaining with a gate: the code path is fixed in advance. (b) is an agent: the model directs its own process and tool use, and the number of steps depends on what it finds. The distinction concerns who controls the path, not how many model calls there are.

  2. A chain has six steps, each correct with probability 0.97, and no gates. What is end-to-end success? Then, in the program’s evaluator-optimizer setting (first draft good 0.3, fix 0.4, false pass 0.1), what is the best quality any number of rounds can reach?

    Answer: 0.97 to the sixth power ≈ 0.833, so one item in six fails even though each step looks reliable. For the loop, the eventual fix probability from a bad start is 0.9 × 0.4 / (1 − 0.9 × 0.6) = 0.36/0.46 ≈ 0.783, so the ceiling is 0.3 + 0.7 × 0.783 ≈ 0.848. Ten rounds in the program reach 0.843.

  3. A colleague proposes going from five voters to fifteen to catch more unsafe outputs, citing the binomial formula. Under what condition will this barely help, and how would you check for it?

    Answer: If errors are correlated, more voters help little: in the program, when 20% of items are hard for every voter, five voters reach 66.7% against a ceiling of 80%, and no number of voters can pass that ceiling. Check by measuring agreement among voters on labeled failures; if they tend to fail on the same items, vary the prompts, models or evidence each voter sees instead of adding copies.

  4. Choose a pattern for each task and say what you would build around it: (a) extracting ten fields from invoices with a known schema; (b) applying a library upgrade across a repository where the files that need changing are unknown in advance.

    Answer: (a) Prompt chaining or a single call with a schema gate and one retry, plus a fallback to human review for flagged items; the steps are known, so a fixed path is easier to test and the gate turns silent errors into flagged ones. (b) Orchestrator-workers or an agent loop with tools, because the number and nature of subtasks depends on the repository; add an iteration limit, tests as ground-truth feedback, a sandbox, and a default path when the plan or a route is unrecognized.

Choosing and evaluating workflows

The post’s advice can be read as an engineering order of operations: start with one call, add a workflow pattern when it demonstrably improves outcomes, and move to agents when the path cannot be fixed in advance; it closes with three principles for agents: simplicity, transparency of planning steps, and careful design of the agent-computer interface through tool documentation and testing. Summary The cookbook shows how little code the patterns themselves need, which shifts the work to what surrounds them: fallbacks, iteration limits, validation and logging. Notebooks

When evaluating a workflow, report end-to-end success, the rate of silent versus flagged failures, the number of calls and tokens per item, and wall-clock latency, each against the single-prompt baseline. Measure step reliabilities and gate recall on realistic inputs and check whether errors are correlated before relying on any product of probabilities. Related entries cover the loop inside an agent (ReAct agents and tool use), planning and reflection components, agent orchestration across several agents, and agent evaluation.

Make a prediction, then check

Specialized handlers succeed 0.95 on their category and 0.5 when misrouted; a general prompt succeeds 0.80. What classifier accuracy must routing exceed to help?

Choose one answer

Learning objectives

  • Distinguish workflows from agents by who controls the path, and state when prompt chaining, routing, parallel voting, orchestrator-workers and evaluator-optimizer fit.
  • Use reliability formulas for end-to-end success, silent errors, routing break-even and evaluator-loop ceilings, and recognize risks such as correlated errors, missing fallbacks and unbounded loops.

Prerequisites & connections

Explore related knowledge →

References

  1. Building effective agents — Anthropic post (2024-12-19, served under anthropic.com/research), Internet Archive copy of 2025-01-15
    Erik Schluntz; Barry Zhang (Anthropic) · 2024
  2. Claude cookbooks — patterns/agents basic workflows and evaluator-optimizer notebooks at fixed commit cbcc709
    Anthropic cookbook contributors · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Claude · 2026-12-02 · Independent AI check (Claude subagent, not the author; not a human or expert review). Ran example.py with python3 3.12 and diffed it against example.stdout.txt (identical); confirmed the python block is byte-identical in en.mdx and zh.mdx and the five display equations match. Re-derived 0.95^4 = 0.8145, the stop-gate silent rate 0.96^4 - 0.95^4 = 0.0348, the retry rate 0.988^4 = 0.9529 and an analytic retry silent rate of about 0.041 (consistent with the simulated rise to 0.042), routing break-even (0.80-0.50)/(0.95-0.50) = 2/3, majority-of-5 0.8369 and its 0.8 x 0.8369 = 0.670 shared-hard value, the decomposition rates (fixed 0.452, orchestrator 0.755, agent loop 0.746 analytically), the evaluator one-round 0.552 and ceiling 0.3 + 0.7 x 0.36/0.46 = 0.848, and 0.97^6 = 0.833. Downloaded the Internet Archive capture 20250115210347 of the Anthropic post with curl and read its full stripped text, including the acknowledgements line 'Written by Erik Schluntz and Barry Zhang'; also fetched the live page, which now shows 'Erik S.', a tooling-changed note and Claude Agent SDK/Strands in the framework list. Fetched util.py, basic_workflows.ipynb, evaluator_optimizer.ipynb and LICENSE at commit cbcc709 (committed 2025-11-28) and confirmed the not-production-code note, route() indexing routes[route_key] with no fallback, extract_xml returning an empty string, and loop() as while True until PASS. Compared zh and en section by section and checked data.json IDs. Did not read orchestrator_workers.ipynb and did not render the MDX.

  • Code output matches the recording; code blocks are byte-identical; all prose numbers match the output.
  • Hand-verified the silent-error, retry, routing break-even, majority-vote, decomposition and 0.848 evaluator-ceiling formulas and all exercise answers.
  • Verified from the archived capture that the authors are Erik Schluntz and Barry Zhang and fixed the source row; the cited definitions, pattern fit conditions, stopping conditions and three principles are all in that capture.
  • All four cookbook observations at the fixed commit are accurate; all probabilities are labelled arbitrary illustrative settings not taken from the sources; zh and en correspond; IDs exist; quiz answer is correct.

Source locations checked:

  • Building effective agents — Anthropic post (2024-12-19, served under anthropic.com/research), Internet Archive copy of 2025-01-15 · Full text of the Internet Archive capture 20250115210347 of anthropic.com/research/building-effective-agents (dated Dec 19, 2024): definitions; simplest-solution and latency/cost trade-off; frameworks list (LangGraph, Bedrock, Rivet, Vellum in that capture); augmented LLM; five workflow patterns with when-to-use text; agents with ground truth, checkpoints, max-iteration stopping, compounding errors, sandboxing; summary three principles; appendices. Live page on 2026-12-02 compared: post-cutoff edits (tooling note, Claude Agent SDK/Strands, newer model names) not used. Acknowledgements line of the archived capture reads 'Written by Erik Schluntz and Barry Zhang' (authors re-verified from that capture in the independent check of 2026-12-02).
  • Claude cookbooks — patterns/agents basic workflows and evaluator-optimizer notebooks at fixed commit cbcc709 · Commit cbcc709f1db0cdfdda1435bf9c0b4d2d1c86ee56 (2025-11-28): patterns/agents/basic_workflows.ipynb all cells; patterns/agents/evaluator_optimizer.ipynb all cells; patterns/agents/util.py lines 1–45; LICENSE lines 1–3 (MIT). Observations: route() indexes routes[route_key] with no fallback; extract_xml returns '' on missing tag; loop() is while True until PASS. orchestrator_workers.ipynb not read. Not executed (needs API key).

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.