Free chapter, full text

Chapter 2: Workflows before agents

The cheapest, most reliable agent is often the one you did not build.

Free in full. The figures and the end-of-chapter exercises are in the PDF.

Composite case: a software company spends two weeks building four cooperating agents to triage support tickets, at forty seconds per ticket, until someone draws the real process on a whiteboard: five boxes, two branches. Rebuilt in an afternoon as a workflow with two model calls, it is faster, cheaper and easier to test.

A workflow is a system where your code decides the sequence of steps, even if some steps call a model; in an agent (Chapter 1), the model does. The difference is who controls the flow.

The core rule: if you can draw the flowchart, build the workflow

If you can draw the flowchart before the task starts, build the workflow. Use an agent only for the parts where the next step depends on what you discover along the way.

In a workflow, every path is code you wrote: testable, logged, priced, explainable. In an agent, the model chooses the path at runtime: you can bound it, not enumerate it. That trade pays only when you need the flexibility. Anthropic's "Building effective agents" draws the same line and advises starting with the simplest solution, adding complexity only when needed (Anthropic, 2024-12-19). Most production "agents" are workflows with a short agentic section, and that is the healthy shape.

To test whether you can draw it, take five real inputs and write down the steps a competent human follows for each. Same steps, or two or three known variants: a workflow. A different path through different systems every time: maybe an agent.

[!ANTI] Building the agent to find out what the workflow is Teams that do not know the process yet build an agent, hoping the model will figure it out. It will, differently each time, and you spend weeks reverse-engineering traces. Interview the human who does the task today, draw the flowchart, build that. Keep the agent for the boxes labeled "it depends".

The pattern catalog

In the first four patterns your code owns the flow. Orchestrator-workers sits on the border. The last two are agents. The first five definitions follow Anthropic's guidance.

Pattern Shape Use when Avoid when Relative cost Typical failure
Prompt chaining Fixed sequence of calls with code checks between them Clear steps (extract, draft, check) Steps depend on each other unpredictably Low Early error flows into later steps
Routing Classify, send to a specialized path Distinct input categories Categories overlap or keep changing Low Confident misrouting
Parallelization Independent calls at once (sectioning) or same call N times (voting) Independent subtasks, high-stakes judgments Shared state Medium, N times the calls Votes agreeing on the same wrong answer
Evaluator-optimizer Generator plus critic in a loop Checkable quality criteria First draft is good enough Medium to high Endless polishing
Orchestrator-workers One model decomposes and delegates Subtasks unknown in advance You can list the subtasks High Bad decomposition
Agent loop (ReAct) Reason, call a tool, read, repeat Path depends on tool results You can draw the flowchart Bounded only by caps Loops, wrong tools, invented parameters
Plan-and-execute Write a plan, execute, revise Long tasks where a visible plan helps review Short tasks Medium to high Following a bad plan faithfully

What the table does not say:

  • Chaining is reliable only because of the gates: plain code between calls checks schema, required fields and length.
  • Routing is your main cost lever (small models for easy cases). Always give the router an "unsure" category that goes to a human or a stronger path; a router forced to choose will choose confidently and wrongly.
  • Voting detects uncertainty cheaply: disagreement between runs is a signal.
  • Evaluator-optimizer needs a stop condition and an iteration cap. The critic always finds something.
  • The agent loop (named after the ReAct paper) needs a full harness. Arize describes agents that keep polling a job's status instead of waiting, turning one task into hundreds of API calls while every log line looks healthy (Arize).
  • Plan-and-execute gives humans a plan to review before anything runs: a natural approval point.

The decision tree: single call, workflow, agent, multi-agent

Walk this tree for every new use case. Stop at the first "yes".

Step 4 asks about contexts, permissions and parallelism, not "roles": splitting does not pay because the task "feels like" a team. Default to the highest box that passes your evals, and move down only with a failing eval case that better prompts, context or tools cannot fix. Write that case down: it justifies the extra cost.

The determinism budget: where to put code and where to put the model

Every LLM call adds variance, and wrong outputs can look right. Spend that variance only where the model buys something code cannot.

Put in code (computable right answer) Put in the model (language and judgment)
Permissions and policy: who sees what, which refunds need approval What is this message about, how urgent does it sound?
Arithmetic, dates, SLA deadlines Which of these documents answers the question?
Lookups by known keys: tier, contract, owner Draft a reply in the right tone
Routing on structured fields, validation, retries, idempotency Summarize this thread for a human

The model proposes, the code disposes. The model returns structured output (a category from an enum, a draft); code validates it, applies business rules and decides. A model that says "priority: P1" for a free-plan customer does not override the rule that free plans have no P1 queue. The test: "if the model gets this wrong, would a unit test have caught it?" If yes, it belongs in code. "Refunds above 500 euros need manager approval" is a rule, not a prompt line: prompts are not enforcement.

Worked example: support ticket triage, built three ways

