Module 3 of 6 · 45 minutes

Workflow patterns

Most reliable 'agentic' systems in production are workflows. These five patterns cover the vast majority of them.

By · Last updated

Learning objectives

  • Describe the five workflow patterns
  • Choose the right pattern for a task
  • Implement routing in Python
  • Implement an evaluator–optimiser loop with a stopping condition
  • Combine patterns thoughtfully
  • Use a code gate where criteria can be checked mechanically
  • Measure a router's accuracy on labelled messages
Setup: the client and the call_llm helper (runs automatically when you press Run on any cell)
Python · setupimport anthropic, json
client = anthropic.Anthropic()          # the real SDK reads ANTHROPIC_API_KEY from the environment
MODEL = "YOUR-MODEL-NAME"               # copy a current model name from your provider's docs

def call_llm(prompt):                   # thin wrapper: one prompt in, text out
    r = client.messages.create(model=MODEL, max_tokens=400,
                               messages=[{"role": "user", "content": prompt}])
    return r.content[0].text.strip()
Practice mode on this page

Every code block in this course is a live cell: press Run and it runs in your browser, and you can edit it and run it again. A real LLM needs a secret API key, and a key must never sit in a web page. So on these pages the cells talk to a small pretend model built into the page. It can ask for tools, read their results and reply, which is everything an agent loop needs. The code is what you'd write for the real thing (it uses Anthropic's Python SDK; OpenAI, Google and Microsoft SDKs follow the same pattern with different field names). The pretend model's decisions come from simple word-matching rules, not real AI, so it is far more predictable than a real model. To use a real one, copy the code into a notebook such as Google Colab and add your own key (see Python for AI, Module 5).

3.1 Five workflow patterns

Anthropic's Building effective agents describes five composable patterns that cover most production systems. Each is a predefined code path with LLM calls inside it.

PatternHow it worksUse when
Prompt chainingA sequence of LLM calls, each processing the previous output, with optional checks ("gates") betweenThe task splits cleanly into fixed steps — e.g. outline → check → draft
RoutingClassify the input, then send it to a specialised prompt, tool or modelDistinct categories need different handling — e.g. refunds vs technical support
ParallelisationRun calls simultaneously: sectioning (independent subtasks) or voting (several attempts, then aggregate)Speed, or more confidence through multiple perspectives
Orchestrator–workersA central LLM breaks the task down dynamically, delegates to worker LLMs, and synthesises resultsYou can't predict the subtasks in advance — e.g. changes across many files
Evaluator–optimiserOne LLM generates; another evaluates and gives feedback; repeatClear evaluation criteria and iterative refinement adds value — e.g. translation, search
Prompt chainingLLMgateLLMLLMRoutingRouterLLM ALLM BLLM CParallelisationInAggregateLLMLLMLLMOrchestrator–workersOrchestratorWorkerWorkerWorkerSynthesisEvaluator–optimiserGeneratorEvaluatorOutputdraftfeedbackapproved
Anthropic's five workflow patterns. Each is a predefined code path with LLM calls inside; real systems combine them.

3.2 Routing in code

Python · a routing workflowROUTES = {
    "REFUND":    "You handle refund requests. Policy: {policy}. Draft a reply to: {msg}",
    "TECHNICAL": "You are a product expert. Help with this care or usage question: {msg}",
    "OTHER":     "Politely answer or redirect this general enquiry: {msg}",
}

def handle(msg, policy):
    category = call_llm(
        "Classify this customer message as REFUND, TECHNICAL or OTHER. "
        f"Reply with one word only.\n\nMessage: {msg}")
    category = category if category in ROUTES else "OTHER"   # never trust the label blindly
    return category, call_llm(ROUTES[category].format(msg=msg, policy=policy))

POLICY = "damaged items can be refunded within 30 days"
for msg in ["My board arrived cracked, I'd like my money back",
            "Can I put the board in the dishwasher?",
            "Do you have a shop in Leeds?"]:
    category, reply = handle(msg, POLICY)
    print(f"[{category}] {msg}\n   {reply}\n")

Each message cost two calls: a cheap one to classify and one to answer with a prompt written for that kind of message. Routing also lets you send easy categories to a small, cheap model and hard ones to a larger model.

3.3 Evaluator–optimiser in code

