Lesson 18: Structured Outputs & Reusable Templates
Force consistent, machine-readable outputs with JSON, tables, and XML tags — and stop rewriting prompts from scratch.
Why Structured Outputs Matter
Free-form answers are useless when your pipeline needs to parse them. The fix: tell the model exactly what shape the output must take — and show it an example.
1. Explicit Format Instructions
Analyze this feedback and return JSON with EXACTLY this structure:
{
"sentiment": "positive | negative | neutral",
"key_themes": ["..."],
"urgency": "high | medium | low"
}
Feedback: "Your product broke after 2 days and support hasn't replied!"
The schema doubles as instructions: keys, allowed values, and types are all specified.
2. The JSON Output Template
Return ONLY valid JSON, no markdown fences:
{"summary": "...", "findings": [...], "confidence": 0.0-1.0}
Then validate with json.loads() in your code — never assume the model got it right (use JSON mode / structured outputs when the API offers it).
3. Markdown Tables
For comparisons and structured data:
Compare React and Vue in a table:
| Aspect | React | Vue |
|---|---|---|
| Learning curve | | |
| Performance | | |
| Ecosystem | | |
4. XML Tags for Long, Multi-Part Outputs
Write a blog post about AI in healthcare.
<outline>
[outline here]
</outline>
<introduction>
[1 paragraph]
</introduction>
<conclusion>
[2 sentences]
</conclusion>
Tags let you (and the model) keep track of many sections — and let your code extract each part with a simple regex.
5. Delimiters Keep Parts Separate
| Delimiter | Use |
|---|---|
| ``` | Code blocks, long data |
| --- | Section separation |
| ||| | Separating examples |
| XML tags | Nested/multi-part structure |
Golden rule: never put user-provided text directly next to instructions — wrap it in delimiters (also a prompt-injection defense).
Reusable Prompt Templates
A template = a prompt with placeholder variables:
You are a [ROLE] specializing in [DOMAIN].
TASK: Create a [CONTENT_TYPE] about [TOPIC].
CONTEXT:
- Audience: [AUDIENCE]
- Tone: [TONE]
- Goal: [GOAL]
OUTPUT FORMAT: [FORMAT]
EXAMPLE: [SHOW_ONE]
Store templates in code with variables, and fill them per request:
template.format(role="SEO writer", topic="local SEO", audience="plumbers")
Template Library Ideas
- Content brief generator
- Data-analysis report (summary → findings → recommendations)
- Code review (correctness, style, security)
- Meeting notes (decisions, action items, owners)
- Customer reply drafts (tone-preserving)
Key Takeaways
- Specify the exact output shape (JSON/table/XML) and show an example.
- Validate structured output in code — JSON mode when available.
- Delimiters separate data from instructions and resist injection.
- Templates make your best prompts reusable; version them like code.
Next up: Prompting for agents — system prompts, tool schemas, and multi-step workflows.
# A reusable prompt template + JSON output validation in code
template = """You are a {role} specializing in {domain}.
Analyze the following input and return ONLY valid JSON matching:
{{
"summary": "string",
"top_findings": ["string"],
"recommendation": "string"
}}
INPUT: {user_input}"""
prompt = template.format(
role="customer success analyst",
domain="SaaS churn",
user_input='"We lost 40 customers this month, mostly from the starter plan."',
)
print(prompt)
# After the model replies, ALWAYS validate before trusting:
import json
model_reply = '{"summary": "Starter-plan churn is high.", "top_findings": ["40 customers lost"], "recommendation": "Investigate onboarding for starter plan."}'
try:
parsed = json.loads(model_reply)
print(f"\nValid JSON! Keys: {list(parsed.keys())}")
except json.JSONDecodeError:
print("\nInvalid JSON - retry or repair the output.")Lesson Code (Python)
# A reusable prompt template + JSON output validation in code
template = """You are a {role} specializing in {domain}.
Analyze the following input and return ONLY valid JSON matching:
{{
"summary": "string",
"top_findings": ["string"],
"recommendation": "string"
}}
INPUT: {user_input}"""
prompt = template.format(
role="customer success analyst",
domain="SaaS churn",
user_input='"We lost 40 customers this month, mostly from the starter plan."',
)
print(prompt)
# After the model replies, ALWAYS validate before trusting:
import json
model_reply = '{"summary": "Starter-plan churn is high.", "top_findings": ["40 customers lost"], "recommendation": "Investigate onboarding for starter plan."}'
try:
parsed = json.loads(model_reply)
print(f"\nValid JSON! Keys: {list(parsed.keys())}")
except json.JSONDecodeError:
print("\nInvalid JSON - retry or repair the output.")Console Output
You are a customer success analyst specializing in SaaS churn.
Analyze the following input and return ONLY valid JSON matching:
{
"summary": "string",
"top_findings": ["string"],
"recommendation": "string"
}
INPUT: "We lost 40 customers this month, mostly from the starter plan."
Valid JSON! Keys: ['summary', 'top_findings', 'recommendation']Code Visualization Tips
- Draw the JSON schema as a form with fields and allowed values the model must 'fill in'.
- Diagram the template as a fill-in-the-blanks card with variables as empty slots.
- Color-code a structured-output prompt: instructions vs. example schema vs. real data.
Professional Tips & Tricks
- Add 'no markdown fences, no explanations, JSON only' — models love wrapping JSON in prose.
- Use the API's structured output / JSON mode when available; fall back to prompts elsewhere.
- Wrap any user-supplied data in <user_input>…</user_input> tags to resist prompt injection.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Design a JSON Prompt
Up next · Continue learning
Prompting for Agentic Workflows
System prompts for agents, tool-use instructions, prompt chaining, and evaluation — production prompting for AI tools.