Chaining, Routing and Parallel Calls
Build a refund-dispute workflow that routes, chains and parallelises model calls, with Pydantic-typed outputs, validation gates between steps and a voting step that sends ties to a person.
Contentsand lesson path
On this page
- Three building blocks for fixed workflows
- Worked example: a refund-dispute workflow with gates
- What a fixed workflow buys you
- Practice questions
- Apply it
- Review prompt
Lessons of Workflow & Planning Patterns
- Workflows Versus Agents: A Decision Guide Concept · 15 min
- Chaining, Routing and Parallel Calls Worked example · 25 min
- Lab: Plan, Execute, Replan Lab · 25 min
- Reflection Loops That Actually Help Worked example · 20 min
- Measuring a Pattern Against a Baseline Lab · 20 min
- Check: Pick the Pattern Knowledge check · 8 questions
What you will learn
- Implement prompt chaining, routing and parallelization with structured intermediate outputs and checks between steps.
Prerequisites: Agent Loops & ReAct
01. Three building blocks for fixed workflows
Many LLM features do not need an agent. When you know the steps in advance, three patterns described in Anthropic's "Building effective agents" cover most designs, and each step can be tested on its own:
- Prompt chaining: a fixed sequence of model calls, where each step works on the output of the one before. Between steps you add a gate: a check in code that the output has the right shape and makes sense before the next step uses it.
- Routing: classify the input first, then send it to a specialised prompt or handler. Billing disputes and outage reports need different prompts, tools and tests; one prompt for both tends to do each less well.
- Parallelisation: run calls at the same time. In sectioning, independent parts of a task run side by side, such as fetching a transaction and a customer profile. In voting, the same task runs several times and the answers are combined, which trades extra calls for more confidence in a judgement.
Errors compound along a chain. If step 1 extracts the wrong amount, step 2 treats it as fact, and step 3 writes a polite, confident email about the wrong amount. A gate turns that into an early, cheap stop. The simplest robust gate is a schema: ask the model for JSON, parse it into a typed object, and treat anything that does not parse as a failed step, not as data.
02. Worked example: a refund-dispute workflow with gates
The problem: a support inbox receives refund disputes. For each message the workflow must decide whether it is a billing dispute, extract the transaction and the amount, check them against the payment record, and decide whether to approve a refund. Anything uncertain goes to a person. Five sample messages cover the paths you need to see: a clean approval, an unsure router, a malformed extraction, a split vote and a message that is not about billing.
You need Python 3.12 or later and Pydantic 2 (pip install "pydantic>=2.7"; tested with Pydantic 2.14.3 on Python 3.12.13). Create a folder workflows and save the four files below into it. The model is a scripted fake that returns the JSON text a real model would return, so the example runs offline and prints the same output every time.
Step 1: a typed output for every model step. Literal limits a field to a closed set, so the router can only answer with one of three intents, and other is an explicit fallback for messages that fit none of the specialised paths. Field adds limits: a confidence between 0 and 1, an amount above zero with at most two decimal places, and a transaction ID that matches a pattern.
"""Typed outputs: every model step must return JSON that parses into one of these."""
from decimal import Decimal
from typing import Literal
from pydantic import BaseModel, Field
class RouteDecision(BaseModel):
intent: Literal["billing_dispute", "technical", "other"] # "other" = fallback
confidence: float = Field(ge=0, le=1)
class DisputeFacts(BaseModel):
transaction_id: str = Field(pattern=r"^tx-\d+$")
amount: Decimal = Field(gt=0, decimal_places=2)
reason: Literal["duplicate", "not_received", "unrecognised"]
class RefundVote(BaseModel):
decision: Literal["approve", "deny"]
reason: str = Field(max_length=200)Step 2: the stand-in model. complete() looks up a scripted reply and counts calls per message. Message m3 gets an extraction with "amount": "about 60", and m4 gets one vote that is chatty text instead of JSON: both are mistakes real models make. To use a real provider, replace the body of complete() with a call that sends the prompt and the context and requests structured output using the schema from RouteDecision.model_json_schema(); most providers offer a JSON-schema or strict tool mode for this. Keep the validation in the next step either way.
"""Scripted stand-in for a model API: returns the JSON text a model would return,
keyed by (prompt name, message id), so every run is the same, offline and free."""
import asyncio
from collections import Counter
CALLS = Counter() # model calls per message, to see where a gate stopped the chain
APPROVE = '{"decision": "approve", "reason": "duplicate charge on the statement"}'
DENY = '{"decision": "deny", "reason": "item marked delivered and signed for"}'
SCRIPT = {
("route", "m1"): '{"intent": "billing_dispute", "confidence": 0.93}',
("route", "m2"): '{"intent": "billing_dispute", "confidence": 0.55}',
("route", "m3"): '{"intent": "billing_dispute", "confidence": 0.91}',
("route", "m4"): '{"intent": "billing_dispute", "confidence": 0.88}',
("route", "m5"): '{"intent": "other", "confidence": 0.97}',
("extract", "m1"):
'{"transaction_id": "tx-101", "amount": "149.00", "reason": "duplicate"}',
("extract", "m3"):
'{"transaction_id": "tx-103", "amount": "about 60", "reason": "duplicate"}',
("extract", "m4"):
'{"transaction_id": "tx-104", "amount": "75.00", "reason": "not_received"}',
("vote", "m1"): [APPROVE, APPROVE, APPROVE],
("vote", "m4"): [APPROVE, DENY, "Sure! I would approve this refund."],
}
async def complete(prompt, message_id, context=None, sample=0):
"""A real call sends the prompt, the context and a JSON schema to the model."""
CALLS[message_id] += 1
await asyncio.sleep(0.1) # stands in for network latency
reply = SCRIPT[(prompt, message_id)]
return reply[sample] if isinstance(reply, list) else replyStep 3: the gates. ask() calls the model and parses the reply with model_validate_json. If the reply does not fit the schema, Pydantic raises ValidationError, and the gate turns it into NeedsHuman with the field and the reason. vote() is the voting pattern: it runs the same prompt three times in parallel, marks replies that fail validation as invalid, and accepts a decision only if a strict majority of all three runs agree (two of three). Anything less, such as one approve, one deny and one invalid reply, is a tie, and a tie goes to a person rather than to a coin flip.
"""Gates between steps: a failed gate stops the chain and hands the case to a person."""
import asyncio
from collections import Counter
from pydantic import ValidationError
from fake_llm import complete
from schemas import RefundVote
class NeedsHuman(Exception):
"""Raised by a gate; the message says which check failed."""
async def ask(prompt, schema, message_id, context=None):
raw = await complete(prompt, message_id, context)
try:
return schema.model_validate_json(raw) # schema gate
except ValidationError as err:
first = err.errors()[0]
field = first["loc"][0] if first["loc"] else "reply" # () if not JSON
raise NeedsHuman(f"{prompt} invalid: {field}: {first['msg']}") from None
async def vote(message_id, context, n=3):
"""Voting: the same prompt n times in parallel; a strict majority must agree."""
replies = await asyncio.gather(
*(complete("vote", message_id, context, sample=i) for i in range(n)))
votes = []
for raw in replies:
try:
votes.append(RefundVote.model_validate_json(raw).decision)
except ValidationError:
votes.append("invalid") # counted, but it cannot win
tally = Counter(v for v in votes if v != "invalid")
decision, count = tally.most_common(1)[0] if tally else ("none", 0)
if count * 2 <= n: # 1 of 3 is not a majority: a tie goes to a person
raise NeedsHuman(f"no majority in votes: {', '.join(votes)}")
return decision, votesStep 4: the chain. handle() routes, extracts, fetches and votes, with a gate after each model step. Two of the gates are not about schemas. The router's confidence must reach 0.8 before the code branches on its answer, and the extracted amount must equal the amount in the payment record. Valid JSON can still be wrong, so cross-check facts against a system of record where you have one.
The transaction and the profile do not depend on each other, so asyncio.gather fetches them at the same time, and the pair takes about as long as the slower call (0.1 s here) instead of the sum. The amount check and the vote need the transaction, so they run after it. Running a step in parallel with the step whose output it needs is a bug, not an optimisation: the step would judge a placeholder, not the real charge.
"""Route, chain and parallelise a refund dispute, with a gate after every step."""
import asyncio
from decimal import Decimal
from fake_llm import CALLS
from gates import NeedsHuman, ask, vote
from schemas import DisputeFacts, RouteDecision
TRANSACTIONS = {"tx-101": {"amount": "149.00", "status": "settled"},
"tx-104": {"amount": "75.00", "status": "settled"}}
async def fetch_transaction(tx_id):
await asyncio.sleep(0.1) # payment gateway
return TRANSACTIONS[tx_id]
async def fetch_profile(message_id):
await asyncio.sleep(0.1) # CRM; needs only the message's customer
return {"refunds_this_year": 0}
async def handle(message_id):
route = await ask("route", RouteDecision, message_id) # step 1: route
if route.confidence < 0.8: # gate: confident enough to branch on
raise NeedsHuman(f"router confidence {route.confidence} < 0.8")
if route.intent != "billing_dispute":
return f"sent to the {route.intent} queue"
facts = await ask("extract", DisputeFacts, message_id) # step 2: chain
tx, profile = await asyncio.gather( # step 3: independent calls in parallel
fetch_transaction(facts.transaction_id), fetch_profile(message_id))
if Decimal(tx["amount"]) != facts.amount: # gate: matches the record
raise NeedsHuman(f"extracted {facts.amount}, record says {tx['amount']}")
context = {"facts": facts.model_dump(mode="json"), "tx": tx, "profile": profile}
decision, votes = await vote(message_id, context) # step 4: voting
return f"{decision} refund of ${facts.amount} (votes: {', '.join(votes)})"
async def main():
for message_id in ("m1", "m2", "m3", "m4", "m5"):
try:
outcome = await handle(message_id)
except NeedsHuman as why:
outcome = f"human review: {why}"
print(f"{message_id} calls={CALLS[message_id]} {outcome}")
if __name__ == "__main__":
asyncio.run(main())python3 pipeline.pym1 calls=5 approve refund of $149.00 (votes: approve, approve, approve)
m2 calls=1 human review: router confidence 0.55 < 0.8
m3 calls=2 human review: extract invalid: amount: Input should be a valid decimal
m4 calls=5 human review: no majority in votes: approve, deny, invalid
m5 calls=1 sent to the other queueRead the output line by line. m1 passes every gate and gets three approvals, for five model calls. m2 stops after one call because the router is unsure, so nothing downstream is spent. m3 stops at the schema gate after two calls and names the field and the reason, which is what a person needs to fix it, or what you would send back to the model in a retry. m4 passes the schema and record gates, but the votes split, so a person decides. m5 goes to the other queue after one call.
Because the path is fixed, each message uses at most five model calls, a number you can budget for. That bound says nothing about how often the decisions are right: measure that on a labelled set of disputes.
03. What a fixed workflow buys you
Fixed workflows like this one have practical advantages over open-ended loops. Each path has a known maximum number of model calls, so the cost per message can be budgeted. Each step has a typed input and output, so you can test one prompt with recorded inputs and see where a regression starts. Small models can handle routing and extraction while a larger model handles the hard judgement; how much that saves depends on your traffic and prices, so measure cost and quality per step.
The price is flexibility. If the right steps depend on what earlier steps find, a workflow needs a branch for every case, and an agent may fit better, as the decision guide explains.
04. Practice questions
05. Apply it
Apply this to a workflow of your own:
- Give every model step a Pydantic (or Zod) model, request structured output with its schema, and still validate the reply before the next step uses it.
- Add at least one gate that checks meaning, not only shape: a cross-check against a record, a business rule or a threshold.
- Give the router a closed set of labels with an explicit
other, and a confidence threshold below which a person decides. - Fetch independent data with
asyncio.gatheror a thread pool, and keep dependent steps in sequence. - Use voting for judgements where a wrong answer is costly, and decide before you build it what a tie means.
- Log which gate stopped each case; the counts show which step needs a better prompt.
06. Review prompt
Without looking back, describe the four steps of the dispute workflow and the gate after each. Explain why a schema gate alone would let a wrong amount through, and what the voting step does with a tie or an invalid reply.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.