The task. A B2B SaaS company receives support tickets by email and chat. For each one the system assigns a category (billing, technical, access, feature, other), a priority from P1 (outage for a paying customer) to P4 (question), stored as an integer 1 to 4, a queue, and optionally a draft reply from the knowledge base. P1s must reach on-call within minutes, wrong P1s wake people at night, and no reply goes out without a human. Available: a CRM, a searchable knowledge base, a status page of open incidents.

Version A: the workflow

Five boxes: classify, look up the customer, apply priority rules, route, draft. Two need a model.

CATEGORIES = {"billing", "technical", "access", "feature", "other"}

def workflow_triage(ticket: Ticket) -> Triage:
    # Model call 1: small, fast model, strict JSON schema
    # (category, urgency_signal, confidence).
    c = classify(ticket.text, schema=ClassifySchema)
    if c.category not in CATEGORIES or c.confidence < 0.6:
        return to_human(ticket, reason="low_confidence")

    # Code: lookups by key.
    customer = crm.get_customer(ticket.sender_email)
    if customer is None:
        return to_human(ticket, reason="unknown_sender")
    incident = status.open_incident_for(customer.region)

    # Code: business rules return an int, 1 (outage) to 4.
    inputs = PriorityInputs(
        category=c.category, urgency=c.urgency_signal,
        tier=customer.tier, open_incident=incident is not None,
    )
    priority = priority_rules(inputs)
    queue = QUEUE_MAP[(c.category, priority)]

    # Model call 2, only where a draft helps.
    draft = None
    if c.category in {"billing", "access"}:
        docs = kb.search(ticket.text, top_k=4)
        draft = draft_reply(ticket.text, docs, customer.name)

    return Triage(c.category, priority, queue, draft,
                  confidence=c.confidence, inputs=inputs,
                  needs_review=True)

At most two model calls per ticket. Priority comes from rules, so a P1 always means the same thing, and every branch is testable with unit tests plus labeled past tickets (100 to 200 across categories, with rare costly cases such as real P1s over-represented). You can price it before writing code: tickets times tokens per ticket times price.

Where the confidence number comes from. A confidence the model writes into its own JSON is a hint, not a probability; the 0.6 is illustrative. Group labeled tickets by stated confidence, measure accuracy per group, and set the threshold where accuracy meets the business bar, probably per category. If stated scores do not track accuracy, use agreement between two or three runs, or token log-probabilities where your provider exposes them.

What it cannot do: investigate. "The export has been broken since your release on Tuesday, see attached log" gets a category and a priority, but nobody checks whether Tuesday's release touched exports.

Version B: the agent

One model in a bounded loop with tools search_kb, get_customer, get_open_incidents, search_recent_tickets, read_attachment and submit_triage. The prompt holds categories, priority policy and queue map; the harness caps the run at 12 steps and a fixed cost; every tool except submit_triage is read-only.

On the Tuesday export ticket, the agent reads the log, finds three similar recent reports, notices an open incident, and proposes a P2 with links: what a senior support engineer does. The cost: 3 to 12 model calls per ticket, each re-sending a growing context, with variable latency. Priority is now the model's reading of a prose policy, so similar tickets can get different priorities, and tests must cover trajectories. On a plain "how do I change my invoice address?" ticket, the agent still searches and checks. Most tickets are plain.

Version C: the hybrid

Run the workflow for every ticket. Send only tickets that need investigation to a bounded agent, and let the agent propose, not decide.

from dataclasses import replace

def triage(ticket: Ticket) -> Triage:
    # Version A, unchanged.
    base = workflow_triage(ticket)
    needs_investigation = base.category == "technical" and (
        base.priority <= 2 or ticket.has_attachment
        or base.confidence < 0.8
    )
    # Most tickets end here.
    if not needs_investigation:
        return base

    result = run_agent(
        task=Task(id=ticket.id,
                  input=investigate_prompt(ticket, base)),
        model=SMALL_MODEL,
        # kb, crm, incidents, tickets
        tools=READ_ONLY_TOOLS, flags=FLAGS,
        budget=Budget(8, 0.20, 60),
    )
    # A handoff keeps the workflow triage, with the reason.
    if result.status != "done":
        return replace(base, note="investigation incomplete: "
                       + result.reason)
    # A validated Finding: the submit_finding argument.
    finding = result.output

    # Keep only evidence that points at real records
    # (ticket, incident, log line).
    evidence = verify_evidence(finding.evidence)

    # The agent proposes; code applies the same rules
    # to richer inputs.
    inputs = replace(base.inputs, evidence=evidence)
    p = priority_rules(inputs)
    return replace(base, priority=p, inputs=inputs,
                   queue=QUEUE_MAP[(base.category, p)],
                   note=finding.summary, links=finding.links)

verify_evidence guards against the nastiest failure: evidence that is wrong but plausible. The agent must cite each claim with a record ID; code fetches each record and drops claims whose ID does not exist or does not match (an "open incident" that is closed). Unverified hunches can appear in the summary but never move a ticket to P1.

