Sub topic 5
Asking for structured output and validating it
This chapter assumes you can write a prompt for a generative AI assistant, know the parts of a workflow (inputs, steps, outputs), and can read a short Python snippet. You have already seen how a parameterized template makes the input side of a workflow repeatable. Here we make the output side repeatable too.
Why free text breaks workflows
A model's reply is text. A person can read a paragraph and use it. A later step or a tool cannot. An email tool needs a subject line in one field and a body in another. If the model sometimes writes "Subject: ..." and sometimes puts the subject in bold, your workflow fails on some runs and not others.
Structured output means you tell the model the exact shape of the reply, usually JSON, and then check that the reply matches. Two parts are needed: asking for the shape, and validating what comes back.
Asking for a shape
Put the format in the prompt as a contract. Name every field, give its type, and state the limits. Add an instruction to return nothing else.
FORMAT_RULES = (
"Return only a JSON object with these keys:\n"
' "subject": string, at most 60 characters\n'
' "preview_text": string, at most 90 characters\n'
' "body": string, plain text\n'
"Do not add commentary or code fences."
)Append FORMAT_RULES to the end of your template. Keeping it in one constant means every step that produces an email draft uses the same contract.
Validating the reply
A model can still break the contract. It may leave out a key, return a number where you wanted a string, or write a subject that is too long. Validation is code that checks the reply before anything else uses it.
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 dataThe function does three jobs:
json.loadsfails if the reply is not valid JSON at all.- The loop checks that each required field exists and has the right type.
- The length check enforces a business rule that a schema alone would not express.
Notice that the same limit (60 characters) appears in the prompt and in the code. The prompt asks, and the code enforces. Never rely on the prompt alone.
What to do when validation fails
A failure should be visible and handled, not ignored. Common options:
- Retry once or twice. Send the same prompt again, or add the error message ("Subject is longer than 60 characters") so the model can correct itself.
- Stop and flag. After the retries run out, halt the workflow and send the raw reply to a person.
- Never pass it on. Do not let an invalid draft reach a publishing or email tool.
def get_valid_draft(prompt, call_model, max_attempts=3):
last_error = None
for _ in range(max_attempts):
full_prompt = prompt
if last_error:
full_prompt += f"\n\nYour last reply was rejected: {last_error}. Fix it."
raw = call_model(full_prompt)
try:
return parse_email_draft(raw)
except (ValueError, json.JSONDecodeError) as err:
last_error = str(err)
raise RuntimeError(f"No valid draft after {max_attempts} attempts: {last_error}")json.JSONDecodeError is a subclass of ValueError, so listing both is only for readability.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| `JSONDecodeError` | Model wrapped the JSON in a code fence or added a sentence before it | Say "no commentary or code fences"; strip fences in code if it still happens |
| Missing key | Format rules left a field out or were vague | List every key explicitly |
| Wrong type | A list returned where a string was expected | State the type next to each key |
| Limit exceeded | Model counts characters poorly | Enforce in code, retry with the error |
Where this fits
The chaining chapter relies on this one. When step two reads summary from step one, it can trust the shape only if step one was validated. Tool connections later depend on it as well, because a CMS or email platform expects exact fields.
Exercise
Your workflow asks for a social post as JSON with keys "text" and "hashtags" (a list of strings). A reply arrives with "hashtags" as one string, "#spring #bikes". Which part of the workflow should catch this, and what should happen next?
Show answer
The validation code should catch it, because the type check finds a string where a list was required. It should raise an error that names the field, and the workflow should retry with that error added to the prompt. If the retries run out, it should stop and flag a person instead of passing the post to a publishing tool.
Exercise
Why enforce the 60-character subject limit in code when the prompt already states it?
Show answer
Models do not reliably count characters, so they sometimes exceed a stated limit. The prompt only asks for the limit, and the code is the only part that guarantees it before the draft reaches the next step.