Sub topic 8
Ask for Structured Output
This chapter assumes you can write a repurposing prompt (core message, brand voice, format spec) and read basic Python. By the end, you will be able to make the model return drafts as data that code can read, check, and route, and you will know how to handle replies that are not valid.
Why free text is not enough
So far the model has returned prose: a LinkedIn post, a newsletter, a script. A person can read that. A program cannot reliably tell where the subject line ends and the body begins, or which sentence made which claim.
This matters once you have more than a handful of drafts. Downstream steps need to find specific parts of each draft:
- A content management system needs a title field and a body field.
- A scheduling tool needs the post text without any "Here is your draft:" lead-in.
- The fact check in the next chapter needs a list of claims, each tied to the passage in the source that supports it.
- A reviewer's queue needs word counts and flags next to each draft.
Structured output means asking the model to reply in a fixed, machine-readable shape. JSON is the usual choice because every mainstream language can parse it.
Design the shape before the prompt
Start with what downstream steps need, then work backwards to the fields. For the formats in this tutorial, one shape covers all of them:
| Field | Type | Purpose |
|---|---|---|
| `headline` | string | Subject line, hook line, or title, depending on the format |
| `body` | string | The main text, in the structure the format spec asks for |
| `call_to_action` | string | The closing ask, kept separate so you can swap links or wording later |
| `claims` | list of objects | Every factual statement in the draft, each with `text` and `source_quote` |
Three design rules keep this shape useful.
- Use one schema for all formats. A video script's "hook" goes in
headline, and a newsletter's subject line also goes inheadline. Your pipeline then needs one parser, not one per channel. - Do not ask the model for values you can compute. Word count is the standard example. Models miscount words, so count
body.split()in your own code. Ask the model only for what requires judgment. - Ask for evidence, not just claims. The
source_quotefield forces the model to point at the source for each claim. Your code can then check that the quote exists. This turns the instruction "use only facts from the source" into something you can test.
Add the schema to the prompt
Append a short block to the prompt from the previous chapter. Describe the shape in words and show an example with placeholder values.
JSON_INSTRUCTIONS = """
Reply with a single JSON object and nothing else. No text before or after it.
Use exactly these keys:
{
"headline": "string",
"body": "string",
"call_to_action": "string",
"claims": [
{"text": "a factual statement made in the draft",
"source_quote": "the exact words from the source that support it"}
]
}
List every number, percentage, name, and result that appears in the draft as a claim.
Copy each source_quote word for word from the source.
"""Two details matter here. "Nothing else" suppresses chatty lead-ins, though it does not eliminate them. "Word for word" makes the quote checkable by plain string matching.
Parse and validate the reply
Never pass a model reply straight to json.loads and trust the result. Replies fail in two different ways:
- Syntax failures. The reply is not valid JSON. Typical causes are a lead-in sentence, a closing remark, a code fence around the JSON, a trailing comma, or an unescaped line break inside a string.
- Shape failures. The reply is valid JSON but does not match your schema. A key is missing,
claimsis a string instead of a list, or a claim has nosource_quote.
A third failure is subtler: the reply is valid and well shaped, but a source_quote does not appear in the source. Your validator can catch it too.
The code below handles all three. It is self-contained, and you can run it as is.
import json
REQUIRED = {
"headline": str,
"body": str,
"call_to_action": str,
"claims": list,
}
class OutputError(ValueError):
"""Raised when a model reply cannot be used."""
def extract_json(raw: str) -> dict:
start, end = raw.find("{"), raw.rfind("}")
if start == -1 or end <= start:
raise OutputError("No JSON object found in the reply.")
try:
data = json.loads(raw[start:end + 1])
except json.JSONDecodeError as exc:
raise OutputError(f"Invalid JSON: {exc}") from exc
if not isinstance(data, dict):
raise OutputError("The top-level JSON value must be an object.")
return data
def normalize(text: str) -> str:
return " ".join(text.lower().split())
def validate_draft(data: dict, source: str) -> dict:
for field, kind in REQUIRED.items():
if field not in data:
raise OutputError(f"Missing field: {field}")
if not isinstance(data[field], kind):
raise OutputError(f"Field '{field}' must be of type {kind.__name__}")
if not data["claims"]:
raise OutputError("The claims list must not be empty.")
haystack = normalize(source)
for i, claim in enumerate(data["claims"]):
if not isinstance(claim, dict) or "text" not in claim or "source_quote" not in claim:
raise OutputError(f"Claim {i} needs 'text' and 'source_quote'.")
if normalize(str(claim["source_quote"])) not in haystack:
raise OutputError(
f"Claim {i} quotes words that are not in the source: {claim['source_quote']!r}"
)
data["word_count"] = len(data["body"].split())
return dataextract_json takes everything from the first { to the last }. This tolerates a lead-in sentence or a code fence around the object without any special handling. normalize lowercases the text and collapses whitespace, so a quote that differs from the source only by a line break still matches.
Retry with the error message
When validation fails, the most effective repair is to send the original prompt again together with the exact error. The model can then fix the specific problem. Limit the number of attempts, because a reply that fails three times usually needs a person, not a fourth try.
def request_structured(prompt: str, source: str, call_model, max_attempts: int = 3) -> dict:
current = prompt
last_error = "unknown error"
for _ in range(max_attempts):
raw = call_model(current)
try:
return validate_draft(extract_json(raw), source)
except OutputError as exc:
last_error = str(exc)
current = (
prompt
+ f"\n\nYour previous reply was rejected: {last_error}\n"
+ "Return only the corrected JSON object."
)
raise OutputError(f"Gave up after {max_attempts} attempts: {last_error}")
if __name__ == "__main__":
source = "Attendees of the 2025 webinar cut onboarding time by 30%."
replies = iter([
"Sure! Here is your post.",
'{"headline": "Faster onboarding", '
'"body": "Attendees cut onboarding time by 30%.", '
'"call_to_action": "Watch the recording.", '
'"claims": [{"text": "Onboarding time fell by 30%", '
'"source_quote": "cut onboarding time by 30%"}]}',
])
result = request_structured("(prompt)", source, lambda prompt: next(replies))
print(result["headline"], result["word_count"])The fake model here fails once, then succeeds, so you can watch the retry path work before you connect a real provider. Replace the lambda with your own call_model.
Where the retry loop sits
Provider features and their limits
Many model providers offer a JSON mode or a way to supply a schema that the output must follow. If yours does, use it, because it greatly reduces syntax failures. Check your provider's documentation for the exact options, since names and guarantees differ.
Keep two limits in mind:
- A schema constraint guarantees shape, not truth. A reply can be perfectly formed and still contain an invented statistic. The
source_quotecheck is what catches that. - Constrained modes can restrict which schema features you may use, such as optional fields or deeply nested objects. Keep your schema flat and small, and it will work in most places.
Even with a native feature, keep your own validator. It costs a few lines, and it gives you one place to enforce rules that no schema can express, such as "every quote must appear in the source."
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `json.loads` fails on a reply that looks fine | Lead-in text, a code fence, or a trailing comma | Slice from the first `{` to the last `}`, and send the parse error back on retry |
| Line breaks break the JSON | Raw newlines inside a string value | Tell the model to write line breaks as `\n` inside strings |
| Quote check fails on a real quote | Curly quotes or different dashes in the source versus the reply | Normalize punctuation in `normalize`, or ask for shorter quotes |
| Model paraphrases the "quote" | The prompt did not say "word for word" | State it explicitly, and keep the check strict |
| Word count is wrong | You trusted the model's own count | Compute it in code from `body` |
| Empty `claims` list on a draft full of numbers | The model skipped the evidence step | Reject empty lists, and say "list every number as a claim" |
| Field types change between runs | The example in the prompt was ambiguous | Show an example with realistic placeholder values, and validate types |
Checks that structure alone does not give you
A validated reply is not a verified reply. Two gaps remain, and the next chapters address them.
First, the model decides which sentences count as claims. It can leave a risky number out of claims while still using it in body. To close that gap, run an independent check on the body text as well. The unsupported_numbers function from the repurposing workflow does this: it compares every number in the draft with the source, whether or not the model listed it.
Second, a quote can be real and still be misused. "Cut onboarding time by 30%" is in the source, but a draft that says "all customers cut onboarding time by 30%" has widened the claim. Only a human reviewer reliably catches that, so every draft still goes to review.
Summary of the working model
- Decide which fields downstream code needs, and use one schema for every format.
- Describe the schema in the prompt, and show a placeholder example.
- Ask for evidence (
source_quote) alongside each claim. - Parse defensively, validate shape and quotes, and compute derived values such as word count yourself.
- Retry with the specific error, a limited number of times, then hand the draft to a person.
- Treat a valid structure as input to review, never as approval.
Exercise
A model reply parses as valid JSON and has all four required fields. The claims list contains one entry with a correct source_quote. The body text, however, says "reduced costs by 45%", and the number 45 appears nowhere in the source. Which of the checks in this chapter would miss the problem, and what would you add to catch it?
Show answer
The structure check and the quote check would both pass, because the invented 45% was never listed as a claim. Add a check that runs on body itself, such as the unsupported_numbers function, which compares every number in the draft with the source. It would flag "45%". The draft should still go to a human reviewer.
Exercise
Your validator raises "Missing field: calltoaction" on the first attempt. Write the text you would append to the prompt on the retry, and explain why it is better than simply sending the same prompt again.
Show answer
For example: "Your previous reply was rejected: Missing field: calltoaction. Return only the corrected JSON object." Sending the same prompt again gives the model no information, so it may repeat the mistake. Naming the exact problem lets the model correct that one field. The attempt limit stops the loop if the model keeps failing.