Plain tickets cost what the workflow costs, and a P1 still means what the rules say. If the agent fails or runs out of budget, the ticket keeps its workflow triage with a note: graceful degradation, not an outage.

Tuning the trigger. needs_investigation decides both cost and coverage. Log it on every ticket and watch two weekly rates: missed investigations (not investigated, later escalated by a human: too tight) and wasted investigations (the finding changed nothing: paying for no value). Change one condition at a time.

The comparison

These are uncached design estimates, not benchmarks. Call counts understate the gap: a classification reads one ticket, while each investigation step re-sends a growing context. With illustrative token counts (about 1,200 input tokens per classification and about 2,800 per ticket for Version A once drafts are counted; a six-step investigation growing from 5,000 to 11,000 tokens, about 48,000 in total), Version C costs about 1.85x Version A when 5% of tickets are investigated, and about 4.4x at 20%. The trigger, not the model, sets the bill.

Google's illustrative ADK 2.0 refund example on mock APIs points the same way: deterministic nodes cut tokens per run from 5,152 to 2,265 and time from 7.2 to 5.7 seconds against a plain LLM agent (Google Developers Blog, Jul 2026, vendor claim).

Dimension A. Workflow B. Agent C. Hybrid
Model calls per ticket 1 to 2, fixed 3 to 12, chosen by the model 1 to 2 for most; up to 2 + 8 when investigated
Relative model cost 1x 1.5x to 12x by call count, more with context growth About 1.85x at 5% investigated, 4.4x at 20% (illustrative)
Latency Low, predictable Variable, capped Low for most tickets
Priority consistency Deterministic Varies between similar tickets Deterministic, richer inputs
Novel, multi-system tickets Human investigates Yes Yes, for routed tickets
Behavior on failure Human queue Hits a cap; no triage without a fallback Falls back to workflow triage
How you test it Unit tests plus labeled set Trajectory and outcome evals, human review Workflow tests plus a small trajectory set

The verdict

Default to Version A: a working system, a labeled dataset and a baseline cost within days. Ship Version C when enough tickets that A handled badly for lack of investigation exist to build an eval set. Ship Version B only if most tickets need investigation, volume is low, and you accept that priorities become judgments.

The hybrid is the general shape of good agent systems: a deterministic spine for predictable work, bounded agentic sections where discovery pays, and code with the last word on decisions that matter. Chapter 17 takes this system to production.

[!DECIDE] Hybrid placement rule Put the agent where the flowchart says "it depends", give it read-only tools and a small cap, make it return evidence rather than decisions, and let code apply the rules. If its output must be acted on directly (a write to a customer record), put a human approval or a deterministic validation between the agent and the action.

Anti-patterns

  • The agent for a cron job. A nightly report built as an agent rediscovers the plan every night, skips a metric as "not relevant today", and reports stop being comparable. Fetch and compare in code, then one model call writes the summary.
  • Multi-agent theater. A "CEO agent" delegates to "manager", "analyst" and "QA" agents. Each hand-off loses context, costs multiply per hop, and nobody can tell which agent caused a wrong output. Usually a prompt chain wearing costumes: apply step 4 of the tree.
  • Agent as error handler. Wrapping a brittle integration in an agent "so it can figure out what went wrong". Fix the integration: agents sometimes read an HTTP 500 with no explicit failure text as "processed" (Arize).
  • Same big model everywhere. Classification and extraction usually run fine on a small model. Route by task and evaluate each route.

Per-track notes

  • Builder. Build Version A first, even if you are sure you will need an agent. Keep the workflow-agent interface typed, with Chapter 8's three statuses: done, handoff, awaiting human.
  • Leader. Use the decision tree as a review gate: every agent proposal names the step it fails, with an example. Ask for cost per successful task and what happens at the cap.
  • Solo. Workflows fail loudly and predictably, so you debug fewer evenings. Keep each step's cost plus your review time in a spreadsheet: that sum, on the retry case, is your pricing floor (Chapter 13).
  • Ops. n8n, Zapier or Make flows are already workflows: routing is a switch after a classification step, chaining is LLM steps with filters, an IF node on the confidence field sends low scores to a human queue, the investigation is an AI agent node behind a condition, with read-only tools, a low iteration limit and an approval step before any customer message.

Checklist

  • [ ] We drew the flowchart from at least five real inputs before choosing an architecture.
  • [ ] We wrote down which step of the decision tree our design fails, with an example.
  • [ ] Every decision with a computable answer is in code, not in a prompt.
  • [ ] Every model output is validated, and every classifier has an "unsure" path.
  • [ ] Every agentic section has caps, a timeout and read-only tools unless writes are approved, and falls back to a workflow result or a human.
  • [ ] We have a workflow baseline for cost and quality to compare any agentic design against.