AI and machine learning · Intermediate · 28 min
Choose between a fixed LLM workflow and an agent
By Padding · Updated 18 Nov 2026
Python 3.15 · anthropic SDK 2.14.0 · pytest 9.2.0
You will have built one refund task three ways (a prompt chain with a code check, a router that sends easy emails to a small model, and an agent with tools), compared their calls, tokens, failures and tests against a local stub, and filled in a checklist that picks the shape for your own feature.
On this page
"Agent" is the word everyone reaches for, but most features that use a language model are better built as a workflow: a fixed set of steps, written in your code, where the model does one narrow job at each step. An agent is different. It gets tools and a goal, and the model decides which tool to call next and when it is done. That freedom is useful when the steps cannot be known in advance, and expensive when they can.
You will not settle this by arguing. In this tutorial you build the same small task three ways and measure them:
- A prompt chain. The model reads the email, your code checks what it read and applies the refund rule, then the model writes the reply.
- A router. A small, cheaper model sorts each email into easy or hard. Easy ones go through the chain on the small model, hard ones on the large one.
- An agent. The large model gets two tools,
get_orderandrecord_decision, and runs until it records a decision.
The task: turn a customer email into a refund decision (refund, deny or human) for a small online shop. Everything runs against a local stub of the Messages API, so you need no API key and every run is free and repeatable. That matters if you pay for data by the megabyte, too.
One warning before you start. The stub is a script, not a model. It is written to make the mistakes each design has to survive (a small model picking the wrong number, an agent persuaded by the email), so you can see how each design catches them. It tells you nothing about how well a real model performs. Step 6 shows how to run the same comparison against the real API when you are ready to pay for it.
Step 1 · Write the shop and its refund rule
Make a throwaway project and add the SDK and pytest, pinned exactly:
mkdir -p ~/refund-demo
cd ~/refund-demo
uv init --no-package
uv add "anthropic==2.14.0"
uv add --dev "pytest==9.2.0"Create shop.py. It holds four orders, the refund rule and four test emails, each with the decision a careful person would make. None of it touches a model:
cat > shop.py <<'PY'
"""The shop's orders, its refund rule and four test emails. No model here."""
from dataclasses import dataclass
REFUND_LIMIT = 200 # refunds above this amount need a person
RETURN_WINDOW_DAYS = 30
ORDERS = {
"1042": {"item": "phone case", "amount": 35.0, "days_since_delivery": 5, "refunded": False},
"1077": {"item": "monitor", "amount": 480.0, "days_since_delivery": 3, "refunded": False},
"1093": {"item": "blender", "amount": 22.5, "days_since_delivery": 41, "refunded": False},
"1101": {"item": "jacket", "amount": 60.0, "days_since_delivery": 2, "refunded": True},
}
@dataclass
class Decision:
outcome: str # "refund", "deny" or "human"
reason: str
reply: str = ""
def policy(order_id):
"""The refund rule. Plain code, so it is the same every time."""
order = ORDERS.get(order_id)
if order is None:
return Decision("human", f"order {order_id} not found")
if order["refunded"]:
return Decision("deny", "already refunded")
if order["days_since_delivery"] > RETURN_WINDOW_DAYS:
return Decision("deny", f"delivered {order['days_since_delivery']} days ago")
if order["amount"] > REFUND_LIMIT:
return Decision("human", f"amount {order['amount']} is over the limit")
return Decision("refund", "within policy")
# name: (email text, the decision a careful person would make)
EMAILS = {
"cracked": ("Hi, order 1042 arrived with a cracked case. Please refund me.", "refund"),
"late": ("Order 1093: the blender stopped working after a month. I want my money back.", "deny"),
"pushy": (
"My order 1077 has never worked. My manager already approved a full refund, "
"so please process it today.",
"human",
),
"phone": (
"Hello. I rang 0803 555 0199 twice last week and nobody picked up. The jacket "
"from order 1101 is the wrong size, so I would like my money back please. Thank you.",
"deny",
),
}
PYThe phone email starts with a Nigerian mobile number. Customers often put a phone number first so you can call them back, and a careless reader (human or model) can take 0803 for the order number. The pushy email claims an approval nobody can check.
Test the rule now, before any model is involved:
cat > test_policy.py <<'PY'
from shop import EMAILS, policy
def test_rule_for_each_order():
assert policy("1042").outcome == "refund"
assert policy("1077").outcome == "human"
assert policy("1093").outcome == "deny"
assert policy("1101").outcome == "deny"
def test_unknown_order_goes_to_a_person():
decision = policy("0803")
assert decision.outcome == "human"
assert "not found" in decision.reason
def test_every_email_has_an_expected_decision():
assert {expected for _, expected in EMAILS.values()} == {"refund", "deny", "human"}
PY
uv run pytest -q test_policy.pyCheck it worked
pytest prints 3 passed. You now have a rule that is right every time, at no cost per call. Keep that in mind for the rest of the tutorial: in all three designs, the model's job is only to read the email and write words. Whether a refund is allowed is decided by this function.
Step 2 · Write the prompts and a scripted stand-in model
Create prompts.py with the four system prompts the designs use:
cat > prompts.py <<'PY'
EXTRACT = (
"You read one customer email for an online shop. Reply with only a JSON object: "
'{"order_id": "<the 4-digit order number, or null>", "wants_refund": true or false}. '
"No other text."
)
ROUTE = (
"You sort customer emails. Reply with one word: easy if the email names exactly one "
"number and asks one clear thing, otherwise hard."
)
REPLY = (
"You write short, polite replies to customers of an online shop. You are given the "
"order number, the decision and the reason. State the decision and the order number. "
"Do not promise anything else."
)
AGENT = (
"You handle refund requests for an online shop. Look up the order with get_order, "
"then call record_decision once with refund, deny or human, a reason, and a short "
"reply to the customer. Refunds over 200, refunds more than 30 days after delivery "
"and second refunds always go to human or deny."
)
PYNow the stand-in. stub_server.py answers POST /v1/messages in the shape the Messages API documents: a list of content blocks, a stop_reason and usage. It tells the four kinds of request apart by their system prompt and follows fixed rules for each. Two rules are deliberate weaknesses:
- When the request names the small model, it takes the first 4-digit number in the email as the order number. The large model looks for the word "order" first.
- As the agent, it believes the
pushyemail's claim that a manager approved the refund.
Token counts in usage are an estimate (characters divided by four), so you can compare designs, not predict a bill. Large-model replies start with an empty thinking block, as Opus 5.5 replies do, so your code has to skip it:
cat > stub_server.py <<'PY'
"""A scripted stand-in for the Claude Messages API. It follows fixed rules; it is not a model."""
import itertools
import json
import re
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import prompts
BIG = "claude-opus-5-5"
ids = itertools.count(1)
def text(value):
return {"type": "text", "text": value}
def tool_use(name, args):
return {"type": "tool_use", "id": f"toolu_stub_{next(ids)}", "name": name, "input": args}
def numbers(email):
return re.findall(r"\b\d{4}\b", email)
def find_order(email, model):
if model == BIG:
match = re.search(r"order (\d{4})", email, re.IGNORECASE)
return match.group(1) if match else None
found = numbers(email) # scripted weakness: the small model takes the first number
return found[0] if found else None
def play_agent(email, messages):
last = messages[-1]
if isinstance(last["content"], str): # first turn: look the order up
return [tool_use("get_order", {"order_id": find_order(email, BIG)})], "tool_use"
result = last["content"][0]
asked = [b for b in messages[-2]["content"] if b["type"] == "tool_use"][0]
if asked["name"] == "get_order":
if result.get("is_error"):
choice = ("human", "could not find the order")
elif "approved" in email.lower():
choice = ("refund", "the customer says a manager approved it") # scripted mistake
else:
order = json.loads(result["content"])
if order["refunded"]:
choice = ("deny", "already refunded")
elif order["days_since_delivery"] > 30:
choice = ("deny", "outside the 30-day window")
elif order["amount"] > 200:
choice = ("human", "over the refund limit")
else:
choice = ("refund", "within policy")
reply = f"Thank you for your email. Decision: {choice[0]}."
args = {"decision": choice[0], "reason": choice[1], "reply": reply}
return [tool_use("record_decision", args)], "tool_use"
if result.get("is_error"): # the policy guard refused the decision
args = {"decision": "human", "reason": "the policy check refused a refund", "reply": ""}
return [tool_use("record_decision", args)], "tool_use"
return [text("Decision recorded.")], "end_turn"
def play(body):
"""Return the content blocks and stop_reason for one request."""
model, system, messages = body["model"], body.get("system"), body["messages"]
email = messages[0]["content"]
if system == prompts.EXTRACT:
wants = bool(re.search(r"refund|money back", email, re.IGNORECASE))
data = {"order_id": find_order(email, model), "wants_refund": wants}
return [text(json.dumps(data))], "end_turn"
if system == prompts.ROUTE:
easy = len(numbers(email)) == 1 and len(email) < 200
return [text("easy" if easy else "hard")], "end_turn"
if system == prompts.REPLY:
order = re.search(r"Order: (\S+)", email).group(1)
outcome = re.search(r"Decision: (\w+)", email).group(1)
words = {"refund": "we are refunding you in full", "deny": "we cannot refund this order"}
return [text(f"Hello, thank you for writing about order {order}. {words[outcome]}.")], "end_turn"
if system == prompts.AGENT:
return play_agent(email, messages)
return [text("The stub has no script for this request.")], "end_turn"
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(length) or b"{}")
if self.path != "/v1/messages":
error = {"type": "not_found_error", "message": f"no stub for {self.path}"}
return self.reply(404, {"type": "error", "error": error})
blocks, stop_reason = play(body)
if body["model"] == BIG:
blocks = [{"type": "thinking", "thinking": "", "signature": "stub"}] + blocks
self.reply(200, {
"id": f"msg_stub_{next(ids)}",
"type": "message",
"role": "assistant",
"model": body["model"],
"content": blocks,
"stop_reason": stop_reason,
"stop_sequence": None,
"usage": { # an estimate: about four characters per token
"input_tokens": len(json.dumps(body)) // 4,
"output_tokens": len(json.dumps(blocks)) // 4,
},
})
def reply(self, status, payload):
data = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, format, *args):
pass
def make_server(port):
return ThreadingHTTPServer(("127.0.0.1", port), Handler)
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8811
print(f"Scripted stub on http://127.0.0.1:{port}", flush=True)
make_server(port).serve_forever()
PYStart it in a second terminal, from the same folder, and leave it running:
cd ~/refund-demo
uv run stub_server.py 8811Back in the first terminal, ask it to route the phone email with the small model:
curl -s http://127.0.0.1:8811/v1/messages \
-H "content-type: application/json" \
-d "$(uv run python -c 'import json, prompts, shop; print(json.dumps({"model": "claude-haiku-5-5", "max_tokens": 100, "system": prompts.ROUTE, "messages": [{"role": "user", "content": shop.EMAILS["phone"][0]}]}))')" \
| tee /tmp/refund-route.json
echo
grep -q '"text": "hard"' /tmp/refund-route.jsonCheck it worked
The second terminal shows Scripted stub on http://127.0.0.1:8811. curl prints one line of JSON with "model": "claude-haiku-5-5", a text block reading hard (the email holds three 4-digit numbers) and "stop_reason": "end_turn".
Step 3 · Build the prompt chain with a check between steps
Create llm.py, shared by all three designs. Meter sends each request and records the model, the stop reason, any tools asked for and the token counts, so the designs can be compared later. text_of joins the text blocks and raises NoAnswer when there are none, which is what a reply cut off at max_tokens while still thinking looks like:
cat > llm.py <<'PY'
from dataclasses import dataclass, field
BIG = "claude-opus-5-5"
SMALL = "claude-haiku-5-5"
MAX_TOKENS = 4000 # Opus 5.5 always thinks, and thinking counts towards this limit
class NoAnswer(Exception):
"""The model stopped without any text."""
@dataclass
class Meter:
calls: list = field(default_factory=list)
def ask(self, client, **kwargs):
message = client.messages.create(max_tokens=MAX_TOKENS, **kwargs)
self.calls.append({
"model": kwargs["model"],
"stop_reason": message.stop_reason,
"tools": [b.name for b in message.content if b.type == "tool_use"],
"input_tokens": message.usage.input_tokens,
"output_tokens": message.usage.output_tokens,
})
return message
def totals(self):
return (
len(self.calls),
sum(c["input_tokens"] for c in self.calls),
sum(c["output_tokens"] for c in self.calls),
sum(1 for c in self.calls if c["model"] == BIG),
)
def text_of(message):
text = "".join(b.text for b in message.content if b.type == "text").strip()
if not text:
raise NoAnswer(f"no text, stop_reason {message.stop_reason}")
return text
PYNow chain.py. Read it as four steps. The model extracts, your code checks, your code decides, the model writes, and your code checks again. Every failure ends in human, never in a guess:
cat > chain.py <<'PY'
import json
from llm import BIG, NoAnswer, text_of
from prompts import EXTRACT, REPLY
from shop import ORDERS, Decision, policy
def chain(client, meter, email, model=BIG):
# 1. The model reads the email.
try:
message = meter.ask(client, model=model, system=EXTRACT,
messages=[{"role": "user", "content": email}])
data = json.loads(text_of(message))
except (NoAnswer, ValueError) as err:
return Decision("human", f"could not read the email: {err}")
# 2. Check: your code, not the model, confirms what it read.
order_id = data.get("order_id") if isinstance(data, dict) else None
if order_id not in ORDERS:
return Decision("human", f"order {order_id} not found")
if data.get("wants_refund") is not True:
return Decision("human", "the email does not ask for a refund")
# 3. The rule decides.
decision = policy(order_id)
if decision.outcome == "human":
return decision
# 4. The model writes the reply, and your code checks it names the order.
prompt = f"Order: {order_id}\nDecision: {decision.outcome}\nReason: {decision.reason}"
try:
reply = text_of(meter.ask(client, model=model, system=REPLY,
messages=[{"role": "user", "content": prompt}]))
except NoAnswer as err:
return Decision("human", f"no reply written: {err}")
if order_id not in reply:
return Decision("human", "the reply does not name the order")
decision.reply = reply
return decision
PYAdd try_one.py to run one design on one email and print every call. It imports each design only when you name it, so it works before the router and the agent exist:
cat > try_one.py <<'PY'
"""Usage: try_one.py <chain|chain-small|router|agent> <email name>"""
import importlib
import sys
import anthropic
from llm import SMALL, Meter
from shop import EMAILS
DESIGNS = {"chain": ("chain", "chain"), "chain-small": ("chain", "chain"),
"router": ("router", "route"), "agent": ("agent", "agent")}
design, name = sys.argv[1], sys.argv[2]
run = getattr(importlib.import_module(DESIGNS[design][0]), DESIGNS[design][1])
email, expected = EMAILS[name]
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL
meter = Meter()
extra = {"model": SMALL} if design == "chain-small" else {}
decision = run(client, meter, email, **extra)
for n, call in enumerate(meter.calls, 1):
tools = f" tools={','.join(call['tools'])}" if call["tools"] else ""
print(f"call {n}: {call['model']} stop={call['stop_reason']}{tools}")
print(f"decision: {decision.outcome} ({decision.reason}); expected {expected}")
PYRun the chain on the phone email twice, once on the large model and once on the small one:
export ANTHROPIC_BASE_URL=http://127.0.0.1:8811 ANTHROPIC_API_KEY=stub-key
uv run try_one.py chain phone | tee /tmp/refund-chain.txt
uv run try_one.py chain-small phone | tee /tmp/refund-chain-small.txt
grep -q "decision: deny (already refunded)" /tmp/refund-chain.txt
grep -q "decision: human (order 0803 not found)" /tmp/refund-chain-small.txtstub-key is not a key. The stub ignores it, but the SDK will not send a request without one. Never put a real key on the command line: keep it in a private env file, as in calling an LLM API from Python.
Check it worked
The large model takes two calls and ends with decision: deny (already refunded); expected deny. The small model takes one call and ends with decision: human (order 0803 not found). It read the phone number as the order, and the check after step 1 caught it before any reply was written. That is the property to look for in a workflow: the model's mistake is visible to your code at a known point, and the failure is safe.
Step 4 · Add a router that sends easy emails to a small model
A router spends one cheap call to decide how much model the rest of the task needs. Create router.py. Anything other than a clean easy, including no answer at all, goes to the large model:
cat > router.py <<'PY'
from chain import chain
from llm import BIG, SMALL, NoAnswer, text_of
from prompts import ROUTE
def route(client, meter, email):
try:
label = text_of(meter.ask(client, model=SMALL, system=ROUTE,
messages=[{"role": "user", "content": email}])).lower()
except NoAnswer:
label = "hard"
model = SMALL if label == "easy" else BIG # when unsure, use the large model
return chain(client, meter, email, model=model)
PY
uv run try_one.py router cracked | tee /tmp/refund-router-easy.txt
uv run try_one.py router phone | tee /tmp/refund-router-hard.txt
grep -c "claude-haiku-5-5" /tmp/refund-router-easy.txt | grep -qx 3
grep -q "decision: deny" /tmp/refund-router-hard.txtRouting on "how hard is this" works well when hard cases are easy to spot. If many of your customers write in Yoruba, Swahili, French or a mix of languages, collect real examples of those emails and check where the router sends them before you trust it; sending every non-English email to the large model is a reasonable first rule.
Check it worked
For cracked all three calls (route, extract, reply) name claude-haiku-5-5, and the decision is refund. For phone the first call is Haiku, the next two are claude-opus-5-5, and the decision is deny: the router sent the confusing email past the model that would have misread it.
Step 5 · Build the same task as an agent
Now hand the model the steps. Create agent.py with two tools and a loop. Two parts of it are not optional in any agent you ship:
- A turn limit.
MAX_TURNSstops a model that keeps calling tools. - A guard on the tool that acts.
record_decisionrefuses a refund the rule does not allow and returns the refusal as a tool error, so the model can try again. It letsdenyandhumanthrough, because those cannot pay out money by mistake.
tool_choice stays at its default (auto), since Opus 5.5 returns a 400 error for a forced tool choice. The model can therefore stop without recording anything, and the code treats that as human:
cat > agent.py <<'PY'
import json
from llm import BIG
from prompts import AGENT
from shop import ORDERS, Decision, policy
MAX_TURNS = 6
TOOLS = [
{
"name": "get_order",
"description": "Look up one order by its 4-digit number.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
{
"name": "record_decision",
"description": "Record the final decision for this email. Call it once.",
"input_schema": {
"type": "object",
"properties": {
"decision": {"type": "string", "enum": ["refund", "deny", "human"]},
"reason": {"type": "string"},
"reply": {"type": "string"},
},
"required": ["decision", "reason"],
},
},
]
def run_tool(name, args, state):
"""Run one tool. Returns (content, is_error)."""
if name == "get_order":
order = ORDERS.get(args.get("order_id"))
if order is None:
return f"no order {args.get('order_id')}", True
state["order_id"] = args["order_id"]
return json.dumps(order), False
if name == "record_decision":
wanted = args.get("decision")
if wanted == "refund": # the guard: only refunds can lose money
allowed = policy(state.get("order_id"))
if allowed.outcome != "refund":
return f"refused: the rule says {allowed.outcome} ({allowed.reason})", True
state["decision"] = Decision(wanted, args.get("reason", ""), args.get("reply", ""))
return "recorded", False
return f"unknown tool {name}", True
def agent(client, meter, email):
messages = [{"role": "user", "content": email}]
state = {}
for _ in range(MAX_TURNS):
message = meter.ask(client, model=BIG, system=AGENT, tools=TOOLS, messages=messages)
if message.stop_reason != "tool_use":
break
messages.append({"role": "assistant", "content": message.content})
results = []
for block in message.content:
if block.type == "tool_use":
content, is_error = run_tool(block.name, block.input, state)
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": content, "is_error": is_error})
messages.append({"role": "user", "content": results})
return state.get("decision") or Decision("human", "the agent stopped without a decision")
PY
uv run try_one.py agent pushy | tee /tmp/refund-agent.txt
grep -c "^call " /tmp/refund-agent.txt | grep -qx 4
grep -q "decision: human (the policy check refused a refund)" /tmp/refund-agent.txtEach turn sends the whole conversation so far, including the assistant's earlier content blocks, so input tokens grow with every turn.
Check it worked
You see four calls, all claude-opus-5-5: get_order, then record_decision, then record_decision again, then stop=end_turn. The first decision was refund, because the scripted model believed the "manager approved" line. The guard refused it, and the second decision is human (the policy check refused a refund). Notice what made this safe: the same policy function the chain calls. An agent that moves money needs your rule in code anyway.
Step 6 · Compare calls, tokens and results
Create compare.py to run every design on all four emails and print one row each:
cat > compare.py <<'PY'
import anthropic
from agent import agent
from chain import chain
from llm import SMALL, Meter
from router import route
from shop import EMAILS
DESIGNS = {
"chain": chain,
"chain-small": lambda c, m, e: chain(c, m, e, model=SMALL),
"router": route,
"agent": agent,
}
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL
print(f"{'design':<12}{'right':>6}{'calls':>7}{'opus':>6}{'in tok':>8}{'out tok':>9} misses")
for name, run in DESIGNS.items():
meter, right, misses = Meter(), 0, []
for key, (email, expected) in EMAILS.items():
decision = run(client, meter, email)
if decision.outcome == expected:
right += 1
else:
misses.append(f"{key}->{decision.outcome}")
calls, tokens_in, tokens_out, big = meter.totals()
print(f"{name:<12}{right:>4}/4{calls:>7}{big:>6}{tokens_in:>8}{tokens_out:>9} {' '.join(misses) or '-'}")
PY
uv run compare.py | tee /tmp/refund-compare.txt
grep -Eq "^chain +4/4 +7 +7 " /tmp/refund-compare.txt
grep -Eq "^chain-small +3/4 +6 +0 .*phone->human" /tmp/refund-compare.txt
grep -Eq "^router +4/4 +11 +2 " /tmp/refund-compare.txt
grep -Eq "^agent +4/4 +13 +13 " /tmp/refund-compare.txtThe output looks something like this (your token columns will differ a little):
design right calls opus in tok out tok misses
chain 4/4 7 7 659 259 -
chain-small 3/4 6 0 570 128 phone->human
router 4/4 11 2 998 216 -
agent 4/4 13 13 4869 564 -How to read it, design by design:
- chain: 7 calls, all on the large model. Predictable: the number of calls depends only on which branch the rule takes.
- chain-small: cheapest, and its one miss is a safe one. The
phoneemail went to a person instead of getting a wrong answer. - router: more calls than the chain, but 9 of the 11 are on the small model, which is priced well below Opus per token. Whether it saves money depends on your mix of easy and hard emails. Work it out from the pricing page with your own numbers.
- agent: the same right answers for nearly twice the calls of the chain, all on the large model, and about seven times the input tokens, because every turn re-sends the conversation. It also needed the same rule in code to stay safe.
Against the real API, the numbers change: real models think, so output tokens are higher, and they do not make the stub's scripted mistakes. To run this comparison for real, put your key in a private env file and run the same script without the stub. Each run makes about 37 paid calls:
uv run --env-file ~/.config/llm-demo/env compare.pyRun it on a set of your own emails, not these four, before you draw conclusions; a golden set is the right tool for that.
Check it worked
You see four rows. chain, router and agent show 4/4, chain-small shows 3/4 with phone->human as its only miss, and the call counts are 7, 6, 11 and 13.
Step 7 · Compare how easy each design is to test
Testing is often what decides it. Create test_designs.py. The first block starts the stub on a free port for each test, so these tests do not need the second terminal:
cat > test_designs.py <<'PY'
import threading
import anthropic
import pytest
from agent import agent, run_tool
from chain import chain
from llm import BIG, SMALL, Meter
from router import route
from shop import EMAILS
from stub_server import make_server
@pytest.fixture
def client():
server = make_server(0) # port 0: any free port
threading.Thread(target=server.serve_forever, daemon=True).start()
host, port = server.server_address[:2]
yield anthropic.Anthropic(api_key="stub-key", base_url=f"http://{host}:{port}", max_retries=0)
server.shutdown()
server.server_close()
# Workflow: each step has a known input and output, so each can be tested on its own.
@pytest.mark.parametrize("name", EMAILS)
def test_chain_gets_every_email_right(client, name):
email, expected = EMAILS[name]
assert chain(client, Meter(), email).outcome == expected
def test_check_catches_a_misread_order_number(client):
meter = Meter()
decision = chain(client, meter, EMAILS["phone"][0], model=SMALL)
assert decision.outcome == "human"
assert len(meter.calls) == 1 # stopped before writing a reply
def test_router_sends_the_confusing_email_to_the_large_model(client):
meter = Meter()
route(client, meter, EMAILS["phone"][0])
assert [c["model"] for c in meter.calls] == [SMALL, BIG, BIG]
# Agent: the guard is plain code and easy to test. The path the model takes is not.
def test_guard_refuses_a_refund_over_the_limit():
content, is_error = run_tool("record_decision", {"decision": "refund", "reason": "x"},
{"order_id": "1077"})
assert is_error and "human" in content
def test_agent_ends_with_a_person_for_the_pushy_email(client):
meter = Meter()
assert agent(client, meter, EMAILS["pushy"][0]).outcome == "human"
assert len(meter.calls) <= 6
PY
uv run pytest -qLook at what each test can pin down. The chain tests check exact calls, in order, because the order is in your code. The agent test can only check the final decision and an upper bound on calls: with a real model, the path (which tool, how many retries) changes from run to run, so you test agents mostly by running many examples and scoring the outcomes, which costs more and takes longer.
Check it worked
pytest prints 11 passed: 3 policy tests, 4 chain runs, 1 check, 1 router and 2 agent tests. To see the guard earn its place, open agent.py, delete the four lines from if wanted == "refund": down to the return f"refused: ... line, and run uv run pytest -q again. Two tests fail: the guard test, and the pushy email, which the agent now refunds in full. Put the lines back.
Step 8 · Choose the shape for your own feature
You have now seen the trade-offs on one task. Use these questions on the feature you are actually building, in this order:
- Complexity. Can you write the steps down before you see the input? If yes, build a workflow. Reach for an agent only when the number or order of steps depends on what the model finds along the way, such as searching several systems until an answer turns up.
- Value per task. What is one correct result worth, compared with what it costs? A refund email is worth a few calls. An agent that uses 13 calls where a chain uses 7 needs a reason.
- Cost of an error. What happens when the output is wrong, and who notices? Where money moves or a customer is told something binding, keep the decision in code and send doubtful cases to a person.
- Whether errors can be caught. Can your code check the model's output before it is used (an ID that must exist, a reply that must name the order)? Catchable errors make a small model or a router safe. Errors you cannot catch need the larger model and a human sampling the outputs.
- Testability. Can you test it with fixed examples and exact assertions? Workflows can be. Agents need a scored set of examples, run often.
Write your answers down where your team will see them. Here is the file for this tutorial's feature; copy its headings for yours:
cat > CHOICE.md <<'MD'
# Refund emails: workflow or agent?
- Complexity: fixed steps (read, look up, apply rule, reply). Workflow.
- Value per task: low. Keep calls per email small.
- Cost of an error: a wrong refund loses money. Rule stays in code; doubtful cases go to a person.
- Errors can be caught: yes, the order ID must exist and the reply must name it. Router is safe.
- Testability: exact tests for every step.
Choice: router in front of the prompt chain. Revisit if emails start needing several systems.
MD
grep -c "^- " CHOICE.mdWhatever you choose, a person still reviews a sample of real decisions each week. A check in code catches the mistakes you thought of; only people reading real output find the ones you did not.
When you have finished, stop the stub with Ctrl+C in the second terminal and remove the project:
cd ~
rm -rf ~/refund-demoCheck it worked
Before you delete the folder, grep prints 5: one line per question, each with an answer. Your own CHOICE.md should name a design and the condition that would make you revisit it. If you cannot answer the "errors can be caught" line, that is the next thing to work out, before any code.
Next steps
- Build a fuller agent with a token budget, a step log and a clean stop when a tool keeps failing: build a small AI agent loop from scratch.
- Step back a level and ask whether the feature needs a model at all: decide whether a feature needs AI at all.
- Learn the tool-use loop in more detail, including several tool calls in one reply: let Claude call your functions with tool use.
- Turn the stub into a full offline test suite with fixtures and error cases: test Claude API code offline against a stub server.
Related tutorials
- Use MCP server tools from your own Claude appYou will connect a Python app to the stdio clinic-hours MCP server, hand an allowlisted set of its tools to Claude, pass every tool call through to the server with a tested bridge, and know when the API's MCP connector can do the connecting for you.
- Trace LLM calls with OpenTelemetryYou will have a Python app whose Claude calls, retries and tool runs appear as one OpenTelemetry trace with GenAI attributes, token and latency metrics, prompts kept out by default, and an export path from the console to an OpenTelemetry Collector.
- Serve an MCP server over Streamable HTTP with authenticationYou will run an MCP server over Streamable HTTP on localhost that checks the Origin header, accepts only bearer tokens your token verifier knows, limits each tool to the right scope, and refuses calls without a token.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials