Lesson 5 of 16 · Level 2: Intermediate
Advanced Prompt Engineering: Prompt Chains, Structured Outputs and Fewer Hallucinations
- ⏱ 14 min read
- ❓ 4 review questions
- ✍️ Exercise with solution
- 📥 Downloadable template
In this lesson
- Break complex tasks into prompt chains that produce better results.
- Ask for answers in an exact structure (tables, JSON, templates) that's ready to use.
- Reduce hallucinations when you work with documents.
- Use AI to improve your own prompts, and test them like a pro.
- Know what result to expect from each technique and what to check before trusting it.
Use the reviews file for the three-prompt chain in the exercise, and log your prompt tests in the workbook.
- prompt-library.xlsx · includes the chain, table, JSON and devil's advocate templates, plus a Prompt tests tab
- customer-reviews.csv · 20 customer reviews for the exercise
In lesson 3 you learned the six-part formula, which handles most everyday tasks. This lesson opens the Intermediate level with advanced prompt engineering: the techniques people who work with AI daily rely on. You'll split work into steps, control the output format, ground answers in your documents and treat prompts as tools that get tested and improved, in any assistant.
- Chain prompts
- Structured outputs
- Ground in documents
- Critical roles
- Test and improve
Prompt chains: one big task, several small steps
When you ask for something complex in a single message ("analyze these 40 reviews, find the problems, propose fixes and write an email to the team"), the AI does everything at once and the quality of each part drops. It works better to split the job into a chain: each step has one clear goal, and its output feeds the next.
Step 1 · Extract
"Read these reviews and list every problem mentioned, with the
exact quote. Don't interpret anything yet."
Step 2 · Group
"Group the problems from the list above into categories. For each
category, say how many reviews mention it and sort them from most
to least."
Step 3 · Propose
"For the 3 most frequent categories, propose 2 solutions each, with
an estimated cost (low, medium, high) and timeline."
Step 4 · Communicate
"Using all of the above, write a 200-word email to the operations
team: the main problem, the data and the proposal."
The advantages: you can fix each step before moving on (an extraction error gets caught before it contaminates the conclusions), each instruction stays simple and the result is far more solid.
If your prompt has more than two major action verbs (analyze, compare, decide, write…), it will probably work better as a chain.
Structured outputs: answers ready to use
If you're going to copy the result into Excel, a CRM or another tool, ask for exactly the structure you need. The more precise the template, the less editing you'll do.
Tables
Return a table with these exact columns, in this order:
Date | Customer | Product | Issue | Urgency (High/Medium/Low)
One row per message. If a value isn't there, write "N/A".
Don't add any text before or after the table.
JSON (for automations)
When another program will read the result (for example, in an automation or a Python script), ask for JSON and show the shape:
Extract the data from this invoice and reply ONLY with valid JSON,
no explanations, in this shape:
{"vendor": "", "invoice_number": "", "date": "YYYY-MM-DD",
"subtotal": 0, "sales_tax": 0, "total": 0}
Use null for any field you can't find.
Expected result for an invoice from a Texas packaging supplier with 8.25% sales tax:
{"vendor": "Lone Star Packaging LLC", "invoice_number": "INV-004587",
"date": "2026-10-14", "subtotal": 1000.00, "sales_tax": 82.50,
"total": 1082.50}
Before accepting the extraction, check that subtotal + sales_tax = total ($1,000.00 + $82.50 = $1,082.50). If it doesn't add up, either the model misread a number or the invoice itself has an error: either way, check by hand. Validating what the model returns automatically is exactly what you'll do with Python in lesson 10.
Fixed templates
For documents you produce often (minutes, product sheets, site visit reports), paste the blank template and ask the AI to fill it in: every result comes out in the same easy-to-review format.
1. You need to analyze 60 survey responses, find themes, prioritize them and write a presentation. What's the best approach?
Splitting the task lets you check every intermediate result and improves the quality of each part.
Grounding answers in your documents
You saw in lesson 2 that models can invent plausible facts. When you work with documents (contracts, reports, policies, minutes), these instructions sharply reduce the risk:
- Rule 1Limit the source"Answer only with the information in the attached document."
- Rule 2Allow "I don't know""If the answer isn't in the document, write 'Not in the document.'" Without that way out, the model tends to fill gaps.
- Rule 3Ask for exact quotes"For each statement, copy in quotation marks the sentence from the document that supports it, with the section or page." That lets you verify in seconds.
- Rule 4Extract first, then conclude"First copy the relevant clauses; then, based only on them, answer the question."
<document>
[paste the contract here]
</document>
Question: What's the penalty if I cancel before 12 months?
Instructions:
1. Copy word for word any clauses about cancellation or penalties,
with their numbers.
2. Answer the question using only those clauses.
3. If the document doesn't specify it, say so clearly.
Asking for quotes reduces invention, but doesn't eliminate it. Find the quote in the original document (Ctrl+F or Cmd+F) before using it in anything important, especially legal, medical or financial matters.
Critical roles: make the AI push back
By default, assistants tend to agree with you and praise whatever you show them. For important decisions, explicitly ask for the opposite:
Devil's advocate
"Here's my plan to launch a delivery service. Act as a skeptical investor and give me the 5 strongest reasons it could fail."
Use it: before you present a proposal.Premortem
"Imagine it's a year from now and this project failed. Write the story of why it failed."
Use it: to uncover risks you hadn't seen.Expert panel
"Evaluate this proposal from three perspectives: finance, the customer and operations. Point out where they disagree."
Use it: when a decision affects several departments.Rubric scoring
"Score this text from 1 to 5 on clarity, persuasiveness and accuracy, justify each score and tell me what to change to raise each one to 5."
Use it: to review important writing.Expected result from a premortem: a short story with specific causes ("orders arrived cold because the delivery zone was too large," "the per-order delivery cost ate the margin"). Turn each cause into a question for your plan: what delivery radius is workable? What minimum order still leaves a margin? If the causes are generic ("not enough marketing"), ask it to be specific to your business and your city.
Metaprompting: let AI improve your prompts
AI is very good at writing instructions for itself. Two ways to use that:
IMPROVE A PROMPT
I'm going to use this prompt many times for [task]. Improve it so
the results are more accurate and consistent. Explain what you
changed and why. Current prompt:
"""
[your prompt]
"""
CREATE A PROMPT FROM SCRATCH
I want a reusable prompt for [task]. First ask me whatever you
need to know about the goal, the audience, the format and the
mistakes I want to avoid. Then write the prompt with placeholders
marked [LIKE THIS] for the parts that change each time.
2. You want AI to answer questions about your employee handbook without inventing anything. Which instruction matters most?
Limiting the source, allowing "not in the document" and requiring citations are the three keys to reducing hallucinations. "Use all your knowledge" invites exactly the opposite.
Test your prompts like a pro
A prompt you'll use many times (to sort emails, summarize calls or write product descriptions) deserves a real test, the same way you'd test an Excel formula before filling it down a whole column:
- Collect 10 to 20 real cases, including hard ones: ambiguous, incomplete, misspelled, in another language or off-topic.
- Define what a good result is before testing: correct category, no invented data, maximum length, tone.
- Run the prompt on every case and count how many come out right.
- Change one thing at a time (add an example, clarify a rule) and rerun the same cases. That's how you know whether the change helped.
- Save the winning version in your prompt library with the date and what it's for.
| Problem in the results | Usual fix |
|---|---|
| Inconsistent format | Show an exact example of the format and say "follow this format exactly." |
| Gets edge cases wrong | Add 2 or 3 examples of those cases with the correct answer. |
| Answers too long | Set a concrete limit (words, bullets, lines). |
| Invents data | Limit the source, allow "N/A" and ask for quotes. |
| Generic tone | Paste a sample of your own writing: "match the style of this example." |
Here's how a prompt for sorting support emails might evolve when it's always tested on the same 20 cases (these are the rows already filled in on the Prompt tests tab of the workbook):
Each version changes one thing: 65%, then 80%, then 95% accuracy. Without the fixed set of cases, you wouldn't know which change worked.
Before saving a prompt to your library, check:
3. You changed your email-sorting prompt. How do you know whether it actually improved?
Only comparing against the same cases tells you whether the change helped or you just got lucky on one example.
4. AI extracts from an invoice: subtotal $1,000.00, sales tax $82.50 and total $1,125.00. What do you do?
A sum that doesn't add up is a red flag. Asking the AI to "make the numbers match" could hide the error instead of finding it.
Practice exercise: your first chain with a structured output
Open customer-reviews.csv (20 reviews of an online coffee store) or use 10 or more real customer comments of your own (Google reviews, messages, surveys; remove names and personal data). Build a chain of three prompts:
- An extraction prompt that returns a table with fixed columns.
- An analysis prompt that groups and counts the topics.
- A writing prompt that turns the analysis into a 150-word executive summary.
See solution
PROMPT 1 · Extraction
Read the reviews between <reviews> tags and return ONLY a table:
# | Sentiment (Positive/Negative/Mixed) | Main topic | Key quote
Allowed topics: Price, Service, Shipping, Quality, Other.
If a review mentions several topics, pick the main one.
<reviews>
[paste here]
</reviews>
PROMPT 2 · Analysis
Using the table above: count the reviews by topic and sentiment,
sort the topics by number of negative reviews and point out the
topic that's most concerning, with 2 quotes that illustrate it.
PROMPT 3 · Writing
Write a 150-word executive summary for the store manager:
1 sentence with the main conclusion, the data behind it and
2 recommended actions. Direct tone, no unnecessary adjectives.
Check the step 1 table before moving on: the table must have exactly 20 rows if you used the file. If a review is misclassified (for example, "The bag arrived torn but they replaced it fast" tagged as purely Negative instead of Mixed), fix it right then, not at the end.
Summary
- Split complex tasks into prompt chains and review each step.
- Ask for exact structures (tables, JSON, templates) when the result goes into another tool, and validate totals.
- With documents: limit the source, allow "not in the document" and require quotes.
- Ask for critiques, premortems and rubric scores so you don't just get flattery.
- Improve your prompts with AI and test them on a fixed set of cases.
Next lesson: AI for Content Creation: Writing, Social Media, Images and Video. You'll apply these techniques to content with a workflow where you bring the strategy and the expertise.
Create your account in 30 seconds, mark your lessons and download your certificate at the end.