Before You Build an Agent: Five LLM Workflow Patterns That Cover Most Use Cases
Prompt chaining, routing, parallelization, orchestrator-workers and evaluator-optimizer: five deterministic patterns that solve most production LLM problems with less cost, latency and debugging pain than a free-roaming agent.
A team has a task: turn support emails into structured tickets, draft a reply, and flag risky ones. Someone says "let's build an agent." Three weeks later they have a loop that sometimes calls the wrong tool, occasionally runs forever, and costs 8x what the estimate said. Nobody can explain why it failed on Tuesday's batch.
Most of these problems did not need an agent. They needed a workflow: a fixed graph of LLM calls where your code decides the control flow. The distinction, popularised in Anthropic's "Building effective agents" write-up, is simple:
- Workflow: the code path is predetermined. The LLM fills in steps.
- Agent: the LLM decides the next step, including which tools to call and when to stop.
Workflows are cheaper, faster, easier to test and easier to debug. Reach for an agent only when you cannot enumerate the steps in advance. This post covers five workflow patterns, with runnable code, and a rule for choosing among them.
Why workflows first
| Property | Workflow | Agent |
|---|---|---|
| Control flow | Your code | The model |
| Latency | Predictable (N calls) | Variable (unbounded loop) |
| Cost | Predictable | Variable, can spike |
| Testing | Unit-test each step | Needs trajectory evals |
| Failure mode | A specific step is wrong | The plan itself is wrong |
| Best for | Known task shapes | Open-ended tasks |
Every step you hardcode is a step you can measure independently. That is the real advantage: you can put an eval on step 2 and know whether step 2 is the problem.
Setup
The examples use the Anthropic Python SDK, but nothing depends on it. Swap in any client. Check the official docs for current model names; the code reads the model from an environment variable on purpose.
import os, json, asyncio
from anthropic import Anthropic, AsyncAnthropic
MODEL = os.environ["LLM_MODEL"] # set to a current model id from the docs
client = Anthropic()
aclient = AsyncAnthropic()
def llm(prompt: str, system: str = "", max_tokens: int = 1024) -> str:
msg = client.messages.create(
model=MODEL,
max_tokens=max_tokens,
system=system,
messages=[{"role": "user", "content": prompt}],
)
return msg.content[0].text
async def allm(prompt: str, system: str = "", max_tokens: int = 1024) -> str:
msg = await aclient.messages.create(
model=MODEL,
max_tokens=max_tokens,
system=system,
messages=[{"role": "user", "content": prompt}],
)
return msg.content[0].text
Pattern 1: Prompt chaining
Problem: One giant prompt does extraction, reasoning and formatting at once, and quality is mediocre on all three.
Idea: Split the task into sequential steps. Each call gets a narrower job. Between steps, add a programmatic gate that checks the output and stops early on failure.
def email_to_ticket(email: str) -> dict:
# Step 1: extract facts only
facts = llm(
f"Extract customer name, product, issue, and urgency from this email as JSON.\n\n{email}",
system="Return only valid JSON with keys: name, product, issue, urgency.",
)
data = json.loads(facts)
# Gate: deterministic validation, no LLM needed
if not data.get("issue") or data.get("urgency") not in {"low", "medium", "high"}:
raise ValueError(f"Extraction failed gate: {data}")
# Step 2: draft a reply from the validated facts, not the raw email
reply = llm(
f"Write a concise, polite support reply for this ticket:\n{json.dumps(data)}",
system="You are a support agent. No promises about refunds or timelines.",
)
return {"ticket": data, "draft_reply": reply}
Use when: the task decomposes cleanly into ordered subtasks. Trade-off: more calls means more latency, in exchange for accuracy. If you use structured outputs for step 1, the json.loads risk disappears; see our structured outputs guide.
Pattern 2: Routing
Problem: Inputs vary widely. A single prompt tuned for refunds is bad at technical bugs, and a single large model is wasteful for trivial questions.
Idea: Classify the input first, then dispatch to a specialised prompt, tool set, or model size.
ROUTES = {
"billing": {"system": "You handle billing. Be precise about amounts.", "model": MODEL},
"technical": {"system": "You are a senior support engineer. Ask for logs.", "model": MODEL},
"general": {"system": "Answer briefly and kindly.", "model": MODEL},
}
def route(query: str) -> str:
label = llm(
f"Classify into exactly one of billing, technical, general.\n\nQuery: {query}\n\nLabel:",
max_tokens=5,
).strip().lower()
return label if label in ROUTES else "general" # safe fallback
def answer(query: str) -> str:
cfg = ROUTES[route(query)]
return llm(query, system=cfg["system"])
The classifier can be a small model, or not an LLM at all. For high volume, an embeddings classifier is far cheaper; see LLM classification at scale and model routing for cost.
Always include a fallback route. The router will eventually emit a label you did not expect.
Pattern 3: Parallelization
Two flavours, both embarrassingly useful.
Sectioning: split independent subtasks and run them concurrently. Voting: run the same task several times and aggregate for reliability.
async def review_pr(diff: str) -> dict:
aspects = {
"security": "Find security issues in this diff.",
"performance": "Find performance problems in this diff.",
"style": "Find readability and naming issues in this diff.",
}
results = await asyncio.gather(*[
allm(f"{instruction}\n\n{diff}") for instruction in aspects.values()
])
return dict(zip(aspects.keys(), results))
async def vote(prompt: str, n: int = 5) -> str:
answers = await asyncio.gather(*[allm(prompt) for _ in range(n)])
from collections import Counter
return Counter(a.strip() for a in answers).most_common(1)[0][0]
# asyncio.run(review_pr(diff))
Sectioning cuts wall-clock latency to roughly the slowest branch. Voting trades cost for reliability, and only helps when the answer space is small enough to compare; see self-consistency and best-of-N. Mind your rate limits: fan-out of 50 calls will hit them.
Pattern 4: Orchestrator-workers
Problem: You cannot know the subtasks in advance. "Update this feature" might touch two files or twelve.
Idea: A planner LLM decomposes the task at runtime into subtasks; worker calls execute them; a final step synthesises. The structure is still fixed (plan, fan out, merge), but the number and content of subtasks are dynamic. This is the bridge between workflows and agents.
async def orchestrate(task: str, context: str) -> str:
plan_raw = await allm(
f"Break this task into 2-6 independent subtasks. Return a JSON list of strings.\n\nTask: {task}\n\nContext:\n{context}",
system="Return only a JSON list.",
)
subtasks = json.loads(plan_raw)[:6] # hard cap on fan-out
outputs = await asyncio.gather(*[
allm(f"Subtask: {s}\n\nContext:\n{context}") for s in subtasks
])
return await allm(
"Combine these partial results into one coherent answer.\n\n"
+ "\n\n".join(f"## {s}\n{o}" for s, o in zip(subtasks, outputs))
)
Note the hard cap on subtasks. An uncapped planner is how a bill gets surprising. For coding-specific variants, see multi-agent coding orchestration patterns.
Pattern 5: Evaluator-optimizer
Problem: First drafts are decent but need to meet a clear quality bar: tone, correctness against a rubric, translation fidelity.
Idea: One call generates, another critiques against explicit criteria, and the loop continues until the critic passes it or you hit a cap.
def generate_with_critic(brief: str, criteria: list[str], max_rounds: int = 3) -> str:
draft = llm(f"Write this:\n{brief}")
for _ in range(max_rounds):
verdict = json.loads(llm(
"Evaluate the draft against each criterion. "
'Return JSON: {"pass": bool, "feedback": "..."}\n\n'
f"Criteria: {criteria}\n\nDraft:\n{draft}",
system="Return only JSON.",
))
if verdict["pass"]:
return draft
draft = llm(
f"Revise the draft using this feedback.\n\nFeedback: {verdict['feedback']}\n\nDraft:\n{draft}"
)
return draft # best effort after the cap
This only works when the criteria are specific and checkable. "Make it better" gives you a critic that always finds something to say. Where possible, make criteria deterministic: word count, required fields, a regex, a unit test. Use an LLM critic only for what code cannot check, and calibrate it; see LLM-as-judge calibration.
Choosing a pattern
| If your task is... | Use | Watch out for |
|---|---|---|
| Sequential, each step simpler than the whole | Prompt chaining | Error compounding across steps |
| Diverse inputs needing different handling | Routing | Misroutes; always add a fallback |
| Independent subtasks, or a need for reliability | Parallelization | Rate limits and cost multiplication |
| Subtasks unknown until runtime | Orchestrator-workers | Unbounded fan-out |
| Clear quality bar, iterative improvement helps | Evaluator-optimizer | Vague critic, endless loops |
| None of the above, steps genuinely open-ended | Agent | Cost, latency, debuggability |
Patterns compose. A real system is often a router in front of a chain whose middle step is a parallel fan-out.
Common pitfalls
- Chaining without gates. A bad step 1 silently poisons steps 2 to 5. Validate between steps with plain code.
- Loops without caps. Every evaluator-optimizer loop and every planner needs a maximum on rounds and fan-out, plus a cost budget. See agent loop control.
- Using the biggest model everywhere. Routers, gates and simple extraction steps usually run fine on a smaller model. Measure before assuming.
- No per-step evals. The main benefit of a workflow is isolating failures. Log each step's input and output, and build a small eval set per step; see LLM observability and tracing.
- Unvalidated JSON between steps. Use structured outputs or schema validation, and handle parse failures explicitly.
- Retrying non-idempotent steps. If a step sends an email or writes to a database, retries need idempotency keys; see durable execution.
- Adding complexity before a baseline. Start with one good prompt and an eval. Add a pattern only when the eval shows a specific failure it addresses.
Checklist before graduating to an agent
- I have a single-prompt baseline with measured accuracy
- I tried chaining or routing and measured the improvement
- I can state why the steps cannot be enumerated in advance
- I have a step budget, a cost budget, and a stop condition
- I have trajectory-level evals, not just final-answer checks
If you cannot tick the first three, you probably do not need an agent yet.
Next steps
Pick one LLM feature you run today as a single large prompt. Write down its failure cases from the last 50 production examples, and tag each as an extraction error, a routing error, a reasoning error or a formatting error. Then apply the one pattern that targets the largest bucket, and compare accuracy, latency and cost before and after. Keep the pattern only if the numbers justify it.
Designing, evaluating and shipping these systems end to end is what we practise in the Joinloop AI Engineering cohort.
Want to build this yourself?
Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.