Courses / GenAI & LLM / Module 3
Module 3: Prompt and context engineering
8 h · theory 3 · hands-on 3 · project 1 · revision 1
You will be able to
- Write system prompts with roles, constraints and examples
- Apply few-shot, chain-of-thought and decomposition where they help
- Budget the context window and order context for recall
- Version prompts and test them
Capstone increment: Prompt templates stored as versioned files with a regression test per template.
Job-description skills: Prompt engineering · Lab tools: promptfoo, pytest
1. Prompts are code; context is data
A prompt template is code: version it, review it, test it. The context you fill it with at runtime (documents, history, retrieved chunks) is data: budget it, rank it, and trim it. Most quality problems in production come from the second part, which is why the field now talks about context engineering.
A good system prompt states who the model is acting as, the task, hard rules, the output format, and what to do when it can't comply (say “not found” instead of guessing). Be specific and literal. Models follow concrete instructions far better than adjectives like “be accurate”.
2. Techniques that earn their tokens
Few-shot examples: two to five input-output pairs teach format and edge cases better than paragraphs of rules. Pick examples that cover the hard cases (missing fields, unusual layouts), not just the easy ones.
Step-by-step reasoning: asking the model to work through intermediate steps helps on multi-step problems, and reasoning models do it internally. It costs output tokens and latency, so don't add it to extraction or classification where it rarely helps; measure first.
Decomposition: split one large ask into several focused calls (classify the document, then extract fields for that document type). Each prompt gets simpler and testable, at the cost of more calls.
Delimiters: wrap documents in tags such as <document>…</document> so the model can tell your instructions from the content. This also helps against prompt injection (Module 12), though it is not a full defence.
3. Budget the context window
System prompt, examples, retrieved documents, conversation history, the question and the space reserved for the answer all share one window. When the total overflows, something must be dropped, and if you don't choose, truncation will cut whatever comes last, often the user's question.
Decide a priority order: the system rules and the question are never dropped; old history is summarised or dropped first; lower-ranked retrieved chunks next. Use the planner below to see what each choice costs and what gets lost.
| Part | Wanted | Kept | Dropped |
|---|---|---|---|
| System prompt | 600 | 600 | - |
| Examples (3 × 250) | 750 | 750 | - |
| Retrieved docs (8 × 500) | 4,000 | 4,000 | - |
| History (6 turns × 180) | 1,080 | 1,080 | - |
| User question | 60 | 60 | - |
Guided experiments
- Set 30 chunks of 500 tokens with an 8,000-token window. With “Naive: cut the end”, what disappears first? Switch to “Trim by priority”. What is dropped instead?
- Move to a 128,000-token window. Everything fits. Now look at the cost per 1,000 calls. Is “just use a bigger window” free?
- Find the smallest number of chunks that still fits with 2 examples and 10 history turns in 8,000 tokens. This is the budget your retriever has to work within.
- Raise the output reserve to 4,000. Why must the reserve come out of the same window as the input?
4. Order matters: start, end and the middle
Models recall information at the beginning and end of a long context more reliably than in the middle (Liu et al., “Lost in the Middle”, 2023). Put instructions first, the most relevant evidence near the end next to the question, and keep the middle short.
Order also affects cost. Providers cache identical prompt prefixes and charge less for cached tokens, so put stable content (system prompt, examples, tool definitions) first and variable content (documents, question) last.
5. Version and test every prompt
Store prompts as files with a name and version (extract_invoice@v7), never as strings scattered through the code. Log which version produced each output. When quality changes, you can tell whether a prompt or a model change caused it.
Give every prompt a regression suite: a small set of inputs with expected outputs or properties (valid JSON, contains no invented values, says not found when the answer is absent). promptfoo runs such suites against several prompts and models side by side. Module 8 turns this into a full evaluation pipeline.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 3.1: Prompt A/B with promptfoo
Write two versions of the invoice-extraction prompt (zero-shot and few-shot with three hard examples). Run both with promptfoo against 15 sample invoices on a local model, checking valid JSON and three exact fields.
Expected: A promptfoo results table with pass rates per prompt version, and a one-paragraph note on which examples made the difference.
Lab 3.2: Prompt files and tests (capstone increment)
Move every prompt in the capstone into prompts/<name>@<version>.txt, load them by name, log the version with each request, and add a pytest regression test per template.
Expected: No prompt strings left in application code; logs show prompt versions; pytest runs the regression tests.
Lab 3.3: Measure position effects
Hide one key fact in a 20-chunk context at positions 1, 10 and 20, ask the same question 10 times per position against a local model, and record how often it’s answered correctly.
Expected: A small table of accuracy by position, and the context order you’ll use in the capstone.
Go deeper
Videos
- AI prompt engineering: A deep dive · Anthropic · ~76 min. Prompt engineers at a model lab on what actually works and why; strong on iteration and testing.
- How I use LLMs · Andrej Karpathy · ~131 min. Shows context management in practice: what to put in the window and when to start fresh.
Further reading
- Docs Prompt engineering overview · Anthropic docs. Clear, tested techniques with examples: roles, examples, XML structure, chaining.
- Article Effective context engineering for AI agents · Anthropic. Why the whole context, not just the prompt, is what you engineer.
- Paper Lost in the Middle: How Language Models Use Long Contexts · Liu et al., 2023. The measurements behind “put the important material at the start or end”.
- Article Prompt Engineering · Lilian Weng. A survey of prompting methods with the papers behind each.
GitHub repositories
- promptfoo/promptfoo: examples/: copy a config that compares two prompts across models with assertions.
- dair-ai/Prompt-Engineering-Guide: The techniques pages (few-shot, chain-of-thought, prompt chaining) with references to the original papers.
- anthropics/claude-cookbooks: Prompt caching and long-context examples: how to structure prompts for reuse and recall.
Checkpoint quiz
Interview questions
- Your RAG answers got worse after you increased the number of retrieved chunks from 5 to 20. What are the likely causes and how would you test them?
- How do you decide what to drop when the context window overflows?
- When would you use few-shot examples instead of more instructions?
- How do you structure a prompt to get the most out of provider prompt caching?
- How do you test a prompt change before it reaches production?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).