08A.9 Workflows vs Agents
Lesson 08A.2 built the agent loop: call the model, run the tool calls it asks for, append the results, repeat until it answers or a budget runs out. This lesson steps back and asks the question that decides whether you should build that loop at all. In December 2024 Anthropic published Building effective agents, the essay this module's decision framework is built on. It draws the line this lesson uses: workflows are systems where LLMs and tools are orchestrated through predefined code paths, while agents are systems where the LLM dynamically directs its own process and tool usage. Between a single API call and a fully autonomous agent sits a spectrum of patterns — chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer — and the engineering skill is picking the simplest rung that solves the task.
What you'll learn
- The workflows-versus-agents distinction, in the words of the providers' own published guidance (Anthropic, OpenAI, Google, LangGraph), and why "agentic system" is the umbrella term
- The spectrum from a single call to an autonomous agent, and the cost you pay for each step of autonomy
- Eight workflow patterns in full: prompt chaining with gates, routing, parallelization (sectioning and voting), orchestrator-workers, evaluator-optimizer, map-reduce, human-in-the-loop checkpoints, and fallback/escalation chains
- A complete
workflows.pyimplementing every pattern over an injectablecall_model, runnable end-to-end with a scripted fake model and no API keys - The Workflow-First Rule (use a deterministic workflow unless an agent is clearly needed) and how to apply it in a design review
- When an agent is the right answer — and the checklist of conditions that rule one out
- The reliability maths: why per-step error rates compound, why verification gates win, and how loop costs multiply
- Durable execution for long-running workflows: state persistence, resumption, idempotency, step-level retries, and the engines that provide them (LangGraph checkpointers, Temporal, Prefect, Celery)
- One task — a refund request — built three ways (single call, workflow, agent) and compared honestly
What you don't need
- API keys. Every runnable sample uses
ScriptedModel, a fake model that replays canned replies, so you can run the whole lesson offline. The provider adapter sketch is labelled illustrative. - The internals of one tool-calling round trip — that's lesson 03.5, and the full agent loop is lesson 08A.2. This lesson orchestrates model calls; it doesn't re-teach how a single call works.
- Experience with workflow engines. Part 6 explains the concepts first, then names the tools.
- Prior orchestration or distributed-systems experience. Wherever a concept maps to something you already know (ETL stages, sagas, job queues), a 🔁 Coming from another stack note says so.
Setup
The runnable code needs Python 3.11+ and Pydantic. First time with uv? Create a project, then add the package:
uv init tool-agents --bare --python 3.13
cd tool-agents
uv add pydantic
# or: pip install pydantic(Already have a project from lessons 03.x or earlier Module 08A lessons? Just uv add pydantic inside it.) This lesson needs no .env file and no API keys: ScriptedModel stands in for the model everywhere. If you later wire call_model to a real provider, the keys go in .env exactly as in lesson 03.1; the adapter sketch in 3.0 shows where.
What you must be able to do after this lesson#
- Explain the difference between a workflow and an agent
- Decide whether a task needs a single call, a workflow or an agent
- Apply the Workflow-First Rule: use a deterministic workflow unless an agent is clearly needed, and name the reason when you choose an agent
- Implement the main workflow patterns such as chaining, routing and parallelization
- Calculate how per-step error rates compound across a multi-step run
- Compare a single call, a workflow and an agent on the same task
Why this matters for an AI engineer#
This is the lesson that decides your architecture before you write a line of agent code. The failure mode it prevents is the most common one in applied AI: reaching for an autonomous loop because it's the exciting option, then paying for it in latency, tokens, debugging time and unpredictable behaviour on a task a five-line chain would have handled.
| You'll hear... | You'll understand it after... |
|---|---|
| "Let's just make it an agent." | Part 1: the distinction and the decision table |
| "Workflows are dead — agents do everything now." | 1.4 What the providers' guidance agrees on |
| "Chain the prompts and add a check between steps." | 3.1 Prompt chaining |
| "Route tickets to different prompts or models." | 3.2 Routing |
| "Ask three models and take the majority answer." | 3.3 Parallelization |
| "The planner should decide the subtasks at runtime." | 3.4 Orchestrator-workers |
| "Have one model critique and another revise, in a loop." | 3.5 Evaluator-optimizer |
| "Summarize a 200-page contract." | 3.6 Map-reduce |
| "A human must approve refunds over $500." | 3.7 Human-in-the-loop checkpoints |
| "If the strong model fails, fall back to the cheap one — or to a plain workflow." | 3.8 Fallback and escalation chains |
| "How many steps can this agent take before we stop it?" | Part 4: when to use an agent |
| "Why does the demo work but production fails 30% of the time?" | Part 5: the reliability maths |
| "The run crashed on step 4 of 9 — do we start over?" | Part 6: durable workflows |
| "Is this task a workflow or an agent?" | The flowchart and the worked example |
Part 1: The distinction that decides everything#
1.1 Two definitions, and they disagree usefully#
Ask five engineers to define "agent" and you'll get five answers. The providers have published theirs, and they don't line up perfectly — which is itself worth understanding.
Anthropic (Erik Schluntz and Barry Zhang, Building effective agents, December 2024) groups everything under agentic systems and splits them two ways:
- "Workflows are systems where LLMs and tools are orchestrated through predefined code paths."
- "Agents, on the other hand, are systems where LLMs dynamically direct their own processes and tool usage, maintaining control over how they accomplish tasks."
OpenAI (A practical guide to building agents, April 2025) defines an agent more narrowly: "Agents are systems that independently accomplish tasks on your behalf." Its litmus test is who controls execution: "Applications that integrate LLMs but don't use them to control workflow execution — think simple chatbots, single-turn LLMs, or sentiment classifiers — are not agents." An agent, in OpenAI's framing, has an LLM managing the workflow: it "recognizes when a workflow is complete and can proactively correct its actions", and it "dynamically selects the appropriate tools depending on the workflow's current state".
Google Cloud (Architecture Center, Choose your agentic AI architecture components) describes an agent as "an application that achieves a goal by processing input, performing reasoning with available tools, and taking actions based on its decisions" — and says what kind of problem that suits: "AI agents are effective for applications that solve open-ended problems". A task whose steps you can list in advance sits on the other side of that line.
LangChain/LangGraph puts it in one line: "Workflows have predetermined code paths and are designed to operate in a certain order. Agents are dynamic and define their own processes and tool usage." (Workflows and agents)
| Source | Definition of workflow | Definition of agent | The dividing line |
|---|---|---|---|
| Anthropic | LLMs and tools orchestrated through predefined code paths | LLM dynamically directs its own process and tool usage | Who decides the steps: your code, or the model |
| OpenAI | "A workflow is a sequence of steps that must be executed to meet the user's goal" | System that independently accomplishes tasks; LLM manages execution and picks tools | Who manages execution: deterministic code, or the model |
| Google Cloud | Not defined on the page; the contrast it draws is with open-ended problems | Goal-directed system that reasons, uses tools, takes actions | Is the problem open-ended |
| LangGraph | Predetermined code paths, operated in a certain order | Dynamic; defines its own processes and tool usage | Predetermined vs dynamic control flow |
The definitions differ in wording but converge on one test, and it's the test this module uses:
If your code decides what happens next, it's a workflow. If the model decides, it's an agent.
1.2 The spectrum, not a switch#
The mistake is treating "workflow vs agent" as a binary. It's a spectrum, and each rung buys flexibility at a price:
flowchart LR
A["1. Single LLM call<br/>prompt → answer"] --> B["2. Prompt chain<br/>fixed steps, code between them"]
B --> C["3. Router<br/>classifier picks the path"]
C --> D["4. Parallelization<br/>independent calls at once"]
D --> E["5. Orchestrator-workers<br/>model picks subtasks at runtime"]
E --> F["6. Agent loop<br/>model directs steps + tools until done"]
style A fill:#e8f4e8
style F fill:#fde8e8Reading left to right:
| Rung | Who controls the flow | Steps known in advance? | Typical cost/latency | Failure character |
|---|---|---|---|---|
| 1. Single call | Nobody — one shot | Yes | Cheapest, fastest | Wrong answer, but bounded |
| 2. Prompt chain | Your code | Yes — fixed sequence | N × single call | Fails at a known step; easy to localise |
| 3. Router | Your code + one classifier call | The set of paths is fixed; which one is data-dependent | 1 + branch cost | Misclassification sends work down the wrong path |
| 4. Parallelization | Your code | Yes — fan-out shape is fixed | ~max(branch) latency, sum of tokens | Partial failures; aggregation is a new failure point |
| 5. Orchestrator-workers | The orchestrator model picks subtasks; your code runs them | No — subtasks decided at runtime | Variable; often super-linear in steps | Hallucinated or duplicated subtasks; synthesis errors |
| 6. Agent loop | The model, step by step, with tools | No | Highest and most variable | Loops, runaway cost, compounding errors |
The practical reading: autonomy is bought per rung, not per system. A production feature is usually a chain with one router, one parallel section and — only where the task genuinely can't be enumerated — an agent loop inside a bounded step. Anthropic's own summary says it plainly: "you should consider adding complexity only when it demonstrably improves outcomes."
1.3 "Agentic" is the umbrella, not the answer#
Anthropic's phrasing matters: all of these variations — chains, routers, agents — are agentic systems. So "we're building an agentic system" tells you nothing about architecture. It only tells you LLMs are doing judgement work somewhere in the pipeline.
OpenAI's guide makes the complementary point from the other side: it tells teams to check that a use case clearly meets its criteria for an agent, "Otherwise, a deterministic solution may suffice", and a deterministic workflow with LLM steps is often exactly right. The useful question is never "is this an agent?" but "which parts of this need model judgement, and which parts should stay deterministic?"
1.4 What the providers' guidance agrees on#
Three major providers have published explicit guidance on this exact question, and they agree remarkably:
| Guidance | Core advice | Key line |
|---|---|---|
| Anthropic, Building effective agents (Dec 2024) | "Finding the simplest solution possible, and only increasing complexity when needed. This might mean not building agentic systems at all." | "Workflows offer predictability and consistency for well-defined tasks, whereas agents are the better option when flexibility and model-driven decision-making are needed at scale." |
| OpenAI, A practical guide to building agents (April 2025) | Build incrementally: "customers typically achieve greater success with an incremental approach" than a fully autonomous agent | Agents fit "workflows that have previously resisted automation" — complex judgement, unmaintainable rulesets, heavy unstructured data; otherwise "a deterministic solution may suffice" |
| Google Cloud, Architecture Center | "AI agents are effective for applications that solve open-ended problems" | Agents "excel at solving problems in real-time by using external data" and "excel at automating knowledge-intensive tasks" |
| LangGraph docs | Workflows for predetermined paths; agents "in situations where problems and solutions are unpredictable" | "Agents have more autonomy than workflows, and can make decisions about the tools they use and how to solve problems." |
The consensus, in one sentence: default to the simplest thing that works — a single call, then a workflow, then an agent — and add autonomy only where it demonstrably earns its cost. That's the module thesis, and it's why this lesson comes before the pattern lessons rather than after them.
1.5 What each rung costs you#
Autonomy isn't free, and the price shows up in four currencies:
- Latency. Every model call is a network round trip measured in seconds. A 10-step agent loop is at least 10 sequential round trips plus tool execution; a chain of the same length is the same — but a workflow's steps are known, so you can parallelise, cache, stream and set per-step timeouts. An agent's path isn't known until it finishes.
- Tokens and money. Each turn resends the growing conversation (the loop's context accumulates tool results — 04.7 is the deep dive). Anthropic's engineering team measured their own production agents at roughly 4× the tokens of a chat interaction, and multi-agent systems at roughly 15× — from How we built our multi-agent research system (June 2025). Workflows multiply cost predictably (N calls); agents multiply it unpredictably (however many turns the model takes).
- Variance. A workflow produces the same shape of outcome every run; an agent's trajectory varies run to run even at temperature 0-equivalent settings, because the environment (tool results, retrieved documents) varies. Variance is fine for research, dangerous for anything with side effects.
- Debuggability. A failed workflow step is a known location with a known input. A failed agent run is a trajectory you have to replay — which is why lesson 08A.14 makes trajectory logging the first observability requirement.
Part 2: The decision framework#
2.1 The questions that decide#
Before choosing a rung, answer these in order. The first "no" usually settles it.
- Can you write down the steps in advance? If yes, it's a workflow — possibly a single call. If the number or nature of steps depends on what the model discovers mid-task, you're on the agent side of the line.
- Does every step need the same prompt, model and tools? If yes, one call with a good prompt (Module 04) beats a chain. If steps want different personas, different models (cheap classifier, strong writer) or different tool sets, you want separate calls — a chain or a router.
- Can you check each intermediate result? Verification gates are what make chains reliable (3.1). If you can't tell a good intermediate result from a bad one, chaining just multiplies the places things can go wrong — that's an argument for fewer steps or an agent with environment feedback.
- Are there side effects or irreversible actions? Refunds, emails, deletions. Wherever the answer is yes, you need a human checkpoint (3.7) and idempotent tools (08A.6, 03.5) regardless of which rung you pick.
- What's the latency and cost budget? Multiply honestly: N sequential calls ≈ N × (model latency + your overhead). Part 5 does the arithmetic.
- Can you evaluate the outcome? Anthropic's test for evaluator-optimizer applies to everything: if you can tell success from failure — by a schema, a test, a rubric, a human — you can verify. If you can't verify, you can't safely automate, workflow or agent.
2.2 The decision table#
| Your situation | Start with | Escalate to |
|---|---|---|
| Single transformation, extraction or classification | One call, schema-constrained (03.4) | A chain if one call can't hold the whole task |
| Task splits cleanly into fixed stages (outline → draft → polish) | Prompt chain with gates | Orchestrator-workers if the subtasks can't be enumerated |
| Inputs fall into distinct categories needing different handling | Router (schema-constrained classifier) | Per-route chains; agent only for the genuinely open routes |
| Independent subtasks, or you want N attempts for confidence | Parallelization (sectioning / voting) | Orchestrator-workers if the split isn't known in advance |
| Subtasks depend on what earlier steps discover | Orchestrator-workers | Bounded agent loop for the worker that needs it |
| Output quality is improvable by critique and you can articulate the standard | Evaluator-optimizer | More rounds or a stronger critic model |
| Input exceeds the context window or is too costly whole | Map-reduce over chunks/documents | Hierarchical reduce for very large corpora |
| Irreversible or high-stakes action | Human-in-the-loop checkpoint — in any architecture | Tighter approvals, not more autonomy |
| Flaky steps, rate limits, model variance | Fallback/escalation chain around any pattern | Retry policy per step (03.8) |
| Steps genuinely can't be predicted; environment gives feedback; you can sandbox and evaluate | Agent loop (08A.2) | Multi-agent only with evidence it pays (08D.3) |
2.3 Choosing with a flowchart#
flowchart TD
Q1{"Can you name the steps<br/>before the run?"} -->|"yes, one step"| S["Single call"]
Q1 -->|"yes, several"| Q2{"Do steps need<br/>different prompts/models?"}
Q1 -->|"no"| Q3{"Can you bound the work<br/>another way?"}
Q2 -->|"no"| C["Prompt chain"]
Q2 -->|"yes, by category"| R["Router"]
Q2 -->|"yes, independent parts"| P["Parallelization"]
Q2 -->|"yes, discovered at runtime"| O["Orchestrator-workers"]
Q3 -->|"yes — decompose once,<br/>then bounded workers"| O
Q3 -->|"no — genuinely open-ended"| A{"Can you verify outcomes,<br/>sandbox, and budget the run?"}
A -->|"yes"| AG["Agent loop"]
A -->|"no"| H["Human-in-the-loop<br/>or don't automate"]
S --> G{"Side effects or<br/>irreversible action?"}
C --> G
R --> G
P --> G
O --> G
AG --> G
G -->|"yes"| HITL["Add approval checkpoint<br/>(3.7) + idempotent tools"]
G -->|"no"| DONE["Ship it — with budgets<br/>and a trace (Part 5-6)"]Every "yes" path ends in the same place: budgets, verification and observability are not optional extras — they're what separates a demo from a system. Parts 5 and 6 build them.
2.4 The worked example, previewed#
Part 7 takes one task — a customer asks for a refund — and builds it three ways: a single call, a prompt-chain workflow with an approval checkpoint, and an agent loop. Same tools, same data, three different contracts between your code and the model. The comparison at the end is the decision table in 2.2 made concrete.
Part 3: The workflow patterns#
3.0 The call_model interface and ScriptedModel#
Every pattern in this part is implemented the same way: your code orchestrates, an injectable call_model performs each model call. That indirection is what makes the patterns testable without keys and portable across providers.
# workflows.py — shared scaffolding for every pattern in this lesson.
# Layer: pure-local — runs with ScriptedModel, no API keys, no network.
from __future__ import annotations
import asyncio
import inspect
import json
import time
import uuid
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Protocol
from pydantic import BaseModel
# A message is provider-neutral: a role and text. Adapters translate this
# into each provider's wire shape — that mapping is lesson 03.2's job,
# not this lesson's.
Message = dict[str, str]
class CallModel(Protocol):
"""Any async callable that sends messages and returns text or a model.
`schema` asks for schema-constrained output (lesson 03.4); `name` labels
the call for tracing. In production this is an adapter over one of the
four provider SDKs; in tests it is a ScriptedModel.
"""
async def __call__(
self,
messages: list[Message],
*,
schema: type[BaseModel] | None = None,
name: str | None = None,
) -> "str | BaseModel": ...
class ScriptedModel:
"""Replays canned replies in order and records every call.
Lesson 08A.2 builds the full ScriptedModel (with tool calls) that the
rest of Module 08A reuses; this trimmed version is all the workflow
patterns need — text replies and structured replies.
"""
def __init__(self, replies: list[Any]) -> None:
self._replies = list(replies)
self.calls: list[dict[str, Any]] = []
async def __call__(
self,
messages: list[Message],
*,
schema: type[BaseModel] | None = None,
name: str | None = None,
) -> Any:
self.calls.append(
{"name": name, "schema": schema.__name__ if schema else None}
)
if not self._replies:
raise RuntimeError("ScriptedModel: out of scripted replies")
reply = self._replies.pop(0)
if schema is None:
return reply
if isinstance(reply, BaseModel):
return schema.model_validate(reply.model_dump())
if isinstance(reply, dict):
return schema.model_validate(reply)
return schema.model_validate_json(reply)
@dataclass
class TraceEvent:
trace_id: str
step: str
ok: bool
detail: str
elapsed_ms: float
class Tracer:
"""One JSON line per workflow event: the minimum viable trajectory log.
Lesson 08A.14 builds the full observability story (spans, cost
attribution, redaction) on top of this shape; lesson 03.10 owns the
general logging discipline.
"""
def __init__(self, trace_id: str | None = None) -> None:
self.trace_id = trace_id or uuid.uuid4().hex[:12]
self.events: list[TraceEvent] = []
self._seq = 0
def record(
self,
step: str,
*,
ok: bool = True,
detail: str = "",
elapsed_ms: float = 0.0,
) -> None:
self._seq += 1
ev = TraceEvent(self.trace_id, step, ok, detail, round(elapsed_ms, 1))
self.events.append(ev)
print(json.dumps({"seq": self._seq, **ev.__dict__}, default=str))
async def _maybe_await(value: Any) -> Any:
if inspect.isawaitable(value):
return await value
return valueThree design choices worth stating:
call_modelis async. Real SDKs have async clients, and the parallelization pattern needsasyncio.gatheranyway (03.9 owns the concurrency mechanics). Every sample below ends inasyncio.run(main()).schemais optional and separate frommessages. When present, the adapter uses that provider's structured-output mechanism (03.4);ScriptedModeljust validates the canned reply against it, which is exactly what a unit test wants.nameexists only for tracing. It costs nothing and turns "which step called the model?" into a grep.
Wiring call_model to the four providers. The adapter is the only provider-specific code in the whole lesson; everything above it is portable. Sketch (illustrative — each branch mirrors the structured-output calls verified in 03.4):
# adapters.py — ILLUSTRATIVE: needs API keys; structure is the lesson.
# call_model(messages, schema=..., name=...) over each provider's SDK.
import json
from openai import AsyncOpenAI
from anthropic import AsyncAnthropic
from google import genai
def _openai_adapter(client: AsyncOpenAI, model: str = "gpt-6-luna"):
async def call(messages, *, schema=None, name=None):
kwargs = {"model": model, "input": messages}
if schema is not None:
# Responses API structured outputs: text.format json_schema
kwargs["text"] = {"format": {
"type": "json_schema", "name": name or "output",
"schema": schema.model_json_schema(), "strict": True}}
resp = await client.responses.create(**kwargs)
if schema is None:
return resp.output_text
return schema.model_validate_json(resp.output_text)
return call
def _anthropic_adapter(client: AsyncAnthropic, model: str = "claude-haiku-5-5"):
async def call(messages, *, schema=None, name=None):
kwargs = {"model": model, "max_tokens": 4096,
"messages": [{"role": m["role"], "content": m["content"]}
for m in messages if m["role"] != "system"],
"system": next((m["content"] for m in messages
if m["role"] == "system"), "")}
if schema is not None:
# output_config.format json_schema; messages.parse validates for you
kwargs["output_config"] = {"format": {
"type": "json_schema", "schema": schema.model_json_schema()}}
resp = await client.messages.create(**kwargs)
text = "".join(b.text for b in resp.content if b.type == "text")
if schema is None:
return text
return schema.model_validate_json(text)
return call
def _gemini_adapter(client: genai.Client, model: str = "gemini-3.8-flash"):
async def call(messages, *, schema=None, name=None):
# generate_content primary; response_json_schema is Google's
# recommended route for arbitrary JSON Schema (03.4, 3.4)
config = {"response_mime_type": "application/json"}
if schema is not None:
config["response_json_schema"] = schema.model_json_schema()
resp = await client.aio.models.generate_content(
model=model, contents=[m["content"] for m in messages],
config=config)
text = resp.text or ""
return schema.model_validate_json(text) if schema else text
return call
def _openrouter_adapter(client: AsyncOpenAI, model: str = "openai/gpt-6-luna"):
# OpenRouter speaks Chat Completions through the openai SDK with a
# different base_url; response_format json_schema passes through to
# endpoints that support it (03.4, 3.6 — check supported_parameters).
...3.1 Prompt chaining, with gates#
The pattern: decompose a task into a sequence of steps; each model call processes the previous step's output; programmatic checks ("gates") between steps verify the process is still on track. Anthropic's example: generate marketing copy, then translate it — or write an outline, check it against criteria, then write the document.
flowchart LR
IN["task"] --> S1["step 1: model call"]
S1 --> G1{"gate 1<br/>(code or model?)"}
G1 -->|"fail, retry"| S1
G1 -->|"pass"| S2["step 2: model call"]
S2 --> G2{"gate 2"}
G2 -->|"fail, retry"| S2
G2 -->|"pass"| OUT["final state"]The implementation below makes one thing explicit that the diagrams hide: a workflow step doesn't have to be a model call. Deterministic code — a database lookup, a validation, a format conversion — is a first-class step. That's the whole point of a workflow: you put the model exactly where judgement is needed and keep everything else in code.
# workflows.py (continued) — prompt chaining. Pure-local.
from typing import Literal
@dataclass
class ChainStep:
"""One step of a workflow.
A step is either deterministic (`fn`: plain code over the state) or a
model call (`build_messages` produces the messages, `schema` asks for
structured output). `gate` inspects the result and returns None to
accept it or a string describing the problem; a non-None result retries
the step up to `max_attempts`, with the reason appended to
`state["_errors"]` so the next `build_messages` can feed it back.
"""
name: str
fn: Callable[[dict[str, Any]], Any] | None = None
build_messages: Callable[[dict[str, Any]], list[Message]] | None = None
schema: type[BaseModel] | None = None
gate: Callable[[Any, dict[str, Any]], str | None] | None = None
max_attempts: int = 1
class GateFailed(RuntimeError):
"""A workflow step's gate rejected its output on every attempt."""
async def prompt_chain(
call_model: CallModel,
task: dict[str, Any],
steps: list[ChainStep],
*,
tracer: Tracer | None = None,
) -> dict[str, Any]:
"""Run steps in order. Each sees everything produced so far in `state`.
`state["input"]` is the task; each step's result lands under its `name`.
"""
state: dict[str, Any] = {"input": task, "_errors": []}
tracer = tracer or Tracer()
for step in steps:
ok = False
for attempt in range(1, step.max_attempts + 1):
t0 = time.perf_counter()
if step.fn is not None:
result = await _maybe_await(step.fn(state))
else:
assert step.build_messages is not None, step.name
result = await call_model(
step.build_messages(state), schema=step.schema, name=step.name
)
elapsed = (time.perf_counter() - t0) * 1000
state[step.name] = result
reason = step.gate(result, state) if step.gate else None
tracer.record(
step.name,
ok=reason is None,
detail=reason or f"attempt {attempt}",
elapsed_ms=elapsed,
)
if reason is None:
ok = True
break
state["_errors"].append(f"{step.name} attempt {attempt}: {reason}")
if not ok:
raise GateFailed(
f"step '{step.name}' failed its gate {step.max_attempts}x: "
f"{state['_errors'][-1]}"
)
return stateNow the example: a support-reply drafter for the running example. Classify the ticket (structured), look up the order (deterministic — no model needed), draft the reply (model), then gate the draft on containing the order ID (deterministic check). Note the repair path: if the classifier picks an order-type category for a ticket that has no order ID, or the draft drops the order ID, that step's gate fails and the step retries with the reason in _errors. (An unknown category never reaches a gate: TicketClass is a Literal, so the schema rejects it when the reply is parsed and a pydantic ValidationError propagates out of prompt_chain.)
# s31_support_reply.py — run standalone: python3 s31_support_reply.py
"""Prompt chaining over ScriptedModel: classify → lookup → draft → check.
Run it: the output is REAL — ScriptedModel replays the canned replies
below, so you see the actual trace lines and state this code produces.
"""
import asyncio
import json
from typing import Literal
from pydantic import BaseModel, Field
from workflows import ChainStep, ScriptedModel, prompt_chain
class TicketClass(BaseModel):
category: Literal["order", "refund", "technical", "other"]
urgency: Literal["low", "normal", "high"]
needs_human: bool = Field(
description="True when a person must review before any reply is sent"
)
ORDERS = { # deterministic "database" — no model involved
"A-1042": {"item": "mechanical keyboard", "status": "delivered",
"total": "189.00", "currency": "USD"},
}
CLASSIFY_PROMPT = """You classify support tickets for a peripherals shop.
Reply with JSON only."""
DRAFT_PROMPT = """Draft a short, polite support reply.
Use ONLY the facts provided. If a fact is missing, say you'll check and
come back — never invent order details, dates or policies."""
def _classify_messages(state):
errors = state["_errors"]
note = f"Previous attempt rejected: {errors[-1]}\n" if errors else ""
return [
{"role": "system", "content": CLASSIFY_PROMPT + "\n" + note},
{"role": "user", "content": json.dumps(state["input"]["ticket"])},
]
def _lookup_order(state):
ticket = state["input"]["ticket"]
order_id = ticket.get("order_id")
return ORDERS.get(order_id, {"found": False})
def _draft_messages(state):
return [
{"role": "system", "content": DRAFT_PROMPT},
{"role": "user", "content": json.dumps({
"ticket": state["input"]["ticket"],
"class": state["classify"].model_dump(),
"order": state["lookup"],
})},
]
def _classify_fits_ticket(result, state):
has_id = bool(state["input"]["ticket"].get("order_id"))
if result.category in ("order", "refund") and not has_id:
return f"category {result.category!r} needs an order ID, but the ticket has none"
return None
def _draft_has_order_id(draft, state):
order_id = state["input"]["ticket"].get("order_id", "")
if order_id and order_id not in draft:
return f"draft does not mention order {order_id}"
return None
async def main() -> None:
model = ScriptedModel([
# 1. classify → structured
{"category": "order", "urgency": "normal", "needs_human": False},
# 2. draft → text
"Hi! Your order A-1042 (mechanical keyboard, USD 189.00) was "
"delivered on schedule. Let us know if anything else comes up.",
])
state = await prompt_chain(model, {"ticket": {
"order_id": "A-1042", "message": "where is my order?"}},
[ChainStep("classify", build_messages=_classify_messages,
schema=TicketClass, gate=_classify_fits_ticket,
max_attempts=2),
ChainStep("lookup", fn=_lookup_order),
ChainStep("draft", build_messages=_draft_messages,
gate=_draft_has_order_id, max_attempts=2)])
print("\nfinal draft:", state["draft"])
print("model calls:", [c["name"] for c in model.calls])
asyncio.run(main())Output (real — produced by ScriptedModel, no API calls; trace_id is shortened to ... and elapsed_ms varies by machine):
{"seq": 1, "trace_id": "...", "step": "classify", "ok": true, "detail": "attempt 1", "elapsed_ms": 0.0}
{"seq": 2, "trace_id": "...", "step": "lookup", "ok": true, "detail": "attempt 1", "elapsed_ms": 0.0}
{"seq": 3, "trace_id": "...", "step": "draft", "ok": true, "detail": "attempt 1", "elapsed_ms": 0.0}
final draft: Hi! Your order A-1042 (mechanical keyboard, USD 189.00) was delivered on schedule. Let us know if anything else comes up.
model calls: ['classify', 'draft']What just happened, and why it matters:
- Three steps, two model calls. The lookup cost zero tokens because it's code. This is the first reliability lesson of the lesson: every step you keep in code is a step that can't hallucinate.
- The gate is deterministic.
_draft_has_order_iddoesn't ask a model "is this good?" — it checks a fact. Gates should be as dumb as possible; a model-judged gate is itself a failure point (that's what evaluator-optimizer in 3.5 is for, when you genuinely need judgement). - Latency is the sum. Three sequential steps ≈ three sequential latencies. Prompt chaining "trades off latency for higher accuracy, by making each LLM call an easier task" — Anthropic's words — and it also makes each call shorter, because each prompt carries only what that step needs (04.6 owns context selection).
- Failure is localised. If
classifyreturns a category that doesn't fit the ticket, the trace shows it at step 1 with its input; you don't get a fluent wrong answer three steps later. That property — failures announce themselves at a known step — is the main thing workflows buy over agents.
When it fits: tasks that decompose cleanly into fixed subtasks (Anthropic's criterion verbatim). When it doesn't: when the subtasks can't be predicted — that's orchestrator-workers (3.4) or an agent.
Evaluation idea: unit-test each step's gate with canned good/bad outputs; then an end-to-end eval on ~50 tickets measuring final-answer correctness and which step failed (Module 10A).
3.2 Routing#
The pattern: classify the input, then dispatch to a specialised handler — a different prompt, a different model, a different tool set, or plain code. Anthropic's examples: customer-service queries split into general / refund / technical; easy questions to a cheap model, hard ones to an expensive one. The win is separation of concerns: optimising one route's prompt can't hurt the others.
flowchart LR
IN["input text"] --> CLF["classifier call<br/>(schema-constrained)"]
CLF --> D{"route +<br/>confidence"}
D -->|"orders"| H1["order handler"]
D -->|"refunds"| H2["refund handler"]
D -->|"technical"| H3["tech handler"]
D -->|"low confidence /<br/>unknown route"| H4["human fallback"]
H1 & H2 & H3 & H4 --> OUT["result"]# workflows.py (continued) — routing. Pure-local.
from pydantic import Field
class RouteDecision(BaseModel):
"""What the classifier returns. Schema-constrained: the model can
only pick a string, a confidence and a reason (03.4)."""
route: str = Field(description="Exactly one of the configured route names")
confidence: float = Field(ge=0.0, le=1.0)
reason: str = ""
ROUTER_PROMPT = """You route support tickets for a peripherals shop.
Pick exactly one route:
{routes}
Give a confidence between 0 and 1 and a one-line reason."""
async def route(
call_model: CallModel,
text: str,
handlers: dict[str, Callable[[RouteDecision, str], Any]],
*,
routes_doc: str,
min_confidence: float = 0.0,
fallback: str = "human",
tracer: Tracer | None = None,
) -> tuple[Any, RouteDecision]:
"""Classify `text`, then dispatch to the matching handler.
`handlers` maps route name → callable(decision, text) → result (sync
or async). A decision below `min_confidence`, or naming a route that
isn't configured, goes to `fallback` — which must itself be a key of
`handlers`, or this raises ValueError rather than a bare KeyError at
dispatch time. The silent misroute is routing's most common
production bug, so the threshold is explicit, not vibes.
"""
tracer = tracer or Tracer()
if fallback not in handlers:
raise ValueError(f"fallback={fallback!r} is not a configured route")
t0 = time.perf_counter()
decision = await call_model(
[
{"role": "system", "content": ROUTER_PROMPT.format(routes=routes_doc)},
{"role": "user", "content": text},
],
schema=RouteDecision,
name="router",
)
assert isinstance(decision, RouteDecision)
tracer.record("router", ok=True,
detail=f"route={decision.route} "
f"confidence={decision.confidence:.2f}",
elapsed_ms=(time.perf_counter() - t0) * 1000)
chosen = decision.route if decision.route in handlers else fallback
if decision.confidence < min_confidence:
chosen = fallback
t0 = time.perf_counter()
result = await _maybe_await(handlers[chosen](decision, text))
tracer.record(
f"route:{chosen}",
detail=f"confidence={decision.confidence:.2f} — {decision.reason}",
elapsed_ms=(time.perf_counter() - t0) * 1000,
)
return result, decisionExample: one ticket routed to one of four handlers. The router can also pick which model handles a route, which is a different use of the same pattern (that's 04.8's routing and model cascading, and 02.9 owns the economics).
# s32_ticket_router.py — run standalone: python3 s32_ticket_router.py
"""Routing over ScriptedModel: classify once, dispatch to a handler."""
import asyncio
from workflows import ScriptedModel, route
ORDERS_ROUTE = """- orders: where is my order, delivery status, tracking
- refunds: return, refund, wrong item, damaged item
- technical: setup help, drivers, compatibility, defects
- billing: invoices, charges, payment methods"""
async def handle_orders(decision, text):
return {"action": "lookup_order", "note": "order status tool call would go here"}
async def handle_refunds(decision, text):
return {"action": "start_refund_flow", "note": "needs approval checkpoint (3.7)"}
async def handle_technical(decision, text):
return {"action": "search_docs", "note": "docs_qa retriever from Module 07"}
async def handle_human(decision, text):
return {"action": "queue_for_human", "reason": decision.reason}
async def main() -> None:
model = ScriptedModel([
# the classifier's structured reply
{"route": "orders", "confidence": 0.93,
"reason": "asks about delivery status"},
])
handlers = {
"orders": handle_orders, "refunds": handle_refunds,
"technical": handle_technical, "billing": handle_human,
"human": handle_human,
}
result, decision = await route(
model, "hi, my package was marked delivered but nothing arrived",
handlers, routes_doc=ORDERS_ROUTE, min_confidence=0.6)
print("decision:", decision.model_dump())
print("dispatched to:", result)
asyncio.run(main())Output (real — ScriptedModel replay; trace_id is shortened to ... and elapsed_ms varies by machine; json.dumps writes the em dash as \u2014):
{"seq": 1, "trace_id": "...", "step": "router", "ok": true, "detail": "route=orders confidence=0.93", "elapsed_ms": 0.0}
{"seq": 2, "trace_id": "...", "step": "route:orders", "ok": true, "detail": "confidence=0.93 \u2014 asks about delivery status", "elapsed_ms": 0.0}
decision: {'route': 'orders', 'confidence': 0.93, 'reason': 'asks about delivery status'}
dispatched to: {'action': 'lookup_order', 'note': 'order status tool call would go here'}Strengths: cheap (one extra classification call), predictable, each route independently testable and optimisable; the classifier itself can be a small model or even a traditional classifier for high-volume routing. Weaknesses: the route set must be enumerable up front; a misroute is silent unless you log decision (the tracer does); coverage gaps all pile onto fallback. Cost/latency: +1 call on every request, then only the chosen branch runs — often cheaper than one giant prompt that tries to handle everything. Failure modes: confident wrong route; route exists but handler is unimplemented; confidence scores that don't mean what you think (calibrate on your own data — Module 10A). Evaluation idea: a labelled set of ~100 tickets → measure routing accuracy per route and the fallback rate; the classifier is the cheapest eval target in the whole module.
3.3 Parallelization: sectioning and voting#
The pattern: run multiple LLM calls simultaneously and aggregate programmatically. Anthropic names two shapes: sectioning (break the task into independent subtasks run in parallel) and voting (run the same task several times for diverse outputs or higher confidence).
flowchart TB
subgraph sec ["Sectioning: different subtasks, one call each"]
T["task"] --> J1["subtask A"] & J2["subtask B"] & J3["subtask C"]
J1 & J2 & J3 --> AGG["programmatic merge"]
end
subgraph vote ["Voting: same call, N times"]
P["one prompt"] --> V1["run 1"] & V2["run 2"] & V3["run 3"]
V1 & V2 & V3 --> MAJ["majority / synthesis"]
end# workflows.py (continued) — bounded parallel calls and voting. Pure-local.
from collections import Counter
@dataclass
class Job:
name: str
messages: list[Message]
schema: type[BaseModel] | None = None
class ParallelJobError(RuntimeError):
"""One or more jobs failed; carries the partial results and the errors."""
def __init__(self, results: dict[str, Any], errors: dict[str, Exception]):
super().__init__(f"{len(errors)} of {len(results) + len(errors)} jobs failed")
self.results = results
self.errors = errors
async def parallel(
call_model: CallModel,
jobs: list[Job],
*,
max_concurrency: int = 4,
tracer: Tracer | None = None,
) -> dict[str, Any]:
"""Run independent model calls concurrently; return {name: result}.
Bounded by `max_concurrency` — a semaphore, the same pattern as lesson
03.9's bounded async (section 4.2 there).
All jobs run to completion; failures are collected into
ParallelJobError.results/.errors rather than aborting the batch —
a workflow should know what it has before it decides what to do.
"""
tracer = tracer or Tracer()
sem = asyncio.Semaphore(max_concurrency)
async def run(job: Job):
async with sem:
t0 = time.perf_counter()
try:
result = await call_model(
job.messages, schema=job.schema, name=job.name
)
tracer.record(job.name, ok=True,
elapsed_ms=(time.perf_counter() - t0) * 1000)
return job.name, result, None
except Exception as exc:
tracer.record(job.name, ok=False, detail=type(exc).__name__,
elapsed_ms=(time.perf_counter() - t0) * 1000)
return job.name, None, exc
outcomes = await asyncio.gather(*(run(j) for j in jobs))
results = {n: r for n, r, e in outcomes if e is None}
errors = {n: e for n, _, e in outcomes if e is not None}
if errors:
raise ParallelJobError(results, errors)
return results
async def vote(
call_model: CallModel,
messages: list[Message],
n: int = 3,
*,
max_concurrency: int = 4,
tracer: Tracer | None = None,
) -> tuple[Any, list[Any]]:
"""Run the same call n times; return (winner, all_answers).
Majority vote for short answers — deterministic, no extra model call.
For open-ended answers, replace the Counter with a final aggregation
call that sees all n replies (see the note after the example).
"""
jobs = [Job(name=f"vote-{i}", messages=messages) for i in range(n)]
results = await parallel(call_model, jobs,
max_concurrency=max_concurrency, tracer=tracer)
answers = [results[f"vote-{i}"] for i in range(n)]
counts = Counter(str(a).strip() for a in answers)
return counts.most_common(1)[0][0], answersExample — sectioning for a product launch (three independent analyses merged in code) and voting for a sentiment call:
# s33_parallel.py — run standalone: python3 s33_parallel.py
"""Sectioning + voting over ScriptedModel. Real output, no API calls."""
import asyncio
import json
from workflows import Job, ScriptedModel, parallel, vote
async def main() -> None:
# --- sectioning: three independent calls, merged in code -----------------
model = ScriptedModel([
"Social: launch post drafted, 3 hashtags.",
"Email: announcement to 12k subscribers drafted.",
"Docs: changelog entry written for v2.4.",
])
jobs = [
Job("social", [{"role": "user", "content": "draft the launch social post"}]),
Job("email", [{"role": "user", "content": "draft the launch email"}]),
Job("docs", [{"role": "user", "content": "write the changelog entry"}]),
]
parts = await parallel(model, jobs, max_concurrency=3)
merged = "\n".join(f"[{k}] {v}" for k, v in parts.items())
print("merged:\n", merged)
# --- voting: same sentiment call three times ------------------------------
model2 = ScriptedModel(["positive", "negative", "positive"])
winner, answers = await vote(
model2, [{"role": "user", "content":
'Classify: "works great but the cable is flimsy"'}], n=3)
print("\nvotes:", answers, "→ winner:", winner)
asyncio.run(main())Output (real — ScriptedModel replay, Counter decides; trace lines abbreviated — note the two trace_ids: sectioning and voting are separate parallel runs):
{"seq": 1, "trace_id": "...", "step": "social", "ok": true, "detail": "", "elapsed_ms": 0.0}
{"seq": 2, "trace_id": "...", "step": "email", "ok": true, "detail": "", "elapsed_ms": 0.0}
{"seq": 3, "trace_id": "...", "step": "docs", "ok": true, "detail": "", "elapsed_ms": 0.0}
merged:
[social] Social: launch post drafted, 3 hashtags.
[email] Email: announcement to 12k subscribers drafted.
[docs] Docs: changelog entry written for v2.4.
{"seq": 1, "trace_id": "...", "step": "vote-0", "ok": true, "detail": "", "elapsed_ms": 0.0}
{"seq": 2, "trace_id": "...", "step": "vote-1", "ok": true, "detail": "", "elapsed_ms": 0.0}
{"seq": 3, "trace_id": "...", "step": "vote-2", "ok": true, "detail": "", "elapsed_ms": 0.0}
votes: ['positive', 'negative', 'positive'] → winner: positiveStrengths: latency ≈ slowest branch, not sum (that's the whole point — link 03.9, 3.1 for the measured speed-up); independent failures don't cascade if you handle ParallelJobError; trivially parallel in tests. Weaknesses: token cost is the sum of branches (you pay N× for latency ÷N); aggregation is a new place to be wrong; unbounded fan-out hits rate limits — hence the semaphore. Cost/latency: latency ~ max(branch), cost ~ sum(branches) + aggregator. Failure modes: one branch fails → ParallelJobError with partial results (decide: proceed with partials, retry the failed job, or abort); correlated failures (all branches share the same bad context); voting ties. Evaluation idea: measure per-branch quality independently and end-to-end — a great sectioning merge can still lose information at the merge step.
3.4 Orchestrator-workers#
The pattern: a central model call decomposes the task into subtasks at runtime, workers execute them (in parallel where independent), and a final call synthesises. Anthropic: "a central LLM dynamically breaks down tasks, delegates them to worker LLMs, and synthesizes their results." The key difference from parallelization: the subtasks aren't pre-defined — the orchestrator decides them from the input.
flowchart TB
G["goal"] --> P["planner call<br/>→ Plan schema"]
P --> T1["worker: subtask 1"] & T2["worker: subtask 2"] & T3["worker: subtask 3"]
T1 & T2 & T3 --> S["synthesizer call<br/>plan + all results → answer"]# workflows.py (continued) — orchestrator-workers. Pure-local.
class SubTask(BaseModel):
id: str
title: str
instructions: str = Field(
description="Exactly what the worker should produce and return"
)
class Plan(BaseModel):
tasks: list[SubTask] = Field(
description="2-6 independent subtasks that together cover the goal"
)
async def orchestrate(
call_model: CallModel,
goal: str,
run_worker: Callable[[SubTask], Any],
*,
context: str = "",
max_workers: int = 3,
tracer: Tracer | None = None,
) -> tuple[Any, Plan, dict[str, Any]]:
"""Decompose `goal` at runtime, run workers concurrently, synthesise.
`run_worker` is injected: a prompt_chain, a single call_model call, or
— the boundary case — a bounded agent loop from 08A.2/08.5. The
orchestrator's authority ends at decomposition plus synthesis: workers
cannot spawn workers. (Workers spawning workers is 08D.3's multi-agent
territory, and it multiplies cost fast — see the token numbers in
Part 4.)
A worker that raises doesn't abort the run — the same collect-then-
decide philosophy as parallel(): the exception is traced (ok=False)
and surfaced to the synthesizer as {"error": ...} in `results`, and
the synthesis prompt tells it to flag failed subtasks plainly. If you
need abort-on-any-worker-failure instead, wrap `run_worker` so it
raises a sentinel you check for, or inspect `results` for "error"
keys before trusting the synthesis downstream.
"""
tracer = tracer or Tracer()
t0 = time.perf_counter()
plan = await call_model(
[
{"role": "system", "content":
"Break the goal into 2-6 independent subtasks. Each worker "
"sees only its own instructions, so make them self-contained."},
{"role": "user", "content":
(f"Context:\n{context}\n\n" if context else "") + f"Goal: {goal}"},
],
schema=Plan,
name="planner",
)
assert isinstance(plan, Plan)
tracer.record("planner", ok=True,
detail=f"{len(plan.tasks)} tasks: "
+ ", ".join(t.id for t in plan.tasks),
elapsed_ms=(time.perf_counter() - t0) * 1000)
sem = asyncio.Semaphore(max_workers)
async def run(task: SubTask):
async with sem:
t0 = time.perf_counter()
try:
result = await _maybe_await(run_worker(task))
except Exception as exc:
tracer.record(f"worker:{task.id}", ok=False,
detail=f"{type(exc).__name__}: {exc}",
elapsed_ms=(time.perf_counter() - t0) * 1000)
return task.id, {"error": f"{type(exc).__name__}: {exc}"}
tracer.record(f"worker:{task.id}", ok=True,
detail=task.title,
elapsed_ms=(time.perf_counter() - t0) * 1000)
return task.id, result
results = dict(await asyncio.gather(*(run(t) for t in plan.tasks)))
t0 = time.perf_counter()
synthesis = await call_model(
[
{"role": "system", "content":
"Synthesize the worker results into one answer to the goal. "
"Cite which subtask each claim came from; say so plainly if "
"the workers disagree or a subtask failed to answer."},
{"role": "user", "content": json.dumps({
"goal": goal,
"plan": [t.model_dump() for t in plan.tasks],
"results": results,
}, default=str)},
],
name="synthesizer",
)
tracer.record("synthesizer", ok=True,
detail=f"{len(results)} worker results",
elapsed_ms=(time.perf_counter() - t0) * 1000)
return synthesis, plan, resultsExample — a restock decision for the running example's product catalogue:
# s34_orchestrator.py — run standalone: python3 s34_orchestrator.py
"""Orchestrator-workers over ScriptedModel. Real output."""
import asyncio
from workflows import ScriptedModel, SubTask, orchestrate
async def main() -> None:
model = ScriptedModel([
# 1. planner → Plan
{"tasks": [
{"id": "sales", "title": "Recent sales velocity",
"instructions": "Report units sold per week for SKU KB-77 "
"over the last 8 weeks from the sales table."},
{"id": "supplier", "title": "Supplier lead time",
"instructions": "Report the current lead time and minimum "
"order quantity for supplier SUP-12."},
{"id": "returns", "title": "Return rate",
"instructions": "Report the 90-day return rate for SKU KB-77 "
"and the top return reason."},
]},
# 2-4. three workers → text each
"KB-77 sold 140/132/158/171/165/190/205/218 units/week, rising.",
"SUP-12 lead time is 21 days; MOQ is 500 units.",
"Return rate 4.1%; top reason: 'key chatter' (37% of returns).",
# 5. synthesizer → final answer
"Recommendation: restock 800 units of KB-77 now. Demand is "
"rising ~6%/week and lead time is 21 days; 800 covers ~3.7 weeks "
"of current velocity and clears the 500-unit MOQ. Watch the 4.1% return rate — "
"the 'key chatter' complaints suggest a batch QC check on arrival.",
])
async def worker(task: SubTask):
return await model(
[{"role": "user", "content": task.instructions}],
name=f"worker:{task.id}")
answer, plan, results = await orchestrate(
model, "Decide whether to restock SKU KB-77 and how much.",
worker, max_workers=3)
print("plan:", [t.id for t in plan.tasks])
print("answer:", answer)
asyncio.run(main()){"seq": 1, ..., "step": "planner", "ok": true, "detail": "3 tasks: sales, supplier, returns", ...}
{"seq": 2, ..., "step": "worker:sales", "ok": true, "detail": "Recent sales velocity", ...}
{"seq": 3, ..., "step": "worker:supplier", "ok": true, "detail": "Supplier lead time", ...}
{"seq": 4, ..., "step": "worker:returns", "ok": true, "detail": "Return rate", ...}
{"seq": 5, ..., "step": "synthesizer", "ok": true, "detail": "3 worker results", ...}
plan: ['sales', 'supplier', 'returns']
answer: Recommendation: restock 800 units of KB-77 now. ...Where's the workflow/agent line here? This looks agentic — the model chose the subtasks. But it's a workflow by Anthropic's definition: the orchestrator decomposes once, workers are bounded single calls, and your code owns the shape (plan → bounded fan-out → synthesis). Nothing loops back to ask "what next?" An agent would let a worker decide it needs another lookup and go get it — that's 08A.2's loop, and it's the rung above.
Strengths: handles tasks whose decomposition depends on the input ("research X" — you can't enumerate the searches in advance); parallel workers cut wall-clock latency; each worker gets a clean, focused context (context isolation — 04.7 and 02.7). Weaknesses: the planner can hallucinate subtasks, miss coverage, or duplicate work; synthesis can drop or contradict worker findings; cost is planner + N workers + synthesis — typically 1.5–3× a chain for the same information. Anthropic's production data point: their research system's multi-agent runs used ~15× the tokens of a chat — the pattern earns its cost only when parallelism or context isolation genuinely helps. Failure modes: empty/degenerate plan (gate it: require 2–6 tasks, reject overlap); worker exception → lands in results as {"error": ...} and the synthesizer is told to flag it — partial synthesis by default, hard abort if you inspect and reject; synthesis ignoring a worker. Evaluation idea: measure coverage (did the plan address the goal?) and synthesis fidelity (are claims traceable to a worker result?) separately — they fail independently.
3.5 Evaluator-optimizer#
The pattern: one model call generates, another evaluates and feeds back, in a loop until a quality bar is met or a stop criterion fires. Anthropic's fit test: "LLM responses can be demonstrably improved when a human articulates their feedback" and "the LLM can provide such feedback." Translation quality, iterative search, and draft-polish loops are the canonical cases.
flowchart LR
T["task"] --> G["generator call → draft"]
G --> E["evaluator call<br/>→ Verdict schema"]
E --> D{"passed and<br/>score ≥ bar?"}
D -->|"yes"| OUT["return draft"]
D -->|"no, rounds left"| R["reviser call<br/>draft + feedback → new draft"]
R --> E
D -->|"no, out of rounds"| BEST["return best draft<br/>+ flag: not converged"]# workflows.py (continued) — evaluator-optimizer. Pure-local.
class Verdict(BaseModel):
"""The critic's structured verdict. `passed` is the gate; `score`
and `feedback` drive the next revision."""
passed: bool
score: int = Field(ge=1, le=10)
feedback: str = Field(description="Specific, actionable critique")
class OptimizeResult(BaseModel):
draft: str
verdict: Verdict
rounds: int
converged: bool = Field(description="True only if the bar was met")
async def evaluator_optimizer(
call_model: CallModel,
draft_messages: list[Message],
critique_messages: Callable[[str], list[Message]],
revise_messages: Callable[[str, Verdict], list[Message]],
*,
max_rounds: int = 3,
min_score: int = 8,
tracer: Tracer | None = None,
) -> OptimizeResult:
"""Generate → critique → revise until the bar is met or rounds run out.
Stop criteria, in order: `passed and score >= min_score` (converged),
`max_rounds` exhausted (return the best-scoring draft, flagged), and
a plateau — two consecutive failed verdicts whose scores didn't
improve, which means another revision is likely to churn.
"""
if max_rounds < 1:
raise ValueError("max_rounds must be at least 1")
tracer = tracer or Tracer()
t0 = time.perf_counter()
draft = await call_model(draft_messages, name="generator")
assert isinstance(draft, str)
tracer.record("generator", ok=True, detail=f"{len(draft)} chars",
elapsed_ms=(time.perf_counter() - t0) * 1000)
best_draft, best_score, best_verdict = draft, -1, None
prev_score = -1
for round_no in range(1, max_rounds + 1):
verdict = await call_model(critique_messages(draft),
schema=Verdict, name="evaluator")
assert isinstance(verdict, Verdict)
tracer.record(f"evaluate:r{round_no}", ok=verdict.passed,
detail=f"score={verdict.score}")
if verdict.score > best_score:
best_draft, best_score, best_verdict = draft, verdict.score, verdict
if verdict.passed and verdict.score >= min_score:
return OptimizeResult(draft=draft, verdict=verdict,
rounds=round_no, converged=True)
plateau = (not verdict.passed and verdict.score <= prev_score
and round_no > 1)
prev_score = verdict.score
if round_no == max_rounds or plateau:
break
t0 = time.perf_counter()
revised = await call_model(revise_messages(draft, verdict),
name=f"reviser:r{round_no}")
assert isinstance(revised, str)
tracer.record(f"reviser:r{round_no}", ok=True,
detail=f"{len(revised)} chars",
elapsed_ms=(time.perf_counter() - t0) * 1000)
draft = revised
return OptimizeResult(draft=best_draft, verdict=best_verdict,
rounds=round_no, converged=False)Example — polish a refund-decline email (the running example) until the critic passes it:
# s35_evaluator.py — run standalone: python3 s35_evaluator.py
"""Evaluator-optimizer over ScriptedModel. Real output."""
import asyncio
from workflows import ScriptedModel, Verdict, evaluator_optimizer
async def main() -> None:
model = ScriptedModel([
# 1. generator → draft v1
"Your refund request was denied. Policy says no refunds after 30 days.",
# 2. evaluator → verdict on v1 (too blunt)
{"passed": False, "score": 4,
"feedback": "Too blunt; lead with empathy, explain the policy "
"reason, offer the exchange alternative."},
# 3. reviser → draft v2
"Hi Sam, thanks for reaching out. I've reviewed your refund "
"request for order A-1042 — unfortunately it's just past our "
"30-day window. I'd be glad to exchange it for another model "
"instead; want me to set that up?",
# 4. evaluator → verdict on v2 (passes)
{"passed": True, "score": 9,
"feedback": "Empathetic, explains the policy, offers an "
"alternative. Ship it."},
])
def critique(draft: str):
return [
{"role": "system", "content":
"You are a support-quality editor. Score 1-10 and say pass "
"only if the reply is empathetic, accurate and offers a "
"path forward."},
{"role": "user", "content": draft},
]
def revise(draft: str, verdict: Verdict):
return [
{"role": "system", "content":
"Rewrite the reply to fix the editor's feedback. Keep it "
"short and warm."},
{"role": "user", "content":
f"Draft:\n{draft}\n\nFeedback:\n{verdict.feedback}"},
]
result = await evaluator_optimizer(
model,
[{"role": "user", "content":
"Write a reply declining a refund for order A-1042 (31 days old)."}],
critique, revise, max_rounds=3, min_score=8)
print("converged:", result.converged, "| rounds:", result.rounds)
print("final:\n", result.draft)
asyncio.run(main()){"seq": 1, ..., "step": "generator", "ok": true, "detail": "69 chars", ...}
{"seq": 2, ..., "step": "evaluate:r1", "ok": false, "detail": "score=4", ...}
{"seq": 3, ..., "step": "reviser:r1", "ok": true, "detail": "211 chars", ...}
{"seq": 4, ..., "step": "evaluate:r2", "ok": true, "detail": "score=9", ...}
converged: True | rounds: 2
final:
Hi Sam, thanks for reaching out. ...Strengths: quality improves measurably per round; the critic's feedback is explicit and logged; bounded by max_rounds so cost is capped at 2×max_rounds calls (one generation, max_rounds critiques, max_rounds − 1 revisions). Weaknesses: the critic can be wrong — a bad rubric makes every draft worse ("reflection loops that make answers worse" is a named failure mode in 08A.10); each round resends the draft, so long documents get expensive fast; convergence isn't guaranteed, hence converged=False + best-effort return rather than an exception. Cost/latency: up to 2×max_rounds calls (1 generation + max_rounds critiques + max_rounds − 1 revisions), sequential — the most expensive bounded pattern here. Failure modes: critic and generator share the same blind spots (same model → correlated errors; use a different model or a rubric for the critic); oscillation between two drafts; score inflation. Evaluation idea: hold out a set of drafts, run the loop, and measure whether round-2 drafts actually beat round-1 on a separate judge — you're testing the loop, not trusting the critic (Module 10A).
3.6 Map-reduce over documents#
The pattern: split a large input into pieces, process each independently ("map"), then combine the partial results ("reduce"). For documents that exceed the context window or are too costly to send whole, this is how you get an answer over all of them. Chunking strategy itself is Module 05's job and retrieval-over-chunks is Module 07's; this lesson owns only the orchestration shape.
flowchart TB
DOC["document set"] --> C["chunk / select pieces"]
C --> M1["map: piece 1 → partial"] & M2["map: piece 2 → partial"] & M3["map: piece N → partial"]
M1 & M2 & M3 --> R1["reduce: merge partials<br/>(tree if too many)"]
R1 --> R2["final reduce → answer"]# workflows.py (continued) — map-reduce. Pure-local.
async def map_reduce(
call_model: CallModel,
items: list[Any],
map_step: Callable[[Any], Any],
reduce_messages: Callable[[list[Any]], list[Message]],
*,
map_concurrency: int = 4,
reduce_batch: int = 8,
tracer: Tracer | None = None,
) -> Any:
"""Map `items` through `map_step`, then reduce partials to one answer.
`map_step(item)` is injected — usually a prompt_chain or a single
call_model call producing a partial result. `reduce_batch` controls a
*tree* reduce: if partials exceed it, they're reduced in groups first,
so no single call ever sees more than `reduce_batch` partials (which
matters when partials are long — the reduce call has its own context
limit). Reduce groups share the map semaphore, so the whole run never
exceeds `map_concurrency` in-flight model calls. An empty `items`
returns `[]` without spending a model call.
"""
if reduce_batch < 2 or map_concurrency < 1: # batch 1 would never shrink the list
raise ValueError("reduce_batch must be >= 2 and map_concurrency >= 1")
tracer = tracer or Tracer()
if not items:
tracer.record("map-reduce", ok=True, detail="no items — skipped")
return []
sem = asyncio.Semaphore(map_concurrency)
async def one(item: Any, idx: int):
async with sem:
t0 = time.perf_counter()
partial = await _maybe_await(map_step(item))
tracer.record(f"map:{idx}", ok=True,
elapsed_ms=(time.perf_counter() - t0) * 1000)
return partial
partials = list(await asyncio.gather(*(one(it, i) for i, it in enumerate(items))))
level = 0
while len(partials) > reduce_batch:
groups = [partials[i:i + reduce_batch] for i in range(0, len(partials), reduce_batch)]
async def reduce_group(group: list[Any], name: str):
async with sem:
t0 = time.perf_counter()
result = await call_model(reduce_messages(group), name=name)
tracer.record(name, ok=True, detail=f"{len(group)} partials",
elapsed_ms=(time.perf_counter() - t0) * 1000)
return result
partials = list(await asyncio.gather(*(
reduce_group(g, f"reduce:l{level}:{gi}")
for gi, g in enumerate(groups)
)))
level += 1
t0 = time.perf_counter()
final = await call_model(reduce_messages(partials), name="reduce:final")
tracer.record("reduce:final", ok=True, detail=f"{len(partials)} partials",
elapsed_ms=(time.perf_counter() - t0) * 1000)
return finalExample — summarise meeting notes across a quarter (each note is a "document"):
# s36_map_reduce.py — run standalone: python3 s36_map_reduce.py
"""Map-reduce over ScriptedModel. Real output."""
import asyncio
from workflows import ScriptedModel, map_reduce
async def main() -> None:
notes = [
{"week": 1, "text": "Kickoff: Q3 targets agreed; hiring frozen."},
{"week": 2, "text": "Launch slipped 2 weeks; support hiring approved."},
{"week": 3, "text": "Beta feedback positive; pricing test starts."},
{"week": 4, "text": "Pricing test flat; decided to hold list price."},
]
async def map_note(note):
return await model(
[{"role": "user", "content":
f"Summarise this week's notes in one sentence, preserving "
f"decisions and dates: {note['text']}"}],
name=f"map:w{note['week']}")
def reduce_msgs(partials):
return [
{"role": "system", "content":
"Merge these weekly summaries into one quarterly summary. "
"Keep decisions, dates and owners; drop repetition."},
{"role": "user", "content": "\n".join(f"- {p}" for p in partials)},
]
model = ScriptedModel([
"W1: Q3 targets agreed; hiring frozen.",
"W2: Launch slipped 2 weeks; support hiring approved.",
"W3: Beta positive; pricing test starts.",
"W4: Pricing test flat; list price held.",
"Q3 summary: targets set, launch slipped 2 weeks with support "
"hiring approved, beta positive, pricing held at list.",
])
answer = await map_reduce(model, notes, map_note, reduce_msgs)
print("quarterly:", answer)
asyncio.run(main())Output (real — ScriptedModel replay; trace lines abbreviated — map:N is the item's index, the week-named calls are the call_model name kwarg):
{"seq": 1, ..., "step": "map:0", "ok": true, ...}
{"seq": 2, ..., "step": "map:1", "ok": true, ...}
{"seq": 3, ..., "step": "map:2", "ok": true, ...}
{"seq": 4, ..., "step": "map:3", "ok": true, ...}
{"seq": 5, ..., "step": "reduce:final", "ok": true, "detail": "4 partials", ...}
quarterly: Q3 summary: targets set, launch slipped 2 weeks with support hiring approved, beta positive, pricing held at list.Strengths: scales to inputs far beyond one context window; map calls are embarrassingly parallel; partial results are inspectable (you can debug one chunk without rerunning all). Weaknesses: the reduce step is a lossy bottleneck — details that don't survive the partial summaries are gone; naive equal-size chunking can split a fact across a boundary (05.6 owns the fix); cost ≈ sum over all chunks + reduces — for huge corpora, retrieval-first (only map the relevant chunks) is usually cheaper than map-everything (Module 07). Cost/latency: latency ≈ slowest map + reduce depth × reduce latency; cost ~ linear in input size. Failure modes: a map step returns empty/garbage → reduce propagates it; order-dependent tasks break under reordering (map-reduce assumes independence — verify before using); tree-reduce depth adds calls. Evaluation idea: compare map-reduce output against the same model answering with full context on inputs that do fit — measure what the compression loses.
3.7 Human-in-the-loop checkpoints#
The pattern: pause the workflow at defined points for a person to approve, edit or reject — then resume. Anthropic's agent description includes "pausing for human feedback at checkpoints"; OpenAI's guide lists human escalation as a guardrail pattern; Google's guidance says "keep a human in the loop." In workflow terms, a checkpoint is a step whose output isn't committed until a human signs off.
sequenceDiagram
participant W as Workflow
participant H as Human approver
W->>W: draft step produces proposal
W->>H: approval request (proposal + context)
H-->>W: approve / edit / reject
alt approve
W->>W: commit proposal, continue
else edit
W->>W: commit edited version, continue
else reject
W->>W: abort or route to fallback
end# workflows.py (continued) — human-in-the-loop checkpoint. Pure-local.
from typing import Literal
class Decision(BaseModel):
"""What the approver returns. `edit` carries the corrected text."""
action: Literal["approve", "edit", "reject"]
edited: str | None = None
note: str = ""
class Rejected(RuntimeError):
"""A checkpoint was rejected; carries the human's note."""
async def checkpoint(
produce: Callable[[], Any],
approver: Callable[[str, Any], Any],
*,
step_name: str,
render: Callable[[Any], str] | None = None,
tracer: Tracer | None = None,
) -> Any:
"""Run `produce`, show its output to `approver`, commit or abort.
`approver(rendered_proposal, raw)` may be sync or async — in
production it's an API call to your approval queue, an email link, a
chat message; in tests it's a function returning a Decision. The
checkpoint is deliberately *outside* the model loop: the human sees
the proposal, not the model's reasoning. Both halves are traced —
`{step_name}:produce` for building the proposal, `checkpoint:{step_name}`
for the human's decision.
"""
tracer = tracer or Tracer()
t0 = time.perf_counter()
proposal = await _maybe_await(produce())
tracer.record(f"{step_name}:produce", ok=True,
detail=type(proposal).__name__,
elapsed_ms=(time.perf_counter() - t0) * 1000)
show = render(proposal) if render else str(proposal)
decision = await _maybe_await(approver(show, proposal))
assert isinstance(decision, Decision)
tracer.record(f"checkpoint:{step_name}", ok=decision.action != "reject",
detail=f"{decision.action} — {decision.note}")
if decision.action == "reject":
raise Rejected(f"{step_name}: {decision.note or 'rejected by approver'}")
if decision.action == "edit":
assert decision.edited is not None
return decision.edited
return proposalExample — approve-then-send for the refund flow:
# s37_hitl.py — run standalone: python3 s37_hitl.py
"""Human-in-the-loop checkpoint over ScriptedModel. Real output."""
import asyncio
from workflows import Decision, ScriptedModel, checkpoint
async def main() -> None:
model = ScriptedModel([
# the drafted refund action the human will approve
"Issue a full refund of USD 189.00 to the card on file for "
"order A-1042, reason: item arrived damaged.",
])
async def approver(rendered, raw):
# In production this is your approval queue / email / chat UI.
# Here it's a function — which is exactly what makes it testable.
print("\n--- APPROVAL REQUEST ---\n" + rendered + "\n------------------------")
return Decision(action="edit",
edited="Issue a partial refund of USD 120.00 ...",
note="policy caps damage refunds at cost price")
committed = await checkpoint(
lambda: model([{"role": "user", "content":
"Draft the refund action for order A-1042."}],
name="draft-refund"),
approver, step_name="refund-approval",
render=lambda p: f"PROPOSED ACTION:\n{p}")
print("\ncommitted:", committed)
asyncio.run(main())Output (real — ScriptedModel + the scripted approver; trace_id is shortened to ... and elapsed_ms varies by machine; json.dumps writes the em dash as \u2014):
{"seq": 1, "trace_id": "...", "step": "refund-approval:produce", "ok": true, "detail": "str", "elapsed_ms": 0.0}
--- APPROVAL REQUEST ---
PROPOSED ACTION:
Issue a full refund of USD 189.00 ...
------------------------
{"seq": 2, "trace_id": "...", "step": "checkpoint:refund-approval", "ok": true, "detail": "edit \u2014 policy caps damage refunds at cost price", "elapsed_ms": 0.0}
committed: Issue a partial refund of USD 120.00 ...The production version is a pause, not a function call. In a real system the approver isn't an in-process function — the workflow suspends, the request goes to a queue/email/chat, and the run resumes hours or days later with the decision. That requires the durable-execution machinery of Part 6: the state up to the checkpoint must be serialisable and the resume point recorded. Lesson 08A.10 builds the full approval pattern for agents; this checkpoint primitive is the workflow-side version, and it's deliberately identical in spirit so the two compose.
Strengths: the strongest safety-per-complexity ratio in the whole pattern set — you get human judgement exactly where stakes are highest without giving up automation elsewhere; approve/edit/reject covers the realistic outcomes; trivially testable (the approver is just a function). Weaknesses: latency becomes human latency (hours, not milliseconds) — design for it: async approval, clear SLA, expiry; approver fatigue is real (too many checkpoints → rubber-stamping — Module 12 owns the guardrail design); the rendered proposal must be complete enough to judge — a truncated context produces bad approvals. Failure modes: approval never arrives (timeout → escalate or abort, never silently proceed); edited text breaks downstream assumptions (re-validate after edit); approver approves what they didn't read (UX problem, not code). Evaluation idea: track approval edit-rate and reject-rate per step — a checkpoint that's always approved unchanged is probably placed too early or too late.
3.8 Fallback and escalation chains#
The pattern: wrap any step — or the whole workflow — in an ordered list of alternatives tried in sequence: cheaper model first, stronger model on failure; provider A, provider B on outage; agent first, deterministic workflow as the safety net. 03.11's fallback chain owns the model-level version; this is the workflow-level composition.
flowchart LR
REQ["request"] --> M1["try: cheap model /<br/>primary path"]
M1 -->|"success"| OUT["result"]
M1 -->|"retryable failure"| M2["try: stronger model /<br/>secondary path"]
M2 -->|"success"| OUT
M2 -->|"failure"| M3["try: fallback workflow<br/>(simpler, deterministic)"]
M3 -->|"success"| OUT
M3 -->|"failure"| H["human / error to caller"]# workflows.py (continued) — fallback and escalation chains. Pure-local.
class AllFailed(RuntimeError):
"""Every alternative in a fallback chain failed."""
def __init__(self, errors: list[Exception]):
super().__init__(f"all {len(errors)} alternatives failed")
self.errors = errors
async def fallback_chain(
alternatives: list[Callable[[], Any]],
*,
names: list[str] | None = None,
retryable: Callable[[Exception], bool] | None = None,
tracer: Tracer | None = None,
) -> Any:
"""Try each alternative in order; return the first success.
Each alternative is a thunk — `lambda: call_model(...)`, a whole
workflow, or a provider-specific adapter — so the chain composes at
any granularity: around one call, one step, or the entire run.
`retryable(exc)` decides whether a failure moves to the next
alternative; default is "any exception" — pass 03.8's classifier
([4.4](../03-llm-apis/08-errors-and-retries.md#44-a-classifier-for-all-four-providers))
in production so a 400 doesn't burn the fallback budget.
"""
tracer = tracer or Tracer()
is_retryable = retryable or (lambda exc: True)
errors: list[Exception] = []
for i, alt in enumerate(alternatives):
label = names[i] if names else f"alt{i}"
t0 = time.perf_counter()
try:
result = await _maybe_await(alt())
tracer.record(f"fallback:{label}", ok=True,
detail=f"succeeded after {i} failure(s)",
elapsed_ms=(time.perf_counter() - t0) * 1000)
return result
except Exception as exc:
tracer.record(f"fallback:{label}", ok=False,
detail=type(exc).__name__,
elapsed_ms=(time.perf_counter() - t0) * 1000)
errors.append(exc)
if not is_retryable(exc):
raise
raise AllFailed(errors)Example — escalate a failing draft through stronger options, ending at a human:
# s38_fallback.py — run standalone: python3 s38_fallback.py
"""Fallback chain over ScriptedModel. Real output."""
import asyncio
from workflows import ScriptedModel, fallback_chain
async def main() -> None:
# A ScriptedModel with no scripted replies always raises — a handy
# stand-in for "the primary provider is down".
down = ScriptedModel([])
strong = ScriptedModel([
"Draft reply (strong model): I've looked into order A-1042 — "
"it shipped Tuesday and the carrier shows delivery Thursday. "
"Here's the tracking link: ...",
])
async def primary():
return await down([{"role": "user", "content": "draft reply"}],
name="primary")
async def escalated():
return await strong([{"role": "user", "content": "draft reply"}],
name="escalated")
async def human_queue():
return "QUEUED FOR HUMAN AGENT: all model paths unavailable"
result = await fallback_chain(
[primary, escalated, human_queue],
names=["cheap-model", "strong-model", "human"],
retryable=lambda e: "scripted replies" in str(e))
print("result:", result)
asyncio.run(main()){"seq": 1, ..., "step": "fallback:cheap-model", "ok": false, "detail": "RuntimeError", ...}
{"seq": 2, ..., "step": "fallback:strong-model", "ok": true, "detail": "succeeded after 1 failure(s)", ...}
result: Draft reply (strong model): I've looked into order A-1042 — ...Strengths: converts hard failures into graceful degradation; the "fallback to a simpler workflow" rung is the key agent-safety pattern — when the agent can't finish, a deterministic chain still answers; cost-aware (cheap first). Weaknesses: each alternative may have different semantics — the caller must handle "which one answered?" (return a tuple or tag the result); fallbacks can mask systemic problems (alert on fallback rate, not just errors — 11A); retryable classification is subtle (03.8 owns it). Cost/latency: worst case = sum of all alternatives' latency; expected case ≈ primary. Failure modes: fallback succeeds with a worse answer silently (tag results by source); cascading fallbacks all hitting the same rate limit; non-idempotent side effects retried (a "send email" tool that partially succeeded then fell back → duplicate email — idempotency keys, 08A.6/03.5). Evaluation idea: measure fallback rate and fallback-quality gap separately; a fallback that fires 20% of the time is a capacity problem, not a resilience feature.
Part 4: When to use an agent — and when not to#
4.1 The agent loop, in one paragraph#
An agent is the rung where the model, not your code, decides what happens next: it calls the model with tools available, the model requests tool calls, your code executes them and returns results, and the loop repeats until the model produces a final answer or a budget/stop condition fires (08A.2 builds it; the module's working definition is "an LLM using tools in a loop to achieve a goal with the model controlling the flow"). Every workflow pattern above is a special case of control you could hand to a loop — the question is whether the model's judgement is needed at every step or only at a few.
4.2 The conditions that favour an agent#
All five of Anthropic's criteria, plus OpenAI's and Google's, point the same way:
| Condition | Why it matters | Source guidance |
|---|---|---|
| The number of steps can't be predicted | If you can't enumerate the path, you can't write the workflow. Anthropic: agents suit "open-ended problems where it's difficult or impossible to predict the required number of steps." | Anthropic, Building effective agents |
| A tool-rich environment | The agent's value is choosing among many possible actions; with one or two tools, a chain is almost always enough | OpenAI: agent "dynamically selects the appropriate tools depending on the workflow's current state" |
| Feedback from the environment | Each tool result is ground truth the model reacts to — test failures, search hits, API errors. "During execution, it's crucial for the agents to gain 'ground truth' from the environment at each step" | Anthropic |
| Tolerance for latency, cost and variance | Runs vary in length and path; you accept that for the capability | Anthropic: agents "trade latency and cost for better task performance" |
| You can evaluate and sandbox | "We recommend extensive testing in sandboxed environments, along with the appropriate guardrails" | Anthropic |
| The task resisted deterministic automation | Complex judgement, unmaintainable rulesets, heavy unstructured data | OpenAI, A practical guide |
| The problem is open-ended and knowledge-intensive | "AI agents are effective for applications that solve open-ended problems" | Google Cloud Architecture Center |
The common thread: agents earn their keep where the path is genuinely unknowable in advance and the environment gives the model something to react to. Coding agents and research agents are the canonical fits — you can't predict which files need editing or which sources matter.
4.3 The conditions that rule an agent out#
Equally important, and where most "we need an agent" requests actually land:
- The task is really a workflow in disguise. If you can name the steps — even vaguely — write them down. "Classify → look up → draft → approve" is a chain, not an agent. Anthropic: "This might mean not building agentic systems at all."
- Tight latency or cost budget. A workflow's cost is known before you ship; an agent's isn't (Part 5). Customer-facing paths with p99 latency targets usually can't absorb a 12-turn loop.
- High-stakes irreversible actions without a human in the loop. Anthropic lists "higher costs, and the potential for compounding errors" as the agent's price; OpenAI's guardrails chapter exists precisely because agents act. If a wrong trajectory sends emails or moves money, you need 3.7 checkpoints and 08A.14's policy layer — which, note, are the same machinery workflows use.
- No way to verify the outcome. If you can't tell success from failure, you can't tell a good run from a bad one — and an agent's variance means "it worked in the demo" proves little. OpenAI's first agent criterion is that the LLM "recognizes when a workflow is complete"; if nothing can check completion, the loop has no floor.
- No sandbox or audit requirement you can meet. Agents take actions; actions need containment (08A.15) and audit trails.
- Regulated or deterministic-required domains. Where a rules engine, a workflow engine or plain code is auditable end-to-end, substituting a model-directed loop is a governance decision, not an engineering one.
4.4 The hybrid reality#
The honest answer for most production systems is both: a workflow spine with agent islands. A support assistant is a chain (classify → retrieve → draft → approve) with an agent loop only inside the "investigate this incident" route, where the step count genuinely can't be known. LangChain's framing is the same: "most agentic systems in production are a combination of workflows and agents." The workflow gives you the predictable 90%; the agent handles the open-ended 10%; and the boundaries between them are exactly the call_model seams this lesson's code is built on — swap a chain step for an orchestrate() call or an agent loop without touching the rest.
Part 5: The reliability maths#
Deep-dive
This part is short on prose and heavy on arithmetic, because the arithmetic is the argument for starting simple.
5.1 Compounding error rates#
Every model call has some probability p of producing an acceptable result. A chain of n steps succeeds only if every step succeeds, so the chain's success rate is pⁿ — it compounds downward, geometrically.
Running the numbers. Save this as reliability_math.py and run python3 reliability_math.py: it needs no packages and no key, and it prints the three tables that appear in 5.1, 5.2 and 5.3.
# reliability_math.py: the arithmetic behind Part 5 (pure Python, no packages, no network)
# 5.1 A chain of n steps succeeds only if every step does: p ** n
print("=== 5.1 Compounding error rates: p^n ===")
steps = (1, 3, 5, 10, 20)
print(" per-step p | " + " | ".join(f"{n:>2}-step".rjust(9) for n in steps))
for p in (0.99, 0.97, 0.95, 0.90, 0.80):
print(f" {p:>10.2f} | " + " | ".join(f"{p ** n:>9.1%}" for n in steps))
# 5.2 A 12-turn loop vs one call: 2,000-token prompt, 400-token answer;
# each loop turn adds ~800 tokens to the history and writes ~400 tokens
single = 2_000 + 400
turns, add_per_turn, out_per_turn = 12, 800, 400
resent_input = sum(2_000 + add_per_turn * k for k in range(turns)) # turn k resends 2,000 + 800*k
output = turns * out_per_turn
loop = resent_input + output
print("\n=== 5.2 Cost multiplication: a 12-turn agent loop ===")
print(f"single call : ~{single:,} tokens")
print(f"{turns}-turn loop: ~{loop:,} tokens ({loop / single:.1f}x the single call)")
print(f" input tokens resent each turn: {resent_input:,}; output: {output:,}")
# price ratio if output tokens cost 5x input tokens
print(f" price ratio at 5:1 output:input = {(resent_input + 5 * output) / (2_000 + 5 * 400):.1f}x")
# 5.3 A gate catching fraction g of failures, then one retry at the same p
p = 0.95
print("\n=== 5.3 What a verification gate buys (per-step p = 0.95) ===")
print(" gate recall | q per step | 5-step chain | calls/step")
for g in (0.0, 0.5, 0.8, 1.0):
q = p + (1 - p) * g * p
calls = 1 + (1 - p) * g # a retry happens only when the gate caught a failure
print(f" {g:.2f} | {q:.3f} | {q ** 5:.1%} | {calls:.2f}")=== 5.1 Compounding error rates: p^n ===
per-step p | 1-step | 3-step | 5-step | 10-step | 20-step
0.99 | 99.0% | 97.0% | 95.1% | 90.4% | 81.8%
0.97 | 97.0% | 91.3% | 85.9% | 73.7% | 54.4%
0.95 | 95.0% | 85.7% | 77.4% | 59.9% | 35.8%
0.90 | 90.0% | 72.9% | 59.0% | 34.9% | 12.2%
0.80 | 80.0% | 51.2% | 32.8% | 10.7% | 1.2%Read it as an engineer, not a mathematician: a model that's "95% reliable per call" — which sounds excellent — gives you a 36% success rate on a 20-step agent run. At 90% per step, a 10-step run succeeds barely a third of the time. This is why "it worked in testing" is meaningless for agents: you weren't testing 20-step trajectories, you were testing the ones that happened to go well.
Two consequences:
- Fewer steps is a reliability feature, not just a cost feature. Every step you keep in deterministic code removes a
pfrom the product. Thelookupstep in 3.1 isn't just free — it's perfectly reliable,p = 1.0, and it can't be prompted wrong. - Step count is a design variable you control in workflows and don't control in agents. A chain's
nis fixed at ship time; an agent'snis whatever the model decides — which is why Part 4's budgets (max steps, max tokens, max cost) aren't optional.
5.2 Cost multiplication in loops#
The same compounding hits your wallet. An agent loop resends the growing conversation every turn — tool results accumulate in context (04.7 owns the mechanics). Illustrative arithmetic (the assumptions are stated, the shape is what matters): a single call has a 2,000-token prompt and a 400-token answer (2,400 tokens). A 12-turn loop starts from the same prompt, adds ~800 tokens to the history per turn (a tool result plus the model's last message) and emits ~400 output tokens per turn, so it uses roughly 34× the tokens of the single call — and that's before retries, fallbacks, or sub-agents. (The price ratio is somewhat lower, about 25×, if output tokens cost 5× input tokens, because most of the extra volume is the cheaper resent input; the point stands either way.) Anthropic's production measurement agrees in spirit: agents ~4× chat tokens, multi-agent systems ~15× (How we built our multi-agent research system, June 2025).
Output of the second section (real — pure-Python arithmetic on the stated assumptions, no API calls):
=== 5.2 Cost multiplication: a 12-turn agent loop ===
single call : ~2,400 tokens
12-turn loop: ~81,600 tokens (34.0x the single call)
input tokens resent each turn: 76,800; output: 4,800
price ratio at 5:1 output:input = 25.2xThe workflow equivalent — a 5-step chain — is exactly 5 calls with known sizes: you can count the tokens before you ship (03.7) and put a hard budget on the run. That's the difference between a cost centre you forecast and one you discover on the invoice.
5.3 What verification gates actually buy#
A gate doesn't make a step perfect — it converts silent errors into caught ones. Model a step with per-attempt success p, a gate that catches fraction g of failures, and one retry at the same p:
q = p + (1 - p) · g · p per-step success after the gateAt p = 0.95, an 80%-recall gate lifts the effective per-step success to ~0.988 — and a 5-step chain from 77% to 94%, for about 4% more calls:
=== 5.3 What a verification gate buys (per-step p = 0.95) ===
gate recall | q per step | 5-step chain | calls/step
0.00 | 0.950 | 77.4% | 1.00
0.50 | 0.974 | 87.5% | 1.02
0.80 | 0.988 | 94.1% | 1.04
1.00 | 0.998 | 98.8% | 1.05The engineering reading: a cheap deterministic gate beats a more expensive model. Checking "does the draft contain the order ID" costs microseconds and catches a whole class of failure; upgrading the drafting model costs 10× per call and catches a different, smaller class. Put gates wherever the check is mechanical (schema validation, required fields, computed totals, forbidden strings) and spend model-judgement only where the check genuinely needs it (the evaluator-optimizer critic). And remember the gate itself can be wrong — a gate with low recall is security theatre; measure it.
5.4 Reliability over repeated runs#
One more piece of maths you'll meet again: pass@k (did any of k attempts succeed?) versus pass^k (did all k succeed — the reliability number). For agents, pass^k is the honest metric because production gives you one shot per user. 08A.14 defines both and builds the eval harness; the point here is that a workflow's pass^k is far easier to estimate because its trajectory is fixed.
Part 6: Durable and long-running workflows#
Deep-dive
Everything so far assumed the run finishes in seconds to minutes, in one process, with nobody waiting. Production disagrees: runs crash, deploys happen mid-run, humans take hours to approve, and jobs need to fire at 3 a.m. A durable workflow is one whose progress survives all of that — the execution state is persisted outside the process, so a run can pause, resume, retry a single step, or move machines without starting over.
6.1 Why in-memory steps aren't enough#
The prompt_chain in 3.1 keeps state in a Python dict. Three things break that:
- Process death. Deploy, OOM, crash — the dict is gone. Everything re-runs, including steps with side effects (a sent email gets sent again).
- Waiting. A human checkpoint (3.7) can take hours. You can't hold a request open that long; the run must suspend and resume later.
- Scale-out. Two workers can't share one in-memory dict; state must live somewhere both can reach.
6.2 The durability checklist#
Whatever engine you pick, the workflow needs these properties — this is the checklist to evaluate any option against:
| Property | What it means for an LLM workflow | How it's usually provided |
|---|---|---|
| State persistence | Every step's inputs and outputs serialisable to JSON (or better, a versioned format) | Checkpointer / event history / state store |
| Resumption | On restart, skip completed steps; re-run only from the failure point | Checkpoints after each step |
| Idempotency | Re-running a step with side effects (send, charge, write) doesn't duplicate them | Idempotency keys, upsert writes, "already done" checks (03.5, Part 7) |
| Step-level retries | A transient failure retries that step, not the whole run | Per-step retry policy with backoff (03.8) |
| Timeouts | Each model call and tool call bounded; a hung step can't hang the run | Per-step deadline + cancellation (03.3 for streams) |
| Scheduling | "Run this workflow daily / in 24h / when X happens" | Cron, delayed starts, event triggers |
| Queues | Work is dispatched to workers, not run inline in the request | Queue + worker pool (03.9) |
| Observability | Every step's model calls, tool calls, tokens, latency, trace_id recorded | The Tracer shape from 3.0, extended (03.10, 08A.14) |
| Versioning | Workflow code changes while runs are mid-flight: in-flight runs must finish on the definition they started with, not the new deploy | Engine versioning/patching APIs (Temporal's GetVersion/patching); hand-rolled runners like durable_runner.py have nothing — one more reason to use an engine |
6.3 A minimal durable runner (pure-local)#
Before naming engines, here's the concept in about 130 lines (the demo is the last 30): persist state and a done set after every step; on restart, skip what's done. This is the idea every engine implements — write it yourself only for learning or tiny jobs; use an engine for anything real.
# durable_runner.py — run standalone: python3 durable_runner.py
"""Minimal durable workflow runner over a JSON state file. Pure-local.
Concept demo, not production code: no retries, no timeouts, no
concurrency — those are what the engines in 6.4 add. The point is the
shape: state on disk, steps marked done, resume skips completed work.
Step results must be JSON-native (text, numbers, dicts, lists): save()
uses default=str, so a Pydantic result would be written as its repr and
a resumed run would read back a string where it expects a model.
"""
import asyncio
import json
import time
import uuid
from pathlib import Path
from workflows import (ChainStep, CallModel, GateFailed, Tracer,
_maybe_await) # reuse the step primitives
class DurableState:
"""JSON-file state: {run_id, state, done_steps}. Written atomically
(temp file + rename) after every step so a crash mid-write can't
corrupt it."""
def __init__(self, path: Path, run_id: str | None = None):
self.path = path
if path.exists():
data = json.loads(path.read_text())
self.run_id = data["run_id"]
self.state = data["state"]
self.done = set(data["done_steps"])
else:
self.run_id = run_id or uuid.uuid4().hex[:12]
self.state = {"input": {}, "_errors": []}
self.done = set()
def save(self) -> None:
tmp = self.path.with_suffix(".tmp")
tmp.write_text(json.dumps({
"run_id": self.run_id, "state": self.state,
"done_steps": sorted(self.done)}, default=str))
tmp.replace(self.path)
async def _run_one_step(call_model, step, state, tracer):
"""One ChainStep against the shared state — same logic as
prompt_chain's inner loop, but operating on the durable state dict
so earlier steps' outputs are visible to later build_messages."""
for attempt in range(1, step.max_attempts + 1):
t0 = time.perf_counter()
if step.fn is not None:
result = await _maybe_await(step.fn(state))
else:
result = await call_model(step.build_messages(state),
schema=step.schema, name=step.name)
elapsed = (time.perf_counter() - t0) * 1000
state[step.name] = result
reason = step.gate(result, state) if step.gate else None
tracer.record(step.name, ok=reason is None,
detail=reason or f"attempt {attempt}", elapsed_ms=elapsed)
if reason is None:
return
state.setdefault("_errors", []).append(
f"{step.name} attempt {attempt}: {reason}")
raise GateFailed(f"step '{step.name}' failed its gate")
async def run_durable(
call_model: CallModel,
steps: list[ChainStep],
state_path: Path,
task: dict,
) -> dict:
"""Run the chain durably: completed steps are skipped on resume."""
ds = DurableState(state_path)
if not ds.done:
ds.state["input"] = task
ds.save()
tracer = Tracer(ds.run_id)
for step in steps:
if step.name in ds.done:
tracer.record(step.name, ok=True, detail="skipped (done)")
continue
# Checkpoint between steps — a real engine checkpoints inside
# steps too, but between-step granularity is the 90% case.
# Lists are copied too: _errors is append-only by design, but a
# shallow copy would let a failed step's error entries leak back
# in through the "before" snapshot on rollback.
before = {k: (dict(v) if isinstance(v, dict)
else list(v) if isinstance(v, list) else v)
for k, v in ds.state.items()}
try:
await _run_one_step(call_model, step, ds.state, tracer)
ds.done.add(step.name)
ds.save()
tracer.record(step.name, ok=True, detail="completed")
except Exception:
ds.state.clear()
ds.state.update(before) # roll back this step's partial writes
ds.save()
raise
return ds.state
async def demo() -> None:
"""Show resume: run steps 1-2, 'crash', resume, finish."""
calls = []
class CountingModel:
async def __call__(self, messages, *, schema=None, name=None):
calls.append(name)
return f"result-of-{name}"
steps = [
ChainStep("extract", build_messages=lambda s: [{"role": "user", "content": "extract"}]),
ChainStep("analyse", build_messages=lambda s: [{"role": "user", "content": "analyse"}]),
ChainStep("report", build_messages=lambda s: [{"role": "user", "content": "report"}]),
]
path = Path("demo_run.json") # in the current folder; deleted first so the demo is repeatable
path.unlink(missing_ok=True)
# First run: kill it after two steps by limiting the step list.
await run_durable(CountingModel(), steps[:2], path, {"doc": "invoice.pdf"})
print("after first run, done:", sorted(json.loads(path.read_text())["done_steps"]))
# "Crash" and resume with the full step list: extract+analyse skip.
state = await run_durable(CountingModel(), steps, path, {"doc": "invoice.pdf"})
print("model calls total:", calls)
print("final keys:", sorted(k for k in state if not k.startswith("_")))
asyncio.run(demo()){"seq": 1, "trace_id": "...", "step": "extract", "ok": true, "detail": "attempt 1", "elapsed_ms": 0.0}
{"seq": 2, "trace_id": "...", "step": "extract", "ok": true, "detail": "completed", "elapsed_ms": 0.0}
{"seq": 3, "trace_id": "...", "step": "analyse", "ok": true, "detail": "attempt 1", "elapsed_ms": 0.0}
{"seq": 4, "trace_id": "...", "step": "analyse", "ok": true, "detail": "completed", "elapsed_ms": 0.0}
after first run, done: ['analyse', 'extract']
{"seq": 1, "trace_id": "...", "step": "extract", "ok": true, "detail": "skipped (done)", "elapsed_ms": 0.0}
{"seq": 2, "trace_id": "...", "step": "analyse", "ok": true, "detail": "skipped (done)", "elapsed_ms": 0.0}
{"seq": 3, "trace_id": "...", "step": "report", "ok": true, "detail": "attempt 1", "elapsed_ms": 0.0}
{"seq": 4, "trace_id": "...", "step": "report", "ok": true, "detail": "completed", "elapsed_ms": 0.0}
model calls total: ['extract', 'analyse', 'report']
final keys: ['analyse', 'extract', 'input', 'report']The demo's "crash" is simulated by running only the first two steps, then resuming with the full list: extract and analyse print skipped (done) and only report calls the model — model calls total shows each name exactly once. (In a real crash the process dies mid-step; the before snapshot rolls back that step's partial writes so a retry starts it clean.)
6.4 The engines: what exists (as of November 2026)#
You will not build durable execution yourself. Four families cover the space:
| Engine | What it is | Durability model | LLM fit | Version (PyPI, Nov 2026) |
|---|---|---|---|---|
| LangGraph (checkpointer) | Graph-state framework; InMemorySaver → SqliteSaver → PostgresSaver/AsyncPostgresSaver |
Checkpoint of graph state after each super-step; resume, time-travel, interrupts for HITL | Best fit for agent loops: pause/resume mid-trajectory, human interrupts are first-class (persistence docs, checkpointers) | langgraph 1.2.20 |
| Temporal | General durable-execution platform; workflow code is deterministic, state rebuilt from event history | Event sourcing: every step's result is an event; replay reconstructs state; activities retry individually | Strong for long-running business processes; Python SDK temporalio; heavier ops footprint (a Temporal server) |
temporalio 1.35.0 |
| Prefect | Python-native workflow orchestration | Flow-run state in a backend; task-level retries, caching, scheduling | Good middle ground: Pythonic decorators, less infra than Temporal | prefect 3.9.1 |
| Celery | The old guard: distributed task queue | Task acks + acks_late + task_reject_on_worker_lost; retries per task |
You build durability yourself on top (chords, canvases); most manual of the four | celery 5.7.0 |
The honest summary: LangGraph if your durable thing is an agent/graph; Temporal if it's a business process that must survive anything; Prefect for Python-native scheduled/data workflows; Celery if you already run it and accept building the semantics yourself. Other durable-execution engines with Python SDKs exist (for example DBOS, Restate and Inngest); they follow the same checklist above, so judge them with it. Module 05's ingestion pipelines lesson covers the data-pipeline side of the same decision; 08F.1 covers the framework-level view.
One durability problem sits above all of these: workflow versioning. You will deploy new code while runs are mid-flight, and an in-flight run must finish on the definition it started with — Temporal's versioning/patching APIs exist precisely for this, and LangGraph's checkpointer keys state to a graph you version yourself. durable_runner.py has no such concept: a resumed run silently picks up whatever step code is on disk now. For a demo that's fine; for production it's the difference between "resume" and "resume correctly after a deploy".
6.5 What durability does not solve#
- It doesn't make steps correct. A resumed run replays the same prompts; if step 3 was wrong, it resumes to a wrong step 4. Durability buys continuation, not correctness — that's Part 5's gates.
- It doesn't deduplicate model calls. A retried step that calls the model again gets a different answer (temperature > 0) or the same one (deterministic settings) — either way, your state machine must tolerate both. For side-effecting steps, idempotency is on you.
- It doesn't remove the need for budgets. A durable agent loop can still loop forever across resumes; max-steps/max-tokens/max-cost travel inside the state.
Part 7: The worked example — refund requests, three ways#
Same task, three architectures. The task: a customer writes in asking for a refund on order A-1042 (a USD 189.00 mechanical keyboard, delivered 31 days ago, reported damaged on arrival). The company policy: refunds within 30 days are automatic; damaged items get a replacement or full refund regardless of window; anything else needs a human.
7.1 As a single call#
The simplest thing that could possibly work: one prompt, one schema-constrained answer. The model sees the ticket and the policy and returns a structured decision your code executes.
# s71_single_call.py — run standalone: python3 s71_single_call.py
"""The refund task as ONE call. Real output via ScriptedModel."""
import asyncio
import json
from pydantic import BaseModel, Field
from workflows import ScriptedModel
POLICY = """Refund policy:
- Within 30 days of delivery: automatic refund on request.
- Damaged or defective items: replacement or full refund, any age.
- Everything else: escalate to a human agent."""
class RefundDecision(BaseModel):
action: str = Field(description="refund | replace | escalate")
amount: float | None = Field(default=None, description="USD amount")
reason: str
needs_human: bool
async def main() -> None:
model = ScriptedModel([
{"action": "refund", "amount": 189.00,
"reason": "item arrived damaged; policy allows full refund "
"regardless of the 30-day window",
"needs_human": False},
])
ticket = {"order_id": "A-1042", "item": "mechanical keyboard",
"total": 189.00, "delivered_days_ago": 31,
"issue": "arrived damaged"}
decision = await model(
[{"role": "system", "content": POLICY},
{"role": "user", "content": json.dumps(ticket)}],
schema=RefundDecision, name="refund-decision")
print("decision:", decision.model_dump())
print("model calls:", [c["name"] for c in model.calls])
asyncio.run(main())decision: {'action': 'refund', 'amount': 189.0, 'reason': 'item arrived damaged; policy allows full refund regardless of the 30-day window', 'needs_human': False}
model calls: ['refund-decision']Honest assessment: this works if the policy fits in the prompt and the decision is simple. It fails silently when the ticket needs data the prompt doesn't have (the actual order status, the customer's history) and when "damaged" needs verification — the model can't check the warehouse photo. One call = one shot at being right, p from Part 5 with n = 1.
7.2 As a workflow#
Same task, decomposed: classify the request, pull the order facts in code, apply the policy as a deterministic rule, draft the customer reply, gate it, and put the irreversible step behind a human checkpoint.
# s72_workflow.py — run standalone: python3 s72_workflow.py
"""The refund task as a prompt-chain workflow. Real output."""
import asyncio
import json
from typing import Literal
from pydantic import BaseModel, Field
from workflows import ChainStep, Decision, ScriptedModel, Tracer, checkpoint, prompt_chain
ORDERS = {"A-1042": {"item": "mechanical keyboard", "total": 189.00,
"delivered_days_ago": 31, "status": "delivered"}}
class RefundClass(BaseModel):
kind: Literal["refund", "replacement", "damage_claim", "other"]
confidence: float = Field(ge=0, le=1)
def _classify(state):
return [{"role": "system", "content":
"Classify the customer's request. JSON only."},
{"role": "user", "content": json.dumps(state["input"]["ticket"])}]
def _lookup(state):
return ORDERS.get(state["input"]["ticket"]["order_id"], {"found": False})
def _policy_check(state):
"""Deterministic — the policy is code, not a prompt."""
kind = state["classify"].kind
order = state["lookup"]
if order.get("found") is False: # unknown order: never auto-approve
return {"eligible": False, "route": "escalate", "cap": 0}
if kind == "damage_claim":
return {"eligible": True, "route": "full_refund",
"cap": order.get("total")}
if kind == "refund" and order.get("delivered_days_ago", 999) <= 30:
return {"eligible": True, "route": "refund", "cap": order.get("total")}
return {"eligible": False, "route": "escalate", "cap": 0}
def _draft(state):
return [{"role": "system", "content":
"Draft a one-paragraph reply. Use only the facts given."},
{"role": "user", "content": json.dumps({
"ticket": state["input"]["ticket"],
"class": state["classify"].model_dump(),
"policy": state["policy"],
})}]
def _mentions_amount(draft, state):
cap = state["policy"].get("cap")
if cap and f"{cap:.2f}" not in draft and f"{cap:.0f}" not in draft:
return f"draft does not mention the approved amount {cap}"
return None
async def main() -> None:
model = ScriptedModel([
{"kind": "damage_claim", "confidence": 0.9},
"Hi — thanks for the photos. We've confirmed the damage and "
"approved a full refund of USD 189.00 to your card. It should "
"appear in 3-5 business days.",
])
async def approver(rendered, raw):
print("\n--- APPROVAL ---\n" + rendered + "\n--------------")
return Decision(action="approve", note="auto-approve under $200")
# The irreversible step sits behind the checkpoint: draft → approve → commit.
async def commit_refund():
return {"action": "issue_refund", "order": "A-1042",
"amount": 189.00, "idempotency_key": "re-A-1042-r1"}
# One Tracer shared by the chain and the checkpoint, so the whole run
# is a single trace — pass your own in production for the same reason.
tracer = Tracer()
state = await prompt_chain(model, {"ticket": {
"order_id": "A-1042", "message": "my keyboard arrived smashed"}},
[ChainStep("classify", build_messages=_classify,
schema=RefundClass, max_attempts=2),
ChainStep("lookup", fn=_lookup),
ChainStep("policy", fn=_policy_check),
ChainStep("draft", build_messages=_draft,
gate=_mentions_amount, max_attempts=2)],
tracer=tracer)
committed = await checkpoint(commit_refund, approver,
step_name="issue-refund", tracer=tracer)
print("\nworkflow committed:", committed)
asyncio.run(main())Output (real — ScriptedModel replay; trace lines abbreviated — one shared trace_id across the chain and the checkpoint; json.dumps writes the em dash as \u2014):
{"seq": 1, ..., "step": "classify", "ok": true, ...}
{"seq": 2, ..., "step": "lookup", "ok": true, ...}
{"seq": 3, ..., "step": "policy", "ok": true, ...}
{"seq": 4, ..., "step": "draft", "ok": true, ...}
{"seq": 5, ..., "step": "issue-refund:produce", "ok": true, "detail": "dict", ...}
--- APPROVAL ---
{'action': 'issue_refund', 'order': 'A-1042', 'amount': 189.0, ...}
--------------
{"seq": 6, ..., "step": "checkpoint:issue-refund", "ok": true, "detail": "approve \u2014 auto-approve under $200", ...}
workflow committed: {'action': 'issue_refund', 'order': 'A-1042', 'amount': 189.0, 'idempotency_key': 're-A-1042-r1'}What the workflow bought: the policy is code (_policy_check) — deterministic, testable, auditable; the model only does what it's good at (classify intent, write the reply); the amount is verified by a gate, not trusted; the money-moving step is behind a human. Cost: 2 model calls + 1 approver touch. Reliability: p_classify × p_draft with gates — roughly 0.95 × 0.95 ≈ 0.90 end-to-end, and every failure announces itself at a named step.
7.3 As an agent#
Same task, model in charge: it can look things up, check policy, search docs, draft — and must ask before it moves money. Bounded: max 8 steps, and issue_refund is gated behind approval.
# s73_agent.py — run standalone: python3 s73_agent.py
"""The refund task as a bounded agent loop. Real output via ScriptedModel.
This is the 'poor man's' agent loop — schema-mediated tool calls so the
whole thing stays provider-agnostic and testable. Lesson 08A.2 builds the
real one with native tool calling, budgets and streaming; the shape is
the same: model decides, code executes, repeat until finish/stop.
"""
import asyncio
import json
from typing import Any, Literal
from pydantic import BaseModel, Field
from workflows import ScriptedModel, Tracer
ORDERS = {"A-1042": {"item": "mechanical keyboard", "total": 189.00,
"delivered_days_ago": 31, "status": "delivered"}}
POLICIES = {"refunds": "Within 30 days automatic; damaged items full "
"refund any age; else escalate to human."}
# Tools honour their arguments and return errors for unknown keys —
# the same contract 08A.6 teaches: a tool is an interface for the model,
# and "no such order" is a result it can read, not a crash.
TOOLS = {
"lookup_order": lambda order_id: ORDERS.get(
order_id, {"error": f"no order {order_id!r}"}),
"get_policy": lambda topic: ({"policy": POLICIES[topic]}
if topic in POLICIES
else {"error": f"no policy topic {topic!r}"}),
"issue_refund": lambda order_id, amount: {
"queued": True, "order": order_id, "amount": amount,
"note": "requires human approval — see 3.7"},
}
POLICY_HINT = "Always check get_policy before deciding. Never call " \
"issue_refund without human approval."
class AgentDecision(BaseModel):
action: Literal["call_tool", "finish", "ask_human"]
tool: str | None = None
args: dict[str, Any] = Field(default_factory=dict)
final_answer: str | None = None
reason: str = ""
async def run_agent(call_model, task: str, *, max_steps: int = 8,
tracer: Tracer | None = None):
tracer = tracer or Tracer()
messages = [{"role": "system", "content": POLICY_HINT},
{"role": "user", "content": task}]
transcript = []
for step in range(1, max_steps + 1):
decision = await call_model(messages, schema=AgentDecision,
name=f"agent:step{step}")
assert isinstance(decision, AgentDecision)
tracer.record(f"agent:step{step}", ok=True,
detail=f"{decision.action} {decision.tool or ''}".strip())
if decision.action == "finish":
return {"answer": decision.final_answer, "steps": step,
"transcript": transcript}
if decision.action == "ask_human":
return {"escalated": decision.reason, "steps": step,
"transcript": transcript}
# call_tool
fn = TOOLS.get(decision.tool or "")
if fn is None:
result = {"error": f"unknown tool {decision.tool!r}"}
else:
try:
result = fn(**decision.args)
except TypeError as exc:
result = {"error": f"bad args: {exc}"}
transcript.append({"tool": decision.tool, "args": decision.args,
"result": result})
# The model must see its own decisions, not just bare tool
# results — lesson 08A.2's native tool-calling loop writes proper
# assistant tool-call messages; this schema-mediated version
# records the equivalent by hand.
messages.append({"role": "assistant", "content":
f"I decided: {decision.action} "
f"{decision.tool or ''} args={decision.args} "
f"— {decision.reason}"})
messages.append({"role": "user",
"content": "Tool result: " + json.dumps(result)})
return {"stopped": "max_steps", "steps": max_steps,
"transcript": transcript}
async def main() -> None:
model = ScriptedModel([
# step 1: look up the order
{"action": "call_tool", "tool": "lookup_order",
"args": {"order_id": "A-1042"}, "reason": "need order facts"},
# step 2: check policy
{"action": "call_tool", "tool": "get_policy",
"args": {"topic": "refunds"}, "reason": "check eligibility"},
# step 3: decide — damaged item, full refund, but must ask human
{"action": "ask_human",
"reason": "damaged-item refund of USD 189.00 needs approval"},
])
outcome = await run_agent(
model, "Customer wants a refund for order A-1042, keyboard "
"arrived damaged. Handle it.")
print(json.dumps({k: v for k, v in outcome.items() if k != "transcript"},
indent=2))
print("tools used:", [t["tool"] for t in outcome["transcript"]])
asyncio.run(main()){"seq": 1, "trace_id": "...", "step": "agent:step1", "ok": true, "detail": "call_tool lookup_order", "elapsed_ms": 0.0}
{"seq": 2, "trace_id": "...", "step": "agent:step2", "ok": true, "detail": "call_tool get_policy", "elapsed_ms": 0.0}
{"seq": 3, "trace_id": "...", "step": "agent:step3", "ok": true, "detail": "ask_human", "elapsed_ms": 0.0}
{
"escalated": "damaged-item refund of USD 189.00 needs approval",
"steps": 3
}
tools used: ['lookup_order', 'get_policy']Honest assessment: the agent explored — it chose to look up the order and check policy rather than being told to. That's the autonomy you pay for. But notice what it cost: 3 model calls where the workflow used 2, a transcript to debug (now including the model's own stated reason for each call, and tool results that validate their arguments like real tools do), a max_steps bound that exists only because the loop could otherwise run forever, and a decision (ask_human) that the workflow got for free by construction — the checkpoint isn't a model choice, it's architecture. The agent's advantage shows on tasks where the needed lookups can't be predicted; on a refund, they can.
7.4 The comparison#
| Single call | Workflow | Agent | |
|---|---|---|---|
| Model calls (this task) | 1 | 2 (+1 human touch) | 3 (variable) |
| Latency | ~1× | ~2× sequential | ~3×+ sequential, unbounded |
| Cost (illustrative) | lowest | ~2–3× single | ~3–10×, variance high |
| End-to-end reliability | p — one shot |
p₁×p₂ with gates ≈ 0.90 |
p³ with drift risk ≈ 0.86, plus loop risk |
| Controllability | low — one opaque decision | high — every step named, gated, logged | low — trajectory varies per run |
| Side-effect safety | none built in | checkpoint by construction | depends on tool permissions (08A.14) |
| Where it wins | simple, stable, high-volume | enumerable steps, verifiable intermediates, approvals | genuinely unpredictable investigation |
The pattern across all three: the workflow isn't a compromise — it's the correct tool for enumerable work, and it left the agent free to do what only an agent can do.
Failure gallery#
Every pattern above fails in recognisable ways. This table collects them — the symptom is what you see in production, the guard is what you build before it bites. The inline Failure modes notes in each section are the short version; this is the diagnostic table.
| Failure | Pattern | Symptom | Guard |
|---|---|---|---|
| Silent misroute | routing | Tickets land on the wrong handler; no error, just wrong answers | Log every RouteDecision (the router trace event does); alert on per-route volume shifts |
| Confident-wrong classifier | routing | confidence: 0.95 on a wrong route — the threshold can't catch it |
Calibrate confidence on labelled data (Module 10A); keep min_confidence plus a human fallback that actually works |
ParallelJobError partials |
parallelization | One branch fails; do you proceed, retry or abort? | The exception carries .results and .errors — decide per job; retry only the failed branch, don't rerun the fan-out |
| Correlated branch failures | parallelization, voting | All N branches fail or agree on the same wrong answer | Branches sharing context share its blind spots; diversify inputs/models for voting, and don't treat agreement as correctness |
| Voting ties / no majority | parallelization | Counter.most_common picks arbitrarily on a tie |
For comparable answers require a strict majority or escalate; for prose, synthesize with a final call instead |
| Hallucinated subtasks | orchestrator-workers | Planner invents work that doesn't exist or misses coverage | Gate the plan (2–6 tasks, self-contained instructions); measure coverage separately from synthesis quality |
| Duplicated subtasks | orchestrator-workers | Two workers answer the same question; synthesis double-counts | Deduplicate plan task titles/IDs before dispatch; the planner trace detail lists what was chosen — diff it against the goal |
| Worker exception | orchestrator-workers | A worker crashes mid-fan-out | Now collected as {"error": ...} in results and flagged by the synthesizer — but a silent error entry is still a failure: alert on ok=False worker events |
| Synthesis drops findings | orchestrator-workers | Final answer ignores a worker's key result | The synthesis prompt demands per-claim citation; verify traceability in evals — it's the pattern's signature failure |
| Correlated critic blind spots | evaluator-optimizer | Critic and generator share the same model biases; feedback can't see the error | Use a different model or rubric-based checks for the critic; prefer deterministic verifiers where possible |
| Oscillation / score inflation | evaluator-optimizer | Drafts ping-pong; critic scores drift upward without real improvement | max_rounds cap, plateau detection, return best-scoring draft with converged=False — never trust the last score alone |
| Reduce bottleneck loss | map-reduce | Details that don't survive partial summaries are gone forever | Design partials to carry what the final answer needs; compare against full-context answers on inputs that fit |
| Order-dependent map | map-reduce | Reordered or merged results change the answer | Map-reduce assumes independent pieces — verify independence before using it; sequential chains preserve order |
| Approval timeout | human-in-the-loop | The human never responds; the run hangs or silently proceeds | Timeout → escalate or abort, never auto-approve; the checkpoint trace shows how long proposals wait |
| Rubber-stamping | human-in-the-loop | Approver approves everything unread; the checkpoint is theatre | Fewer, better-placed checkpoints; track edit-rate and reject-rate — an always-approved checkpoint is misplaced |
| Edit breaks downstream | human-in-the-loop | The human's edited text violates assumptions later steps rely on | Re-validate edited proposals through the same gates as model output |
| Fallback masks systemic failure | fallback chain | The cheap model answers badly-but-successfully; errors flatline while quality craters | Tag results by source; alert on fallback rate and fallback-quality gap, not just exceptions |
| Cascading fallbacks | fallback chain | All alternatives hit the same rate limit or outage together | retryable classifier (03.8); diversify providers, not just models |
| Non-idempotent retries | fallback chain, durable runs | A retried "send email"/"issue refund" executes twice | Idempotency keys and "already done" checks on every side-effecting step (03.5, Part 7) |
| Compounding step failures | agent loop, long chains | pⁿ — a "95% per step" model gives ~36% on a 20-step run |
Fewer model steps, more deterministic code, verification gates — Part 5 |
| Runaway loop cost | agent loop | The bill grows with turns × growing context | Budgets from the first sample: max steps, max tokens, max cost, wall-clock (08A.2) |
| Resume replays wrong code | durable workflows | A deploy mid-run changes step behaviour under a resumed execution | Engine versioning/patching (6.4); hand-rolled runners don't have it |
The common thread: workflows fail loudly at named steps; agents fail silently inside trajectories. That's why every guard above is either a deterministic check between steps or a trace event you can alarm on — the Tracer output in Part 3 isn't decoration, it's the detection layer for this whole table.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Agents are just better workflows." | They're a different contract: your code controls the steps in a workflow; the model controls them in an agent. Agents cost more latency, more tokens and more variance — Anthropic's own production data shows ~4× chat tokens for agents and ~15× for multi-agent systems. Use them where the path can't be enumerated, not by default. |
| "If the demo works, the agent is reliable." | A demo exercises the paths that happen to succeed. With per-step success p, an n-step run succeeds pⁿ of the time — a "95% reliable" model gives a 20-step agent ~36% end-to-end. Measure pass^k, not one lucky run. |
| "The model decides the steps, so it's an agent." | Not necessarily. Orchestrator-workers decomposes once at runtime and runs bounded workers — Anthropic classes it as a workflow. The dividing line is whether control can loop back to the model indefinitely. |
| "Adding more steps makes the system smarter." | Every model step multiplies the failure probability (pⁿ) and the cost. Steps kept in deterministic code are free and perfect — put the model only where judgement is needed. |
| "Human-in-the-loop is a failure of automation." | It's a feature at the right boundary. A checkpoint converts an irreversible action into an approved one for the cost of human latency — which is why every provider's guidance includes it. Place it on side effects, not on every step. |
| "Fallbacks are free resilience." | A fallback that fires often is a capacity problem wearing a resilience costume — and silent fallbacks to worse answers are worse than loud failures. Tag results by source and alert on fallback rate. |
| "Durable execution makes agents reliable." | It makes runs continuable, not correct. A resumed run replays the same prompts; wrong steps resume to wrong successors. You still need gates, budgets and idempotent side effects. |
| "Voting always improves answers." | Majority vote helps when errors are independent; it amplifies them when the model has a systematic bias. And it multiplies cost by N — spend it on high-stakes single answers, not bulk work. |
| "Map-reduce is just chunking." | Chunking decides what goes in each piece (Module 05's job); map-reduce is the orchestration that processes pieces independently and merges — and the reduce step is a lossy bottleneck you must design for. |
| "You need a framework or engine to build workflows." | Every pattern here is a few dozen lines over a call_model function — Anthropic's guidance is literally "start by using LLM APIs directly". Engines earn their place for durability, not for basic chaining. |
| "Temperature 0 makes an agent deterministic." | It removes sampling randomness, not trajectory randomness: tool results, retrieved documents and timestamps differ per run, so the model's path differs. Determinism lives in your code paths, not the model's. |
Key takeaways#
- Workflows are LLMs and tools orchestrated through predefined code paths; agents are systems where the LLM dynamically directs its own process and tool usage (Anthropic's definitions, echoed by OpenAI, Google and LangGraph). The test: who decides what happens next?
- The Workflow-First Rule: use a deterministic workflow unless an agent is clearly needed. Name the reason before you build the loop (unpredictable steps, open-ended length, worth the cost); the wider decisions live in 13A.8 (workflow vs agent is §11.1).
- It's a spectrum, not a switch: single call → prompt chain → router → parallelization → orchestrator-workers → agent loop. Buy autonomy one rung at a time; Anthropic, OpenAI and Google all say start simple.
- Every pattern in Part 3 is the same shape: your code orchestrates,
call_modelperforms each call, gates verify between steps, budgets bound the run.workflows.pyimplements all of them over an injectablecall_model— testable withScriptedModel, portable across providers. - Put the model only where judgement is needed. Deterministic steps (lookups, policy checks, gates) are free, fast and perfectly reliable — they're what make workflows trustworthy.
- Reliability compounds downward:
pⁿacrossnmodel steps. Fewer steps and verification gates beat bigger models; a cheap deterministic gate beats a 10×-cost model upgrade. - Agents earn their keep only where the step count can't be predicted, the environment gives feedback, and you can evaluate, sandbox and budget the run. Otherwise the task is a workflow — possibly with an agent island inside one route.
- Irreversible actions get human checkpoints regardless of architecture — and durable execution (persistence, resumption, idempotency, step retries) is what makes long runs and human waits survivable.
- The same task built three ways teaches more than any table: Part 7's refund request shows a single call, a gated workflow with approval, and a bounded agent — and the workflow is the right answer because the steps were enumerable.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Workflow-First Rule | Use a deterministic workflow unless an agent is clearly needed; build an agent only when you can name why a fixed path will not do |
| Agentic system | The umbrella term for any system where LLMs do judgement work — includes both workflows and agents (Anthropic's usage) |
| Workflow (agentic) | LLMs and tools orchestrated through predefined code paths; your code decides the steps |
| Agent (LLM agent) | A system where the model dynamically directs its own process and tool usage in a loop |
| Prompt chaining | Decomposing a task into sequential model calls, each processing the previous output, with programmatic gates between steps |
| Gate (verification gate) | A check between workflow steps — deterministic code or a model call — that accepts, retries or rejects a step's output |
| Routing (workflow pattern) | Classifying input with a schema-constrained call, then dispatching to specialised handlers |
| Route decision | The classifier's structured output: route name, confidence, reason |
| Sectioning | Parallelization shape: breaking a task into independent subtasks run concurrently |
| Voting | Parallelization shape: running the same call N times and aggregating (majority or synthesis) |
| Orchestrator-workers | A workflow where a planner call decomposes the task at runtime, bounded workers execute subtasks, and a synthesizer merges results |
| Evaluator-optimizer | A generate→critique→revise loop that iterates until a quality bar is met or a stop criterion fires |
| Verdict | The evaluator's structured output in evaluator-optimizer: passed, score, feedback |
| Map-reduce (workflow) | Processing document pieces independently (map) then merging partial results (reduce), tree-style for large sets |
| Human-in-the-loop checkpoint | A workflow pause point where a person approves, edits or rejects a proposal before it commits |
| Approval request / Decision | What a checkpoint shows the human and what they return: approve / edit / reject |
| Fallback chain | An ordered list of alternatives tried in sequence when the primary path fails — at call, step or whole-workflow granularity |
| Escalation | Moving work to a stronger model, a different provider or a human when the current path can't succeed |
call_model |
The injectable async function every pattern calls — an adapter over a provider SDK in production, ScriptedModel in tests |
ScriptedModel |
A fake model that replays canned replies in order and records calls; makes workflows testable without API keys (full version in 08A.2) |
ChainStep / prompt_chain |
The workflow primitive: a step is deterministic code or a model call, with optional gate and retry |
Tracer / trace event |
One JSON line per workflow step — the minimum trajectory log; extended in 08A.14 |
| Durable workflow | A run whose progress is persisted outside the process, so it survives crashes, waits and restarts |
| Checkpoint (workflow) | A saved snapshot of workflow state after a step — distinct from a model-weight checkpoint (02.6) |
| Compounding error rate | The pⁿ decline of end-to-end success as the number of model steps grows |
| pass@k / pass^k | "Any of k attempts succeeded" vs "all k succeeded" — the reliability metric for agents (08A.14) |
| Durable execution | The engine property of persisting execution state so runs resume mid-flight (Temporal's term; the general concept is durable workflows) |
All terms are also collected in the glossary.
Exercises#
- Prompt chaining (3.1): run
s31_support_reply.py, then break the draft gate (remove the order ID from the scripted reply). Watch the retry fire — what lands instate["_errors"], and how does_classify_messages's note change on attempt 2? - Routing (3.2): add a
billinghandler and a fifth route toORDERS_ROUTE. Script a low-confidence decision (confidence: 0.3) and verify it lands onhuman— then removemin_confidenceand watch the misroute happen silently. What would you alert on in production? - Voting (3.3): extend
votefor open-ended answers: after collecting N replies, make a finalcall_modelthat sees all of them plus the original question and returns one answer. When does synthesis beat majority? - Orchestrator-workers (3.4): make one worker return
{"error": ...}instead of text. Trace what the synthesizer sees — should it proceed with partial results or fail? Implement the decision. - Evaluator-optimizer (3.5): script a critic that never passes (
score: 3every time). Confirm the loop returnsconverged=Falsewith the best draft — and count the model calls: what's the worst-case cost ofmax_rounds=5? - Durable runner (6.3): run the demo, then kill the process between steps 2 and 3 for real (Ctrl-C mid-run), and resume — which steps re-execute and why is that safe here but dangerous for a
send_emailstep? - Worked example (Part 7): build the refund task as all three (the files exist:
s71,s72,s73). Compare the trace JSONs: which architecture gives you the most debuggable failure? - Reliability maths (Part 5): pick a real pipeline you're building. List its model steps, estimate
pper step from an eval, and computepⁿ. Where does a deterministic step or a gate buy you the most?
Hints for the exercises
- Add a second draft reply to the script first: the retry makes another model call, and with only one reply left you would get
RuntimeError: ScriptedModel: out of scripted replies. On a gate failurestate["_errors"]gets"draft attempt 1: draft does not mention order A-1042". Only_classify_messagesreads_errors, so its "Previous attempt rejected" note appears only if the classify step retries; the draft step's retry sees the same_draft_messagesunless you make it read_errorstoo (a good small change to make). - With
min_confidence=0.3removed (default0.0) the 0.3-confidence decision is dispatched to its chosen handler without anyone noticing. In production alert on the fallback rate and on per-route volume shifts, and log everyRouteDecision. - Add a final
call_modelthat receives the question and all N replies and returns one answer. Synthesis beats majority when answers are prose, when no two replies are string-identical, or when each reply contains a different correct fragment. - Wrap the worker so one task raises; the synthesizer then sees
{"error": "..."}for that task id. A sensible default is partial synthesis with the failure flagged; fail hard when a missing subtask makes the answer unsafe (for example the supplier lead time in the restock decision). - Worst case with
max_rounds=5: 1 generation + 5 critiques + 4 revisions = 10 calls (the loop breaks after the last critique without revising). A plateau needs a failed verdict whose score is not above the previous one, so a flatscore: 3stops at round 2: 1 + 2 critiques + 1 revision = 4 calls. - Steps that finished are in the state file and are skipped; the step that was running re-executes from its start. That is safe for pure model calls and lookups, and dangerous for
send_emailbecause the first attempt may already have sent before the crash, so the re-run sends again unless the step is idempotent. - The workflow trace names every step, so a failure points to one line; the agent trace shows decisions but not why a decision was wrong. Treat that as an answer to defend with a concrete failing case rather than a rule.
- The steps where a gate or deterministic code replaces a model call remove a factor from the product; compute
pⁿbefore and after to see the gain.
Check yourself#
- State Anthropic's definitions of workflow and agent in one sentence each, and the test that tells them apart.Workflows orchestrate LLMs and tools through predefined code paths; agents let the LLM dynamically direct its own process and tool usage. The test: who decides what happens next — your code or the model.
- Name the five workflow patterns Anthropic describes, and one production pattern the essay doesn't cover that this lesson adds.Prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer. This lesson adds map-reduce over documents, human-in-the-loop checkpoints, and fallback/escalation chains.
- Why is a deterministic lookup step inside a prompt chain more reliable than a model call that "looks up" the same data?Because
p = 1.0: code can't hallucinate, can't be prompt-injected into wrong output, costs zero tokens, and runs in microseconds. Every model step you replace with code removes a failure probability from thepⁿproduct. - A router sends 8% of tickets to
humanfallback. Is that a bug? What two numbers would you check before answering?Not necessarily — some tickets genuinely need humans. Check the fallback rate over time (a spike means classifier drift) and the outcomes of fallback tickets (are humans resolving them, or bouncing them back?). Alert on rate, not just count. - Sectioning three subtasks cuts latency ~3× but triples token cost. When is that trade still worth it?When the subtasks are independent and each is expensive in latency but the merged result is needed quickly — e.g., three analyses blocking one user-facing answer. If the branches are cheap or the result isn't latency-sensitive, sequential is simpler and the cost is the same.
- Orchestrator-workers lets the model pick subtasks at runtime — why does Anthropic still class it as a workflow rather than an agent?Because the orchestrator decomposes once, up front, into a bounded set of workers — control doesn't loop back to the model to decide "what next?" repeatedly. The model picks the shape once; your code owns the execution contract.
- In evaluator-optimizer, what are the three stop criteria, and why must the result carry a
convergedflag instead of raising on non-convergence?Pass threshold met,max_roundsexhausted, and (in a tuned version) score plateau. Non-convergence is a normal outcome, not an exception — the caller needs the best draft plus the flag to decide retry/escalate/human, so raising would destroy the information. - A 10-step agent run uses a model that is 95% reliable per step. What's the approximate end-to-end success rate, and what two design changes improve it most?
0.95¹⁰ ≈ 60%. Biggest wins: fewer model steps (move verifiable work into code/gates) and verification gates with retries — each converts silent errors into caught ones at ~4% extra calls. - Why does a human checkpoint belong on the irreversible step rather than on every step?Because checkpoints cost human latency (hours) and attention — placing them on every step trains approvers to rubber-stamp. Put them where an error is irreversible or high-stakes: payments, sends, deletions, external commitments.
- Your fallback chain tries cheap→strong→human. The strong model is down and the cheap one keeps answering badly but successfully. What observability would catch this?Tag every result with which alternative produced it, and alert on the rate of non-primary answers plus a quality proxy (does the cheap model's output pass the same gates?). A fallback that fires 20% of the time is a capacity problem; one that fires 0.1% is resilience.
- What four properties must a durable workflow have to survive a crash mid-run, and which one is easiest to forget?State persistence (serialisable state after each step), resumption (skip completed steps), idempotency (side effects safe to retry), step-level timeouts/retries. Easiest to forget: idempotency — retries are the whole point of durability, and a retried "send email" duplicates it.
- Give two conditions that favour an agent and two that rule one out, with the reasoning.Favour: unpredictable step count (can't enumerate the path), environment feedback (tool results to react to), ability to evaluate/sandbox/budget. Rule out: enumerable steps a chain handles, tight latency/cost budgets, irreversible actions without approval, no way to verify outcomes.
Further resources#
- Anthropic, Building effective agents (Erik Schluntz & Barry Zhang, Dec 2024): the essay this lesson's framework is built on — workflows vs agents, the five patterns, when (and when not) to use agents.
- Anthropic, patterns/agents cookbook: minimal reference implementations of the workflow patterns.
- OpenAI, A practical guide to building agents (PDF, April 2025): when to build an agent, the model/tools/instructions triad, orchestration patterns, seven guardrail types.
- Google Cloud, Choose your agentic AI architecture components: Google's definition of an agent, the kinds of problem it suits and the component map.
- LangChain, Workflows and agents and Persistence: the same distinction in LangGraph terms, plus checkpointer mechanics for Part 6.
- Anthropic, How we built our multi-agent research system (June 2025): production numbers on token multipliers and why multi-agent earns its cost only sometimes.
- Dex Horthy (HumanLayer), 12-Factor Agents: principles for reliable LLM software — own your prompts, own your control flow, contact humans with tool calls, make your agent a stateless reducer.
- Temporal documentation: durable execution concepts (event history, replay, activities) behind the Temporal row of the 6.4 table.
← 08A.8 — Provider Built-in and Server-Side Tools | Module 08A overview | 08A.10 — Agent Patterns: ReAct, Plan-and-Execute, Routing and Orchestrator-Workers →