Sub topic 8
Ask for structured output
This chapter assumes you can write prompts for a chat model, know the channels you publish to, and can read basic Python. It builds on the prompt from the previous chapter, which combines the core message, brand voice, and a format spec.
Why free text is hard to use downstream
A model that replies in free text gives you a block of prose. A person can read it. A script cannot reliably tell where the subject line ends and the body begins, or which line is the call to action.
Structured output is a reply in a fixed, machine-readable shape, usually JSON. Asking for it lets your pipeline pull out fields, run checks on each one, and send them to the right place, such as an email tool or a review queue.
Define the fields from the format spec
Your format spec already names the parts of each format. Turn those parts into field names. For the email newsletter spec ("Subject line, two-sentence intro, three bullets, one call to action"), the fields are:
subject: a stringintro: a stringbullets: a list of three stringscta: a stringclaims_used: a list of the source sentences the draft relies on
The last field supports the fact checks in later chapters. It asks the model to show its evidence.
Add the schema to the prompt
State the shape in the prompt, give one small example, and say that nothing else may appear in the reply.
import json
EMAIL_SCHEMA = {
"subject": "string",
"intro": "string, two sentences",
"bullets": ["string", "string", "string"],
"cta": "string",
"claims_used": ["quoted source sentence"],
}
def add_output_instructions(prompt: str, schema: dict) -> str:
return (
prompt
+ "\n\nReply with one JSON object and nothing else. "
"No Markdown fences, no commentary. Use exactly these keys:\n"
+ json.dumps(schema, indent=2)
)Many providers also offer a JSON mode or a way to pass a schema as a parameter. Use it when available, because it constrains the output more strongly than instructions do. Keep the prompt instructions as well. They tell the model what each field means.
Parse and validate every reply
Never assume the reply is valid. Parse it, then check the keys and sizes.
import json
REQUIRED = {"subject", "intro", "bullets", "cta", "claims_used"}
def parse_email_draft(raw: str) -> dict:
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(f"Reply is not valid JSON: {exc}") from exc
if not isinstance(data, dict):
raise ValueError("Reply must be a JSON object")
missing = REQUIRED - data.keys()
if missing:
raise ValueError(f"Missing keys: {sorted(missing)}")
if not isinstance(data["bullets"], list) or len(data["bullets"]) != 3:
raise ValueError("Expected exactly three bullets")
return dataWhen parsing fails, retry once with the error message appended to the prompt. If the second attempt also fails, send the item to a human instead of looping.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Reply wrapped in a Markdown fence | The model formats it like a chat answer | Say "no Markdown fences", or strip fences before parsing |
| Extra text before the JSON | No instruction to omit commentary | Say "nothing else", or use the provider's JSON mode |
| Wrong number of bullets | The schema shows types but not counts | State the count in the field description and check it in code |
| Invented `claims_used` entries | The model writes plausible but absent quotes | Check that each quote appears in the source text |
A valid structure does not mean valid content. The model can return perfectly formed JSON containing an invented statistic. Structure makes checking easier, but it does not replace the fact checks or human review.
Exercise
A model returns {"subject": "Q3 results", "intro": "...", "bullets": ["a", "b"], "cta": "Register now", "claimsused": []}. Which check in parseemail_draft rejects it, and what should the pipeline do next?
Show answer
The bullet-count check rejects it, because the reply has two bullets instead of three. The pipeline should retry once with the error message added to the prompt. If the retry also fails, it should send the item to a human reviewer.
Exercise
Write a check that confirms every entry in claims_used appears word for word in the source text. Why is this useful?
Show answer
Example: def quotes_in_source(source, claims): return [c for c in claims if c not in source]. It returns the quotes that are not in the source. Any returned entry is a likely invented claim, so the draft needs closer review.