Sub topic 5
Asking for structured output and validating it
This chapter assumes you have written prompts for a generative AI assistant, can read short Python snippets, and know how a workflow splits into inputs, steps, and outputs. It also assumes you have seen parameterized prompt templates. Here you will learn to ask a model for output in a fixed shape and to check that shape before anything else uses it.
Why structure matters in a workflow
A person can read a loose paragraph from a model and fix small problems as they go. A later workflow step or a marketing tool cannot. An email tool expects a subject field and a body field. A scheduler expects a date. A reporting step expects numbers it can add up.
If a model returns "Here's your email! Subject: Spring deals..." the next step must guess where the subject ends. Guesses fail in ways that are hard to see. Structured output removes the guesswork. You tell the model the exact fields you need, and your code checks that the reply has them.
Structured output has two halves:
- Asking: the prompt names the format, the fields, and the rules.
- Validating: code checks the reply before it moves on.
You need both. Models follow format instructions well but not perfectly, so validation is the safety net.
Choosing a format
JSON is the usual choice for workflows. It is a text format made of named fields, and nearly every language and marketing tool can read it. Other formats have their place.
| Format | Good for | Watch out for |
|---|---|---|
| JSON | Fields consumed by code or tools | Stray text around the JSON, missing quotes |
| CSV | Tables such as keyword lists | Commas inside values break columns |
| Markdown with fixed headings | Drafts a person will read and edit | Hard to check automatically |
| Plain text with labels | Quick, informal steps | Labels drift between runs |
Use JSON whenever a machine reads the result. Use Markdown when a person is the main reader and you only need a predictable layout.
Asking for the format
A good format request has four parts: the shape, the field rules, an example, and a ban on extra text.
Return only a JSON object with exactly these keys:
- "subject": string, at most 60 characters
- "preview_text": string, at most 110 characters
- "body": string, plain text, no HTML
Do not add any text before or after the JSON.
Do not wrap the JSON in a code fence.
Example:
{"subject": "Spring tune-ups start today", "preview_text": "Book before Friday and save 15%.", "body": "Hi there, ..."}Each part does a job:
- Exact keys stop the model from inventing names such as
titlein place ofsubject. - Types and limits tell the model what "valid" means, and they match the checks your code will run.
- An example shows the shape more clearly than a description does. Keep it short, and make its content different from what you want, so the model does not copy it.
- No extra text prevents replies that begin with "Sure! Here is the JSON:".
Some model services offer a built-in JSON mode or a schema feature that forces valid JSON. Use it when you have it. It reduces syntax errors, but it does not check your business rules, such as the 60-character subject limit. You still validate.
Validating the reply
Validation is a short function that stands between the model and the rest of the workflow. It parses the reply, checks the fields, and raises a clear error if anything is wrong.
import json
REQUIRED_FIELDS = {"subject": str, "preview_text": str, "body": str}
def parse_email_draft(raw):
data = json.loads(raw)
for key, expected_type in REQUIRED_FIELDS.items():
if not isinstance(data.get(key), expected_type):
raise ValueError(f"Missing or invalid field: {key}")
if len(data["subject"]) > 60:
raise ValueError("Subject is longer than 60 characters")
return dataRead it in three stages.
json.loads(raw)turns text into a Python dictionary. It raisesjson.JSONDecodeErrorif the text is not valid JSON, which catches replies with extra chatter or a missing bracket.- The loop checks that each required key exists and has the right type.
data.get(key)returnsNonefor a missing key, andNonefails the type check, so one test covers both cases. - The length check enforces a rule that a type check cannot express.
Levels of checking
Validation works in layers. Each layer catches a different kind of problem.
| Layer | Question | Example |
|---|---|---|
| Syntax | Is it valid JSON? | Unclosed brace |
| Shape | Are the right keys present with the right types? | `subject` is a list, not a string |
| Rules | Do values meet limits? | Subject over 60 characters |
| Content | Does it follow policy? | Banned phrase, missing disclosure line |
The sample function covers the first three. A content layer might look for banned words or required phrases:
BANNED_PHRASES = ["guaranteed", "risk-free", "act now"]
def check_content(draft):
text = (draft["subject"] + " " + draft["body"]).lower()
found = [p for p in BANNED_PHRASES if p in text]
if found:
raise ValueError(f"Banned phrases found: {', '.join(found)}")
return draftKeep checks cheap and deterministic. A check that always gives the same answer for the same input is easy to trust and easy to test. Judgments about tone or accuracy belong to human review or to a scoring step, which later chapters cover.
Handling failures
A validator that raises an error is only half the design. You must decide what happens next. There are three common options.
- Retry with feedback. Send the model its own reply and the error message, and ask for a corrected version. This fixes most format slips.
- Retry fresh. Run the same prompt again. This helps when the failure looks random.
- Stop and flag. Give up after a set number of tries and send the item to a person.
Here is a loop that combines them:
import json
REQUIRED_FIELDS = {"subject": str, "preview_text": str, "body": str}
def parse_email_draft(raw):
data = json.loads(raw)
for key, expected_type in REQUIRED_FIELDS.items():
if not isinstance(data.get(key), expected_type):
raise ValueError(f"Missing or invalid field: {key}")
if len(data["subject"]) > 60:
raise ValueError("Subject is longer than 60 characters")
return data
def get_valid_draft(prompt, call_model, max_attempts=3):
current_prompt = prompt
last_error = None
for attempt in range(1, max_attempts + 1):
raw = call_model(current_prompt)
try:
return parse_email_draft(raw)
except (ValueError, json.JSONDecodeError) as error:
last_error = error
current_prompt = (
prompt
+ "\n\nYour previous reply was rejected: "
+ str(error)
+ "\nReturn corrected JSON only.\nPrevious reply:\n"
+ raw
)
raise RuntimeError(f"No valid draft after {max_attempts} attempts: {last_error}")json.JSONDecodeError is a subclass of ValueError, so listing both is redundant but makes the intent clear to readers. The cap on attempts matters. Without it, a prompt that can never succeed would loop forever and spend money on each pass.
Common errors
These problems appear often in real marketing workflows.
- Code fences around JSON. Models often wrap JSON in a Markdown fence even when told not to.
json.loadsthen fails. You can strip a leading and trailing fence before parsing, but keep the instruction in the prompt as well. - Numbers as strings. A field such as
"word_count": "85"passes a presence check but fails a number check. Validate types, and convert deliberately when needed. - Silent truncation. If the reply hits the model's length limit, the JSON ends mid-way. The parse error tells you. Do not "repair" truncated JSON by guessing.
- Right shape, wrong content. A draft can pass every check and still invent a discount or a product feature. Structure checks catch format problems, not factual ones. Facts need review, covered in the chapter on human review.
- Overly tight rules. A check that rejects good drafts wastes retries. If a rule fails often, ask whether the rule or the prompt is wrong.
- Unvalidated values passed to tools. A publishing tool may accept any string. Validate before you send, because the tool will not.
Designing the schema for the next step
Work backward from the consumer. List what the next step or tool needs, then request exactly that.
For a social post workflow feeding a scheduler, the needs might be a post text, a hashtag list, and a suggested publish time. The schema follows:
SOCIAL_FIELDS = {
"text": str,
"hashtags": list,
"publish_at": str, # ISO 8601, for example 2026-12-01T09:00:00
}Some practical rules help:
- Prefer a few flat fields to deeply nested objects. Flat shapes are easier for the model to produce and easier for you to check.
- Use fixed value lists where you can. A
channelfield limited to"email","linkedin", or"instagram"can be checked with oneintest. - Use standard formats for dates (ISO 8601) so tools parse them without surprises.
- Allow an explicit "unknown" or empty value for facts the model might not have, rather than forcing it to invent something. A field like
"discount_percent": nullis better than a made-up number.
Testing your validator
Treat the validator as code that deserves tests. Feed it good replies and a set of known-bad ones.
import json
REQUIRED_FIELDS = {"subject": str, "preview_text": str, "body": str}
def parse_email_draft(raw):
data = json.loads(raw)
for key, expected_type in REQUIRED_FIELDS.items():
if not isinstance(data.get(key), expected_type):
raise ValueError(f"Missing or invalid field: {key}")
if len(data["subject"]) > 60:
raise ValueError("Subject is longer than 60 characters")
return data
good = '{"subject": "Spring tune-ups", "preview_text": "Save 15%", "body": "Hello"}'
bad_cases = {
"not json": "Sure! Here is your email.",
"missing field": '{"subject": "Hi", "body": "Hello"}',
"wrong type": '{"subject": "Hi", "preview_text": 5, "body": "Hello"}',
"long subject": json.dumps(
{"subject": "x" * 61, "preview_text": "p", "body": "b"}
),
}
print("good:", parse_email_draft(good)["subject"])
for name, raw in bad_cases.items():
try:
parse_email_draft(raw)
print(name, "-> unexpectedly accepted")
except ValueError as error:
print(name, "-> rejected:", error)Running this prints one accepted case and four rejections. If a bad case is accepted, you have found a gap in the validator before a real draft does. Keep these cases. They become part of the fixed test inputs you will use when you evaluate the whole workflow.
Where validation sits in a workflow
Place a validator right after every step whose output feeds code. In a chained workflow, that means after each model call that a later step or tool depends on. Catching a bad reply at step two is cheaper than finding out at step five that a field is empty.
Log the failures too. A count of how often each check fails tells you which prompt needs work. If subject length fails in one run out of five, tighten the prompt's wording on length, or lower the stated limit slightly so the model lands under the real one.
Exercise
A model reply passes json.loads and has every required field with the right type, but the email body promises "50% off" when the campaign brief says 15%. Which layer of checking would catch this, and what should the workflow do about it?
Show answer
No syntax, shape, or rule check catches it, because the reply is valid in form. A content check could catch it only if you compare the discount in the draft against the brief with code, for example by extracting percentages and comparing them. In general, factual errors need a human review checkpoint before publishing. The workflow should route drafts with claims about price or offers to a reviewer.
Exercise
Your validator rejects about 30% of replies because the subject is over 60 characters. Name two changes you could make before loosening the limit.
Show answer
Make the prompt state the limit more strongly (for example, "at most 55 characters") and add a short example subject that is under the limit. You could also retry with the error message included, so the model sees exactly what to fix. Loosening the limit is a last resort, since 60 characters comes from how email clients display subjects.
Exercise
Why should a retry loop have a maximum number of attempts, and what should happen when the maximum is reached?
Show answer
Some prompts can never produce a valid reply, and without a cap the loop would run forever and keep spending on model calls. When the cap is reached, the workflow should stop and send the item to a person, along with the last error, instead of publishing or silently dropping it.