Skip to content

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”.

System promptrole, rules, formatExamples2–5 few-shot pairsRetrieved docsranked chunksHistoryrecent turns + summaryQuestionthe user’s askBudgettokens per partOrderrules first, ask lastContext windowinput + output reserveModelone callCandidate context (more than fits)Budget, order, then call the modeltrim lowest-ranked first
Context engineering is choosing what goes in, in what order, within a token budget. Most quality wins come from here.

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.

Common misconception: “A longer, more detailed prompt is always better.” Past a point, extra rules conflict, dilute attention and cost money on every call. Delete any line you can’t show improves your eval scores.

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.

Context budget plannerEverything you send competes for the same window. Make it overflow, then compare the two trimming policies.
6,490 of 7,000 input tokens used · $3.25 per 1,000 calls
PartWantedKeptDropped
System prompt600600-
Examples (3 × 250)750750-
Retrieved docs (8 × 500)4,0004,000-
History (6 turns × 180)1,0801,080-
User question6060-
Guided experiments
  1. 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?
  2. 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?
  3. 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.
  4. 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.

In production: Prompt caching only works on an exact prefix match. A timestamp or request ID at the top of your system prompt silently disables it.

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 code

Labs

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

GitHub repositories

Checkpoint quiz

1. Your context overflows and the naive client cuts the end. What is most likely lost?
2. Where should the most relevant retrieved evidence go in a long context?
3. Prompt caching stops working after you add the request time to the first line of the system prompt. Why?
4. When does step-by-step reasoning most often fail to pay off?
5. What is the main reason to version prompts as files?

Interview questions

  1. 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?
  2. How do you decide what to drop when the context window overflows?
  3. When would you use few-shot examples instead of more instructions?
  4. How do you structure a prompt to get the most out of provider prompt caching?
  5. 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).