Chapter 2 · Chains and Structured Output
Prompt Chaining: Stages, Fixed Schemas and the promptlab Helper
- Page 5 of 24
- 19 min read
One big prompt that reads a messy customer message, decides what to do and writes the reply is hard to debug. When the reply is wrong, you cannot tell whether the model misread the message, applied the wrong rule or wrote badly. A prompt chain splits the job into small stages. Each stage has a clear input and a clear output, and ordinary Python code sits between the stages to check the result and decide what happens next.
This page builds a three-stage chain for support tickets (extract, validate, draft). On the way it introduces promptlab.py, the small helper that every later code page uses to call a "model", record what happened and keep tests repeatable.
What you will learn
- How to design a chain with explicit inputs and outputs, and why extraction, interpretation, classification, explanation and drafting belong in different stages.
- How the shared
promptlabhelper works, and what a toy provider is and is not. - How to pass only validated results between stages, using a fixed schema checked in plain Python.
- How to branch and stop in code instead of in the prompt, and how to define failure handling for each stage.
- How to avoid sending large context to every stage.
Why a chain, and what a stage is
A stage is one prompt (or one piece of code) with a declared input, a declared output and one job. Our chain turns a raw ticket into a reply draft:
ticket text
| stage 1: extract (model) -> JSON record: order_id, issue, action, email
| stage 2: validate (Python) -> accepted record, or a stop with a reason
| branch: missing info? unusual issue? (Python) -> stop or hand to a person
| stage 3: draft (model) -> reply text for a person to review
reply draft (never sent automatically)| Stage | Input | Output | Done by | If it fails |
|---|---|---|---|---|
| Extract | Ticket text | Record with four fixed keys | Model | Retry only transport errors, then stop |
| Validate | Raw extract reply | Checked record, or a list of problems | Python | Stop; the problems name the field |
| Branch | Checked record | Continue, ask the customer, or hand over | Python | Always ends in a named status |
| Draft | Only the facts the reply may use | Reply text | Model | Stop; nothing is sent |
Writing this table before any prompt is the most useful habit in this page. If you cannot fill the "Input" and "Output" cells, the stage is not yet well defined.
The promptlab helper
Every code page of this tutorial imports one small file, promptlab.py. It is shown here in full, once. It uses only the Python standard library, so there is nothing to install. Copy it into a file named promptlab.py in your working folder.
"""promptlab: a tiny, stdlib-only helper for prompt experiments (Python 3.12).
A Client wraps any provider function, records a Response for every call and can
append one JSON line per attempt to a log file. Tutorials use toy providers, so
all numbers here are repeatable stand-ins, never measurements of a real model.
"""
from __future__ import annotations
import json
import string
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Callable, Mapping, Sequence
Message = Mapping[str, str]
Provider = Callable[..., "str | dict[str, Any]"]
@dataclass(frozen=True)
class Usage:
"""Token counts for one call; cached_input_tokens is the part of the input served from a cache."""
input_tokens: int
output_tokens: int
cached_input_tokens: int = 0
@dataclass
class Response:
"""What complete() returns: the text, its Usage, a latency in milliseconds and extra metadata."""
text: str
usage: Usage
latency_ms: int
meta: dict[str, Any] = field(default_factory=dict)
class ProviderError(RuntimeError):
"""Raised by Client.complete() after the failure was logged and all retries were used."""
def estimate_tokens(text: str) -> int:
"""Roughly estimate tokens as one per four characters (at least 1). A rule of thumb, not a tokenizer."""
return max(1, round(len(text) / 4))
class Client:
"""Call a provider(messages, **settings) function and keep a record of every attempt.
The provider returns a str or a dict with the key "text" and optionally "cached_input_tokens".
Latency is a deterministic fake derived from a call counter unless real_timing=True.
"""
def __init__(self, provider: Provider, model: str = "toy", log_path: str | Path | None = None,
retries: int = 0, real_timing: bool = False) -> None:
self.provider, self.model, self.retries, self.real_timing = provider, model, retries, real_timing
self.log_path = Path(log_path) if log_path else None
self.calls = 0 # attempts made so far; drives the fake latency and numbers the log lines
def _log(self, record: dict[str, Any]) -> None:
if self.log_path is None:
return
self.log_path.parent.mkdir(parents=True, exist_ok=True)
with self.log_path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, sort_keys=True, ensure_ascii=False) + "\n")
def complete(self, messages: Sequence[Message], **settings: Any) -> Response:
"""Send messages to the provider; retry on any exception; log every attempt, failures included."""
if not messages or any("role" not in m or "content" not in m for m in messages):
raise ValueError("messages must be a non-empty list of {'role': ..., 'content': ...} items")
prompt = [dict(m) for m in messages]
for attempt in range(1, self.retries + 2):
self.calls += 1
base = {"attempt": attempt, "call": self.calls, "messages": prompt, "model": self.model, "settings": settings}
started = time.perf_counter()
try:
raw = self.provider(prompt, **settings)
data = {"text": raw} if isinstance(raw, str) else dict(raw)
text = str(data["text"]) # a reply without "text" counts as a provider failure
except Exception as exc: # the provider may fail in any way; record it, then retry or give up
self._log({**base, "error": f"{type(exc).__name__}: {exc}", "status": "error"})
if attempt > self.retries:
raise ProviderError(f"{type(exc).__name__}: {exc} (after {attempt} attempt(s))") from exc
continue
tokens_in = sum(estimate_tokens(m["content"]) for m in prompt)
cached = min(int(data.get("cached_input_tokens", 0)), tokens_in)
usage = Usage(tokens_in, estimate_tokens(text), cached)
if self.real_timing:
latency = round((time.perf_counter() - started) * 1000)
else:
latency = 40 + 5 * usage.output_tokens + 10 * (self.calls % 3)
response = Response(text, usage, latency, {"attempt": attempt, "call": self.calls, "model": self.model})
self._log({**base, "latency_ms": latency, "meta": response.meta, "status": "ok", "text": text,
"usage": asdict(usage)})
return response
raise AssertionError("unreachable") # pragma: no cover
def render(template: str, **variables: Any) -> str:
"""Fill {name} fields in template; raise ValueError if a variable is missing or not used. To print a literal brace, write it twice."""
names = {name for _, name, _, _ in string.Formatter().parse(template) if name}
if names - variables.keys():
raise ValueError(f"missing variables: {sorted(names - variables.keys())}")
if variables.keys() - names:
raise ValueError(f"unused variables: {sorted(variables.keys() - names)}")
return template.format(**variables)Its parts, briefly:
- provider: any function
provider(messages, **settings)that returns text (or a dict with a"text"key). A real provider would wrap your SDK call;Clientdoes not care which. This is the only place a model is involved. Client.complete(messages): calls the provider and returns aResponsewithtext,usage,latency_msandmeta. It rejects malformed messages before calling anything.retries: on any exception the client tries again. When all attempts fail it raisesProviderError. Every attempt, including failures, is logged.log_path: appends one JSON line per attempt (messages, settings, status, text, usage), the raw material for debugging a chain later.estimate_tokens: a rough rule, one token per four characters. It is not a tokenizer; use it to compare sizes, not to predict a bill. Latency is a deterministic fake unless you passreal_timing=True.render(template, **variables): fills{name}fields and raises an error if a variable is missing or unused, so a typo cannot silently produce a broken prompt.
Toy providers: stand-ins, not models
The providers in this tutorial are toy providers: small deterministic functions written on the page that imitate one behaviour. They are a stand-in, so that your chain, your checks and your tests can be run repeatedly with identical results. Real models are less predictable, and that is exactly why you test. A result from a toy provider tells you that your code handles a case; it says nothing about how well a real model would do.
from promptlab import Client, ProviderError, estimate_tokens, render
def toy_echo(messages, **settings):
"""Stand-in provider: repeats the last message in capitals."""
return messages[-1]["content"].upper()
client = Client(toy_echo, model="toy-echo", log_path="logs/demo.jsonl")
reply = client.complete([{"role": "user", "content": render("Say hi to {name}.", name="Aiko")}])
print(reply.text)
print(reply.usage)
print(reply.latency_ms, reply.meta)
print(open("logs/demo.jsonl", encoding="utf-8").read().count("\n"), "log line")SAY HI TO AIKO.
Usage(input_tokens=4, output_tokens=4, cached_input_tokens=0)
70 {'attempt': 1, 'call': 1, 'model': 'toy-echo'}
1 log lineThe latency is the fake, repeatable number. The log has one line per attempt, so a chain of five calls leaves five lines you can read.
Stage 1: extraction, kept apart from interpretation
The extract prompt asks only for what the ticket states, and tells the model to use null for anything missing. It does not ask "what should we do?". Keeping extraction separate from interpretation means a wrong field can be traced to one small prompt, and the policy for what to do about it stays in code you can read.
The same split applies elsewhere in the chain:
| Separate this | from this | Why |
|---|---|---|
| Extraction (what does the text say?) | Interpretation (what should we do?) | Facts can be checked against the text; decisions are policy. |
| Classification (which of four issue types?) | Explanation (why, in words for the customer) | A label can be tested against known answers; prose cannot. |
| Drafting (first version) | Revision (improve against a rubric) | A revision needs something fixed to be judged against. The next page, Chain Reliability: Error Rates, Early Failures, Revision Loops and Fallbacks, adds that stage. |
In our chain the label issue is classified in stage 1 from a fixed list, and stage 3 only explains it. Stage 3 drafts once; a revision stage is deliberately left out until you can measure whether it helps.
Here are the two prompts and the two toy providers. The extractor finds fields with simple rules; the drafter fills one sentence from the facts it is given.
import json, re
EXTRACT = """Read the support ticket. Reply with JSON only, with the keys order_id, issue, action, email.
issue is one of: damaged, late, wrong_item, other. action is one of: refund, replace, none.
Use null for anything the ticket does not state. Do not guess.
### TICKET
{ticket}"""
DRAFT = """Write a polite reply of at most 60 words to a customer.
You may use only these facts:
order: {order_id}
problem: {issue}
our next step: {step}
Do not promise anything that is not listed."""
def toy_extract(messages, **settings):
"""Stand-in: finds fields with simple rules and answers in JSON. A real model reads more loosely."""
text = messages[-1]["content"].split("### TICKET", 1)[1].lower()
order = re.search(r"order\s*#?\s*(\d{4,})", text)
mail = re.search(r"[\w.]+@[\w.]+\w", text)
issue = next((k for w, k in [("cracked", "damaged"), ("late", "late"), ("wrong", "wrong_item")] if w in text), "other")
action = next((k for w, k in [("refund", "refund"), ("replace", "replace")] if w in text), "none")
return json.dumps({"order_id": order and order.group(1), "issue": issue, "action": action,
"email": mail and mail.group(0)})
def toy_draft(messages, **settings):
"""Stand-in: fills a sentence from the facts it is given."""
facts = dict(line.split(": ", 1) for line in messages[-1]["content"].splitlines() if ": " in line)
return f"Hello, thank you for writing about order {facts['order']}. We are sorry about the {facts['problem']} problem. Our next step: {facts['our next step']}."Stage 2: a fixed schema and validated results
Stage 1 must return the same four keys every time. That fixed schema is the contract between stages: stage 3 never sees a raw model reply, only a record that passed the checks. Writing the schema in code, not only in the prompt, is what makes the contract real.
Remember that asking for JSON is not the same as guaranteeing it. Some providers offer schema-constrained output, which guarantees the format but not that the values are correct, and it can still fail on a refusal or a cut-off reply. Whichever you use, check three things yourself: the syntax (is it JSON?), the schema (keys, types, allowed values) and the business rules (here: an order number and an email address are required). JSON and Schemas: Fields, Types, Enums and Missing Values and the page after it go deeper; here a plain-Python check keeps the idea visible.
SCHEMA = { # the fixed contract between stage 1 and the rest of the chain
"order_id": (str, None),
"issue": (str, {"damaged", "late", "wrong_item", "other"}),
"action": (str, {"refund", "replace", "none"}),
"email": (str, None),
}
REQUIRED = ["order_id", "email"]
STEP = {"refund": "we will start your refund", "replace": "we will send a replacement",
"none": "a colleague will review your case"}
def check_record(text):
"""Stage 2 (plain Python): return (record, problems). No model is involved."""
try:
record = json.loads(text)
except json.JSONDecodeError as exc:
return None, [f"not valid JSON ({exc.msg})"]
if not isinstance(record, dict) or set(record) != set(SCHEMA):
return None, [f"keys must be exactly {sorted(SCHEMA)}"]
problems = []
for key, (kind, allowed) in SCHEMA.items():
value = record[key]
if value is not None and not isinstance(value, kind):
problems.append(f"{key}: expected {kind.__name__}")
elif allowed and value not in allowed:
problems.append(f"{key}: {value!r} is not one of {sorted(allowed)}")
return record, problems
def run_chain(ticket, extractor, writer):
"""Three stages: extract (model) -> validate and branch (Python) -> draft (model)."""
try:
raw = extractor.complete([{"role": "user", "content": render(EXTRACT, ticket=ticket)}]).text
except ProviderError as exc:
return {"status": "failed", "stage": "extract", "why": str(exc)}
record, problems = check_record(raw)
if problems:
return {"status": "failed", "stage": "validate", "why": "; ".join(problems)}
missing = [key for key in REQUIRED if record[key] is None]
if missing: # stop: do not let a model invent the gap
return {"status": "needs_info", "ask_customer_for": missing}
if record["issue"] == "other": # branch: this case is not ours to automate
return {"status": "human", "record": record}
prompt = render(DRAFT, order_id=record["order_id"], issue=record["issue"].replace("_", " "),
step=STEP[record["action"]])
try:
reply = writer.complete([{"role": "user", "content": prompt}]).text
except ProviderError as exc:
return {"status": "failed", "stage": "draft", "why": str(exc)}
return {"status": "drafted", "to": record["email"], "reply": reply}Read run_chain as the chain's table of contents. Every return ends the chain with a status you can count, log and test: failed, needs_info, human or drafted.
Branches and stopping rules live in Python
Two decisions in run_chain are made outside the prompt. If order_id or email is missing, the chain stops and reports what to ask the customer; it does not let a model "fill in" a plausible order number. If the issue is other, the ticket goes to a person. Code makes these decisions better than a prompt does: they are free (no model call), they behave the same on every run, a unit test can cover them, and a clever ticket cannot talk its way past them.
Run the chain on three invented tickets. Notice that ticket B never reaches stage 3.
from pprint import pprint
TICKETS = {
"A": "Hello, order 48213 arrived with a cracked screen. Please send a refund. Kwame, [email protected]",
"B": "My parcel never came and nobody answers. Please help. Lena, [email protected]",
"C": "Order #51877 is fine, but how do I change the language of the app? Mateo, [email protected]",
}
extractor, writer = Client(toy_extract), Client(toy_draft, log_path="logs/chain.jsonl")
for name, ticket in TICKETS.items():
print(name)
pprint(run_chain(ticket, extractor, writer), width=76)A
{'reply': 'Hello, thank you for writing about order 48213. We are sorry '
'about the damaged problem. Our next step: we will start your '
'refund.',
'status': 'drafted',
'to': '[email protected]'}
B
{'ask_customer_for': ['order_id'], 'status': 'needs_info'}
C
{'record': {'action': 'none',
'email': '[email protected]',
'issue': 'other',
'order_id': '51877'},
'status': 'human'}Ticket A produces a draft for a person to review. Ticket B stops with needs_info: the ticket has no order number, so the right next step is a question to the customer. Ticket C has a number, but its problem is not one the chain handles, so it is handed over with the extracted record attached.
Failure handling for each stage
Decide, per stage, what a failure means before it happens. The chain above separates three kinds:
- The call failed (timeout, network): a retry is reasonable, because the same input may succeed.
Client(retries=1)does this, and the log keeps both attempts. - The call worked but the content is unusable (not JSON, wrong key, value outside the list): do not retry blindly. Stop with the stage name and the exact problem. Validation and Repair: jsonschema, Business Rules and Bounded Retries shows careful repair.
- The content is valid but incomplete (a required field is null): a normal outcome, not an error. Report
needs_info.
The toy providers below each break one rule, so you can see the three paths without a real model.
def chatty(messages, **settings): # breaks the contract: prose around the JSON
return "Sure! Here is the data: " + toy_extract(messages)
calls = {"n": 0}
def flaky(messages, **settings): # fails once, then works
calls["n"] += 1
if calls["n"] == 1:
raise TimeoutError("provider timed out")
return toy_extract(messages)
def always_down(messages, **settings):
raise ConnectionError("provider unreachable")
writer = Client(toy_draft)
for label, provider, retries in [("chatty", chatty, 0), ("flaky, 1 retry", flaky, 1), ("down, 1 retry", always_down, 1)]:
result = run_chain(TICKETS["A"], Client(provider, retries=retries), writer)
print(f"{label}: {result['status']} {result.get('stage', '')} {result.get('why', '')[:70]}".rstrip())chatty: failed validate not valid JSON (Expecting value)
flaky, 1 retry: drafted
down, 1 retry: failed extract ConnectionError: provider unreachable (after 2 attempt(s))The chatty provider wrapped the JSON in a friendly sentence, a typical real-model habit; the chain stopped at validate instead of passing on garbage. The flaky provider recovered on its retry. The unreachable one stopped at extract, with both attempts counted in the message.
Do not repeat large context
A support ticket often arrives with a long thread of earlier messages. Only stage 1 needs to read it. After extraction, later stages need a few validated facts, so pass the facts and not the thread. This keeps later prompts short, cheaper and easier to read, and it gives the drafting model less irrelevant text that could distract it. If a stage does need a large unchanged block, put it first and keep it identical between calls; providers that cache prompts reuse an identical beginning, which Prompt Caching and Cost: Stable Prefixes, Usage Data and Estimates covers.
history = "\n".join(f"> message {i}: thanks, still waiting for an update" for i in range(60))
long_ticket = TICKETS["A"] + "\n" + history
extract_prompt = render(EXTRACT, ticket=long_ticket)
draft_prompt = render(DRAFT, order_id="48213", issue="damaged", step=STEP["refund"])
print("extract stage reads :", estimate_tokens(extract_prompt), "tokens (rough)")
print("draft, facts only :", estimate_tokens(draft_prompt), "tokens (rough)")
print("draft, ticket again :", estimate_tokens(draft_prompt + long_ticket), "tokens (rough)")extract stage reads : 836 tokens (rough)
draft, facts only : 50 tokens (rough)
draft, ticket again : 822 tokens (rough)These numbers use the rough four-characters rule, so treat them as a comparison, not a measurement. The facts-only draft prompt is a small fraction of the size of a draft prompt that repeats the thread.
Where this shows up at work
Support teams chain "read, check, draft" before a person replies. Finance teams chain "extract fields from an invoice, check totals in code, write a summary". Data teams chain "classify a record, then explain the label". In every one of them, the useful property is the same: when a result is wrong, the log tells you which stage produced it, and a test can pin that stage down.
Common mistakes
- Passing a raw model reply to the next stage. One bad reply then corrupts everything after it. Validate between stages and pass only the checked record.
- Letting the prompt decide the branch. "If the order number is missing, make one up" or "…skip this step" cannot be tested and can be argued with. Put branches in code.
- Retrying every failure. A retry helps a timeout; it does not fix a misunderstanding. Retrying invalid content can hide a real defect and double the cost.
- Re-sending the whole context to every stage. It costs more and adds noise. Pass the validated facts.
- Trusting a toy provider's result. It shows that your code handles a case. Real models need their own tests, which later pages build.
Try it yourself
Use the page's code: run each block in order in one Python folder with promptlab.py beside it.
- Easy. Add ticket D,
"Order 60412 arrived late. Please replace it. Priya", and predict the status before you run it. - Medium. Add a branch rule: a late order with a refund request goes to a person, because refunds for late orders need approval. Write it as a function and test it on two records.
- Hard. Write a toy extractor that returns a value outside the allowed list for
issue, and show that the chain stops atvalidateand names the field. Then say which earlier idea from the Beginner tutorial (answering "null when missing", not guessing) this protects.
Answers
Easy. The ticket has an order number but no email address, and email is required, so the status is needs_info and the customer is asked for the email.
ticket_d = "Order 60412 arrived late. Please replace it. Priya"
print(run_chain(ticket_d, Client(toy_extract), Client(toy_draft))){'status': 'needs_info', 'ask_customer_for': ['email']}Medium. A strong answer is a small, pure function that takes the checked record and returns true or false; you place it in run_chain next to the other rule (if needs_human(record): return {"status": "human", ...}).
def needs_human(record):
return record["issue"] == "other" or (record["issue"] == "late" and record["action"] == "refund")
late_refund = {"issue": "late", "action": "refund"}
late_replace = {"issue": "late", "action": "replace"}
print(needs_human(late_refund), needs_human(late_replace))True FalsePass checklist: it is plain Python with no model call; it is tested on both a case that triggers it and one that does not; it runs after validation, so it can trust the field values.
Hard.
def wrong_enum(messages, **settings):
return json.dumps({"order_id": "1", "issue": "broken", "action": "refund", "email": "[email protected]"})
result = run_chain(TICKETS["A"], Client(wrong_enum), Client(toy_draft))
assert result["stage"] == "validate"
print(result["why"])issue: 'broken' is not one of ['damaged', 'late', 'other', 'wrong_item']Pass checklist: the failure status names the stage (validate) and the field (issue); the draft stage is never called; no retry is attempted. This is the same rule as in the Beginner tutorial: an extractor should return null or a stated value, never a guess, and your code is what checks that it did.
Summary
- A chain is small stages with declared inputs and outputs. Write the input/output table before the prompts.
- Keep extraction, interpretation, classification, explanation, drafting and revision apart, so each can be tested alone.
- Use a fixed schema and check syntax, schema and business rules in code before the next stage sees the result.
- Make branches and stopping rules in Python: stop when required information is missing, and name the reason.
- Define failure handling per stage; retry transport errors, stop on unusable content.
- Pass validated facts, not the whole context, to later stages. Toy providers make the code testable; they say nothing about real models.
Next: Chain Reliability: Error Rates, Early Failures, Revision Loops and Fallbacks, where you measure how often a whole chain succeeds and stop early errors from spreading.