Python · generate, critique, revisedef write_with_review(brief, max_rounds=3):
    draft = call_llm(f"Write a product description.\nBrief: {brief}")
    for round_no in range(1, max_rounds + 1):
        review = call_llm(
            "Review this product description against the brief. If it fully meets "
            "the brief, reply APPROVED. Otherwise list specific fixes.\n"
            f"Brief: {brief}\nDraft: {draft}")
        print(f"round {round_no}: {len(draft.split())} words\n{draft}\nreview:\n{review}\n")
        if review.startswith("APPROVED"):
            break
        draft = call_llm(f"Revise the draft using this feedback.\nFeedback: {review}\nBrief: {brief}\nDraft: {draft}")
    return draft

final = write_with_review("Large bamboo chopping board, mention it is hand-wash only, "
                          "mention the 45 cm size, under 30 words")

The first draft was enthusiastic, too long and missed both required facts; the review listed exactly those faults; the revision fixed them and the second review approved. Note the max_rounds limit: every loop needs a stopping condition. This pattern only earns its extra calls when the evaluator has clear criteria to check, as the brief gives it here.

3.4 Combining patterns

Real systems mix patterns: a router sends complex tickets to an orchestrator, whose workers run in parallel, with an evaluator checking the final reply. Start with one pattern, measure, and add complexity only when it demonstrably helps.

3.5 Prompt chaining with a gate in code

The evaluator above was a second LLM call. When the criteria can be checked mechanically, a few lines of Python make a cheaper and stricter gate between the links of a chain:

Python · a chain with a code gatedef gate(draft, max_words, must_mention):
    problems = [f"- Mention: {m}" for m in must_mention if m.lower() not in draft.lower()]
    if len(draft.split()) >= max_words:
        problems.append(f"- Cut to under {max_words} words (currently {len(draft.split())})")
    return problems

brief = "Large bamboo chopping board, mention it is hand-wash only, mention the 45 cm size, under 30 words"

draft = call_llm(f"Write a product description.\nBrief: {brief}")           # link 1
problems = gate(draft, 30, ["hand-wash only", "45 cm"])                     # gate: plain Python, free
print("gate found:", problems or "nothing")

if problems:                                                                # link 2 runs only if needed
    draft = call_llm("Revise the draft using this feedback.\nFeedback: " + "\n".join(problems) +
                     f"\nBrief: {brief}\nDraft: {draft}")
    problems = gate(draft, 30, ["hand-wash only", "45 cm"])

print("publish" if not problems else "send to a human", "->", draft)

Two LLM calls instead of four, and the gate cannot be talked round. A good rule: check with code whatever code can check (length, required words, valid JSON, a number within range) and save LLM evaluators for judgements such as tone.

3.6 Parallelisation: voting

For decisions where a mistake is costly, ask more than once and take the majority. Here three differently worded classifiers vote on each message:

Python · three votes, majority winsfrom collections import Counter

PROMPTS = [
    "Classify this customer message as REFUND, TECHNICAL or OTHER. Reply with one word only.\n\nMessage: {msg}",
    "You are a support triage assistant. Classify the message as REFUND, TECHNICAL or OTHER, one word only.\n\nMessage: {msg}",
    "Which queue should this go to? Classify as REFUND, TECHNICAL or OTHER. Answer with one word only.\n\nMessage: {msg}",
]

def vote(msg):
    labels = [call_llm(p.format(msg=msg)) for p in PROMPTS]     # a real system sends these at the same time
    winner, count = Counter(labels).most_common(1)[0]
    return winner if count >= 2 else "OTHER", labels

for msg in ["I want my money back for this cracked board", "How often should I oil the board?"]:
    winner, labels = vote(msg)
    print(f"{winner:10} votes={labels}   {msg}")

All three votes agree here because the pretend model is deterministic. A real model's answers vary from call to call, especially on borderline messages, and that variation is what voting smooths out. The price is three calls per message, so use it where being wrong matters: content moderation, security review, anything that triggers an irreversible action. In production the three calls are sent concurrently (with asyncio or a thread pool), so voting adds cost but little waiting time.

3.7 Measure the router before you trust it

A router is a classifier, so test it like one: a small set of real messages with the label a person would give, and a list of the misses.

Python · a test set for the routerTESTS = [
    ("I'd like a refund for the cracked board",          "REFUND"),
    ("Please can I have my money back",                  "REFUND"),
    ("The board arrived split in two, what are my options?", "REFUND"),
    ("Can it go in the dishwasher?",                     "TECHNICAL"),
    ("How do I oil the board?",                          "TECHNICAL"),
    ("My board smells odd after a week",                 "TECHNICAL"),
    ("Do you have a shop in Leeds?",                     "OTHER"),
    ("What are your opening hours?",                     "OTHER"),
]

def classify(msg):
    label = call_llm("Classify this customer message as REFUND, TECHNICAL or OTHER. "
                     f"Reply with one word only.\n\nMessage: {msg}")
    return label if label in ("REFUND", "TECHNICAL", "OTHER") else "OTHER"

misses = [(msg, want, got) for msg, want in TESTS if (got := classify(msg)) != want]
print(f"accuracy: {(len(TESTS) - len(misses)) / len(TESTS):.0%}\n")
for msg, want, got in misses:
    print(f"wanted {want:9} got {got:9} {msg}")

Six out of eight. Both misses are messages that never use the obvious word: a damaged item described without "refund", and a product problem described without a care term. The pretend model fails on these because it only matches words; a real model would do better, but it too will have misses, and they tend to be the indirect, emotional or mixed messages. Every miss lands in the wrong prompt and gets a confidently wrong reply, so the router's accuracy is a ceiling on the whole workflow's. Keep this test set, add every misrouted message you find in production, and re-run it whenever you change the prompt or the model.

Exercise: add a DELIVERY route

Delivery questions are currently lumped into OTHER. Add a fourth label, DELIVERY, to the classification prompt and to the list of accepted labels, then classify the three messages.

Your turnLABELS = ("REFUND", "TECHNICAL", "OTHER")       # add DELIVERY here...

def classify4(msg):
    label = call_llm("Classify this customer message as REFUND, TECHNICAL or OTHER. "   # ...and here
                     f"Reply with one word only.\n\nMessage: {msg}")
    return label if label in LABELS else "OTHER"

for msg in ["Where is my parcel?", "The courier left it in the rain", "Do you sell gift cards?"]:
    print(f"{classify4(msg):10} {msg}")
Show a solution
LABELS = ("REFUND", "TECHNICAL", "DELIVERY", "OTHER")

def classify4(msg):
    label = call_llm("Classify this customer message as REFUND, TECHNICAL, DELIVERY or OTHER. "
                     f"Reply with one word only.\n\nMessage: {msg}")
    return label if label in LABELS else "OTHER"

for msg in ["Where is my parcel?", "The courier left it in the rain", "Do you sell gift cards?"]:
    print(f"{classify4(msg):10} {msg}")
Exercise: count the calls

Patterns cost calls. Wrap call_llm in a function counted that adds one to a counter each time, then use it to count how many LLM calls the evaluator–optimiser loop makes for this brief.

Your turncalls = 0

def counted(prompt):
    ...   # add 1 to calls, then return call_llm(prompt)

brief = "Small bamboo board, mention it is hand-wash only, under 20 words"
# Write, review and revise using counted() instead of call_llm(), then print calls
Show a solution
calls = 0

def counted(prompt):
    global calls
    calls += 1
    return call_llm(prompt)

brief = "Small bamboo board, mention it is hand-wash only, under 20 words"
draft = counted(f"Write a product description.\nBrief: {brief}")
for _ in range(3):
    review = counted("Review this product description against the brief. If it fully meets the brief, "
                     f"reply APPROVED. Otherwise list specific fixes.\nBrief: {brief}\nDraft: {draft}")
    if review.startswith("APPROVED"):
        break
    draft = counted(f"Revise the draft using this feedback.\nFeedback: {review}\nBrief: {brief}\nDraft: {draft}")

print(draft)
print("LLM calls:", calls)

Key takeaways

  • Chaining: fixed sequential steps with gates.
  • Routing: classify, then specialise.
  • Parallelisation: sectioning for speed, voting for confidence.
  • Orchestrator–workers: dynamic decomposition.
  • Evaluator–optimiser: generate, critique, revise — with a round limit.
  • Check with code whatever code can check; keep LLM evaluators for judgement.
  • A router's accuracy caps the whole workflow: test it on labelled messages and keep the misses.