Part 15 / Stage 4
Prompt engineering
Goal: Write prompts that work reliably — and prove it with evals instead of vibes. Time: ~2.5 hours · Needs: Part 14
What you will learn
- Clear, direct instructions
- Structure with XML tags
- Few-shot examples
- Letting the model think
- Breaking tasks into steps: prompt chains
- Evals: the only honest judge of a prompt
Topics in this part
Practice
These run fully offline; the eval harness scores any function that maps text to a label.
Exercise 1: Specify it
Take the vague prompt "Check this review" and rewrite it (as a printed string) into a specified one for deciding whether a product review mentions a safety issue: role, task, output labels, and the fallback for non-reviews.
Show the solution to Exercise 1
# Exercise 1: Specify it
PROMPT = """You review product reviews for safety issues.
Task: read the review below and decide whether it reports a SAFETY issue
(injury, fire, overheating, electric shock, choking hazard, toxic smell).
Output exactly one label:
- SAFETY the review reports a safety issue
- NO-SAFETY it is a normal review (quality, delivery, price complaints included)
- NOT-A-REVIEW the text is not a product review at all
<review>
{review_text}
</review>"""
print(PROMPT)
# Every edge case is decided up front: quality complaints are NO-SAFETY,
# off-topic text has its own label, and the output is machine-checkable.
Exercise 2: Build the fence
Write build_prompt(question, docs) producing: instruction header, <documents> with id-attributed <doc> tags, grounding rules (use only, cite, say-don't-know), and the fenced question. Print it for two SUPPORT_DOCS entries.
Show the solution to Exercise 2
# Exercise 2: Build the fence
from ailab import SUPPORT_DOCS
def build_prompt(question, docs):
context = "\n".join(f'<doc id="{d["id"]}">{d["text"]}</doc>' for d in docs)
return (
"You answer customer questions for an online store.\n"
"Use only the documents below. If they do not contain the answer, say you don't know.\n"
"Cite the doc id in square brackets after each fact.\n\n"
f"<documents>\n{context}\n</documents>\n\n"
f"<question>{question}</question>"
)
docs = [d for d in SUPPORT_DOCS if d["id"] in ("returns", "warranty")]
print(build_prompt("Can I return a laptop after 40 days if it is still boxed?", docs))
Exercise 3: Harden the classifier
The lesson's keyword classifier missed "Do you sell gift cards?" (predicted payment, wanted other). Fix the rule order/words so the eval reaches 1.0 on the six lesson cases — then add two NEW cases that break it again and print the new score.
Show the solution to Exercise 3
# Exercise 3: Harden the classifier
cases = [
("Where is my parcel? It's 5 days late", "shipping"),
("I want my money back for these shoes", "returns"),
("Card was charged twice", "payment"),
("Can't log in, reset link expired", "account"),
("Do you sell gift cards?", "other"),
("Package never arrived", "shipping"),
]
def classifier(text):
t = text.lower()
# Fix: match "card was charged"-style payment phrases, not the bare word
# "card" (which also appears in "gift cards").
rules = {
"shipping": ["parcel", "package", "late", "arrived"],
"returns": ["money back", "return"],
"payment": ["charged", "declined", "refund", "credit card", "debit card"],
"account": ["log in", "password", "reset"],
}
for label, words in rules.items():
if any(w in t for w in words):
return label
return "other"
def evaluate(classify, cases):
hits = 0
for text, want in cases:
got = classify(text)
hits += got == want
if got != want:
print(f"MISS: {text!r} expected={want} got={got}")
return hits / len(cases)
print("fixed classifier on lesson cases:", round(evaluate(classifier, cases), 3))
# Two new cases that break it again:
new_cases = cases + [
("The package of my gift card never came", "shipping"), # 'package' ok... but:
("I returned it last week, where is my refund?", "payment"), # 'return' fires first
]
print("with two new cases:", round(evaluate(classifier, new_cases), 3))
# Keyword rules are brittle by nature — every fix invites a new collision.
# That is exactly why Part 14's model-based triage plus THIS eval set wins.
Exercise 4: A/B the rules
Create classifier A (lesson's rules) and classifier B (your Exercise 3 version). Score both on the same 8-case set (6 original + your 2) and print a two-line comparison. Which wins, and on which cases do they differ?
Show the solution to Exercise 4
# Exercise 4: A/B the rules
CASES = [
("Where is my parcel? It's 5 days late", "shipping"),
("I want my money back for these shoes", "returns"),
("Card was charged twice", "payment"),
("Can't log in, reset link expired", "account"),
("Do you sell gift cards?", "other"),
("Package never arrived", "shipping"),
("The package of my gift card never came", "shipping"),
("I returned it last week, where is my refund?", "payment"),
]
def classifier_a(text): # lesson's original rules
t = text.lower()
rules = {"shipping": ["parcel", "package", "late", "arrived"],
"returns": ["money back", "return"],
"payment": ["charged", "card", "refund"],
"account": ["log in", "password", "reset"]}
for label, words in rules.items():
if any(w in t for w in words):
return label
return "other"
def classifier_b(text): # exercise 3's hardened rules
t = text.lower()
rules = {"shipping": ["parcel", "package", "late", "arrived"],
"returns": ["money back", "return"],
"payment": ["charged", "declined", "refund", "credit card", "debit card"],
"account": ["log in", "password", "reset"]}
for label, words in rules.items():
if any(w in t for w in words):
return label
return "other"
def score(classify):
results = [(text, want, classify(text)) for text, want in CASES]
return sum(w == g for _, w, g in results) / len(CASES), results
acc_a, res_a = score(classifier_a)
acc_b, res_b = score(classifier_b)
print(f"A (original): {acc_a:.3f}")
print(f"B (hardened): {acc_b:.3f}")
for (text, want, got_a), (_, _, got_b) in zip(res_a, res_b):
if got_a != got_b:
print(f"differs: {text!r} -> A={got_a} B={got_b} (want {want})")
Mini-project: Prompt A/B test
Write two versions of a triage prompt builder (terse vs specified-with-few-shot), a stand-in model that follows each prompt's rules deterministically, and score both on 30 labelled tickets with the eval harness. Print both scores and every MISS of the winner.
A complete version is in solutions/mini_prompt_ab_test.py.
Stretch: grow the eval to 100 cases and run it on every prompt change (Track A turns this into CI).
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Vague asks | The model fills gaps unpredictably | Decide edge cases in the prompt |
| Instructions and data interleaved | Model can't tell rules from content | XML-fence the data |
| Three easy few-shot examples | Edge cases stay undefined | Cover the tricky cases |
| "It looks better" after one try | Single samples are noise | Eval set, two scores |
| One mega-prompt | Untestable, unfixable | Chain with checkable steps |
| No "say you don't know" rule | Hallucinated answers to unanswerable questions | State the fallback explicitly |
Quick recap
- Specify role, task, constraints, output, and the impossible-input fallback.
- Fence data in XML tags; state grounding rules outright.
- Few-shot examples show the format on the hard cases.
- Buy reasoning room (steps / extended thinking) only where the task earns it.
- Chain multi-job prompts into checkable steps.
- Let the evals decide: a measured 0.833 with a visible MISS beats "seems better".
Checklist
- I rewrote a vague prompt into a specified one.
- I built a prompt with fenced documents and grounding rules.
- I chose few-shot examples that cover edge cases.
- I know when extended thinking is worth the cost.
- I sketched a task as a chain with checkable outputs.
- I ran the eval harness and read its MISS lines.
Read more: Prompt engineering overview