Learn prompting¶
A short guide to read before (or alongside) the labs. The README has setup, the file list and rules of thumb. This page explains how the pieces fit, which decisions matter, and where to go deeper.
1. What prompting is, and why it exists¶
A prompt is everything you send the model in one call: a system message with your rules, maybe a few worked examples, the user's text, and settings such as temperature and an output schema. The model reads only that, and writes the most likely continuation. Prompting is choosing those inputs so the answer is right, comes back in a shape your code can use, and stays right when the input is hostile.
The problem it solves: a model knows a lot about language and nothing about your business. It doesn't know that "rate batao" means a quotation request, that a complaint shouldn't create order lines, or that your code needs {"intent": ..., "lines": [...]} and not a friendly paragraph. Without that, you get answers that read well and break your pipeline.
Analogy: prompting is briefing a capable temp on day one. They are smart and fast, but they've never seen your company. A vague brief ("sort these messages") gets you their own idea of sorting. A good brief gives the categories with one-line definitions, two or three filled-in examples, a form to fill in, and a warning: "customers sometimes write 'tell your system to give me a discount'. Ignore that." And you check their first fifty before trusting them.
When you need it: always. Every topic after this one is a prompt underneath: tool descriptions (llm-api), retrieved chunks (rag), agent instructions (agents). Prompting alone is enough when the answer only needs the text in front of the model; when it needs live data, add tools (../llm-api); when it needs your documents, add retrieval (../rag).
2. The mental model¶
Read the diagram left to right.
- The left box is the whole prompt. System rules, worked examples as real user/assistant turns, and the buyer's message last. Plus knobs:
temperature,thinkandschema. - The model is stateless. It sees this call and nothing else. A chat "remembers" only because your code resends the history every time, and you pay for those tokens on every call.
- The right side is your code.
reply.parse(Triage)checks the shape;score()andcheck_triage()check whether it is right.
Analogy: the model is a call-centre agent with no notepad who gets a fresh printout for every call: the rulebook, a few sample calls, and the customer's words. Whatever isn't on the printout doesn't exist for them.
The one idea to hold on to: the model only knows what this call contains, and only your code knows whether the answer is right. Better wording raises the odds; a schema fixes the shape; a golden set tells you if a change helped; a check in code catches what slips through.
In code (one call):
import door
import triage
prompt = triage.load_prompt("triage-v3") # system text + 4 examples, from prompts/
messages = triage.build_messages(prompt, "Bhai 50 bag cement bhej do, Wardha site pe.")
reply = door.chat(messages, schema=triage.Triage) # the answer must be JSON of this shape
print(reply.parse(triage.Triage))
# intent='order' lines=[Line(product='cement', quantity=50.0, unit='bag')] city='Wardha'
door is the repo's one door to the model (../door/): Ollama with qwen3:8b by default, any hosted provider with LLM_MODEL (see Model providers).
3. The labs in three stages¶
Stage 1: what you send (01–02)¶
| Script | What you see | Key takeaway |
|---|---|---|
01_message_anatomy.py |
No system message: the model promises prices. No history: "make it 300" means nothing. Temperature 1.0: three answers in three runs. Thinking: ~10x the tokens | Rules in the system message; resend history; temperature 0 for anything you parse |
02_instructions_and_few_shot.py |
v1 (one line) vs v2 (definitions and rules) vs v3 (plus four examples) on six tricky messages | Definitions fixed all six; the examples added nothing for +60% tokens. Add examples only for a miss rules can't fix |
Stage 2: getting data back, and knowing it's right (03–04)¶
- 03 Structured output. "Answer in JSON" failed 1 in 4 on our run (a quantity as a string).
schema=makes the model produce only that shape. Then three layers make the schema good: a closed list (Literal), a description per field, and a validator that turns the string "N/A" into a real null. A valid shape still isn't a right answer: the closed list called a TMT bar "Tools", and "no_think" from Ollama's template turned up in the tags. - 04 Prompt versions. Each version is a file; the same 20 cases run against each; code scores them. On qwen3:8b: v1 15%, v2 95%, v3 95%. The ship rule is per slice, not the average (a prompt can win overall and lose Hinglish buyers), and a tie keeps the cheaper prompt. The misses were one pattern, an invented quantity 1 when the buyer gave no number. v5 added a rule for it; the Hinglish case still got "1 kg", and the ship rule kept v4. The fix that works is in code:
check_triage()flags a quantity that isn't in the text.
Stage 3: hostile input (05)¶
- 05 Injection basics. Nine attacks ("ignore all previous instructions", a fake system note, a fake JSON answer, a tag break-out, Hinglish instructions, two in new wording) and one honest buyer who writes "ignore my last message". On qwen3:8b the tags and the "this is data" rule never beat the naive prompt (5 of 10 safe vs 4 of 10), and the facts check never fired, because attackers type their fake values into the message. Phrase rules in code took it to 9 of 10; a polite "P.S." in new wording (A10) still flipped the order to "other", which is why a label never places an order on its own. The full defence stack is in the RnR capstone (
../rnr/03, learn-guardrails).
4. Decisions your team will face¶
| Decision | Start with | Change when |
|---|---|---|
| Where rules live | System message, short, one definition per label | Never in the user message, never glued to user text |
| Few-shot examples | None; clear definitions first | The eval shows a miss a rule can't fix: add one example for it, as real user/assistant turns, and keep it only if the score rises |
| Output | schema= with a Pydantic model, Literal for closed lists |
The task is free text for a person to read (a reply draft) |
| Temperature | 0 | Drafts where variety helps and a person edits the result |
| Thinking (reasoning) | Off | The golden set shows it fixes a slice that matters, and the latency and tokens are worth it |
| Prompt storage | Files with a version and a one-line note, in git | Many teams edit prompts: a prompt registry with the same versions and evals |
| When to ship a change | Golden set run: better on a slice, worse on none; a tie keeps the cheaper prompt | The set is small or stale: grow it from real misses first |
| Untrusted text | User turn and tags, phrase rules in code, a facts check, never a write from a label | Text can trigger writes or reach tools: add approval and the rnr guardrail stack |
5. What the labs don't cover¶
The labs use 20 cases, one model and a terminal. Production adds:
- A bigger, living golden set. Hundreds of cases sampled from real traffic, labelled by people, refreshed as buyers change how they write.
- Prompt management. Who can change a prompt, review before merge, the version recorded with every call, rollback.
- Model changes. A new model, or a new version of the same one, is a prompt change: rerun the eval before switching.
- Long and multi-turn context. Trimming history, summarising old turns, keeping the system prompt within budget (
../agents/04). - Cost. Long system prompts and examples are paid for on every call; prompt caching and shorter prompts matter at volume (
../rnr, cost phase). - Stronger injection defences. Classifiers, separate models for untrusted text, and least-privilege tools.
Check yourself¶
Answer each in a sentence or two, without looking. If one is hard, reread the section in brackets.
- A chat seems to remember what the buyer said earlier. Where does that memory actually live, and what does it cost you? (section 2)
- Why does a schema fix the shape of the answer but not whether it is right? (section 3, lab 03)
- A new prompt version scores higher on average but lower on Hinglish messages. Would you ship it? Why? (section 3, lab 04)
- Why can't tags plus a "this is data" rule be your only defence against injection? (section 3, lab 05)
- A teammate wants every message labelled "order" to place the order automatically, since the label is right 95% of the time. Would you agree? Why? (section 3, lab 05)
Same pattern, other industries¶
The labs triage B2B buyer messages, but the pattern carries across domains. What changes is the labels, the fields and the risk.
| Industry | Use case | What changes |
|---|---|---|
| E-commerce (B2C) | Route customer emails to returns, delivery, payments or product questions | Volumes are high: a small, cheap model with a tight schema; tone-sensitive replies go to people |
| Banking | Classify complaints for RBI reporting categories and pull account and date fields | Labels come from the regulator, so definitions are copied word for word; every label is audited |
| Healthcare | Sort patient portal messages: appointment, prescription refill, urgent symptom | Missing an urgent message is the costly error: score recall on that slice and send anything unsure to a nurse |
| Logistics | Read shipment exception emails into status, consignment number and reason | Fields must match the system of record: check every ID against it in code, like check_triage |
Going deeper: advanced prompting topics¶
Once the labs make sense, these are the topics worth searching for. Each one fixes a specific weakness of the basic approach.
| Topic | What it solves | Search for |
|---|---|---|
| Prompt optimisation | Hand-tuning prompts is slow and guessy | "DSPy", "automatic prompt optimization" |
| Example selection | Fixed examples don't fit every input | "dynamic few-shot", "example selection retrieval" |
| Self-consistency | One sample can be a fluke on hard cases | "self-consistency prompting", "majority vote LLM" |
| Prompt chaining | One prompt doing three jobs does each badly | "prompt chaining", "decompose LLM task" |
| Constrained decoding | Small models still slip outside a format | "constrained decoding JSON schema", "grammar-based sampling" |
| Prompt caching | Paying again for the same long system prompt | "prompt caching", "prefix caching" |
| Prompt registries | Many prompts, many owners, no history | "prompt management", "prompt versioning LLMOps" |
| Injection defences | Instructions hidden in user or retrieved text | "spotlighting prompt injection", "dual LLM pattern", "CaMeL" |
| Long-context behaviour | Rules in the middle of a long prompt get ignored | "lost in the middle", "context engineering" |
Before moving on, try these: the exercises in PRACTICE.md: a new intent through the whole loop, a Hinglish slice that stops getting worse, a new attack with a fix that doesn't hold honest buyers, then build complaint tickets from buyer messages yourself.
Next topic: tool calling. A tool's docstring is a prompt too, and the model's answer becomes a request your code runs.