Instructions, examples, and in-context learning
A prompt is an instruction given to a model to perform a task. Prompt engineering is the cheapest adaptation technique and — thanks to strong base models — often enough on its own, so exhaust it before reaching for finetuning. Two properties of the model shape how much effort it takes: it must be able to follow instructions at all, and it should be robust to perturbation (writing "5" vs. "five", an extra newline, or different capitalization shouldn't swing the answer). Stronger models are generally more robust, so they need less fiddling.
Key concept · The three parts of a prompt
A prompt generally has up to three parts: a task description (what you want done — including the role the model should play and the output format), example(s) of how to do the task, and the task itself (the concrete question to answer or text to process). Not every prompt needs all three, but naming them helps you build prompts deliberately rather than by trial and error.
Key concept · In-context learning: zero-shot and few-shot
Teaching a model via examples in the prompt is in-context learning, introduced in the GPT-3 paper ("Language Models Are Few-Shot Learners"). It was a breakthrough: the model learns the desired behavior from the prompt, with no weight updates — a form of continual learning that lets a model use information beyond its training cutoff. Each example is a shot: five examples is 5-shot learning; no examples is zero-shot. More examples generally help but cost context (and tokens). As models get stronger, the gain from few-shot over zero-shot shrinks — though few-shot still matters for niche domains the model saw little of.
Two slots, one final prompt
Many APIs split a prompt into a system prompt and a user prompt — think of the system prompt as the task description (the standing role and rules) and the user prompt as the task (this turn's question and data). The book uses prompt for the whole input and context for the information provided so the model can do the task.
Key concept · Chat templates — and why they bite
Under the hood, the system and user prompts are concatenated into one final prompt via the model's chat template before being fed to the model — so from the model's view they're processed the same way. Each model family has its own template (Llama 2 uses [INST] <<SYS>>…; Llama 3 switched to <|start_header_id|> tokens), and a provider can change it between versions. Using the wrong template — even an extra newline — causes silent failures: the model still returns something plausible, so the bug is hard to spot. Good practice: match the model's documented template exactly, verify any third-party tool uses the right one, and print the final assembled prompt to check.
Key concept · Why system prompts can boost performance
Providers report that a good system prompt improves results. Since the two prompts are ultimately concatenated, the boost comes from one of two things: the system prompt comes first, and models are often better at instructions placed early; and models are frequently post-trained to prioritize the system prompt (OpenAI's "instruction hierarchy"). That prioritization also helps defend against prompt attacks — user input can't as easily override system rules.
How much you can say — and where to say it
How much you can put in a prompt is bounded by the model's context length, which has ballooned — from GPT-2's 1K tokens to Gemini-1.5 Pro's 2M in about five years (2M ≈ 2,000 Wikipedia pages, or a sizable codebase). But a bigger window doesn't mean every position is used equally.
Key concept · "Lost in the middle" and needle-in-a-haystack
Research shows models understand instructions at the beginning and end of a prompt far better than those buried in the middle. The standard probe is the needle in a haystack (NIAH) test: insert a random fact (the needle) at different positions in a long context (the haystack) and ask the model to retrieve it — accuracy dips for middle positions. Tests like RULER further measure how gracefully a model handles long inputs. Practical upshot: put the most important instructions where the model attends most, and if performance degrades with length, shorten the prompt (this is context efficiency). Use private/real needles when testing, so the answer isn't already in training data.
How to write an effective prompt
Early prompt "hacks" ("write Q: not Question:", "I'll tip $300") can help weak models but age badly as models get better at following instructions. The durable practices are more principled.
Key concept · Be clear, give context, decompose, and let it think
Write clear, explicit instructions: say exactly what you want, ask for a specific output format, adopt a persona, and show examples. Provide sufficient context — it reduces hallucination — and decide whether the model may use only the given context or also its own knowledge. Break complex tasks into subtasks (prompt decomposition): a chain of smaller prompts is easier to debug, monitor, and sometimes parallelize, and lets you use cheaper models for easy steps. Give the model time to think with chain-of-thought (CoT) ("think step by step") and self-critique (ask it to check its own answer) — reasoning before answering measurably improves hard tasks.
Key concept · Iterate, version, and be wary of tools
Prompt engineering is empirical: experiment systematically and track results like any ML experiment (log the prompt, model, and sampling settings). Treat prompts as artifacts — version them and keep them separate from code — and watch for prompt–model coupling: a prompt tuned for one model may need rewriting when you switch models. Finally, vet prompt-engineering tools: some silently rewrite your prompt or make extra, billable API calls behind the scenes, so understand what a tool does before trusting it.
Defending against adversarial prompts
Exposing a model to users exposes it to prompt attacks — inputs crafted to make the model misbehave. The more tools and private data your application gives the model access to, the higher the stakes, so defense scales with capability.
Key concept · Three kinds of attack
Prompt extraction: getting the model to reveal its system prompt, so an attacker can copy your app or find weaknesses. Jailbreaking and prompt injection: jailbreaking bypasses the model's safety guardrails to make it do something it shouldn't; prompt injection smuggles malicious instructions into the model through user input or, more insidiously, through content it retrieves (a poisoned web page or document the agent reads and obeys). Information extraction: coaxing the model to leak its training data or confidential information it has access to.
Key concept · Defenses at three levels
No single fix suffices, so defend in layers. Model level: choose models with strong safety training and instruction-hierarchy prioritization of the system prompt. Prompt level: state rules explicitly, remind the model to ignore attempts to override its instructions, and repeat critical constraints. System level: the strongest lever — isolate and sanitize untrusted input, filter inputs and outputs with guardrails, give tools the least privilege they need, sandbox anything that executes, and keep a human in the loop for high-impact actions. Assume any text the model ingests — including retrieved documents — could be adversarial.
Chapter 5 quiz
Fifteen questions on prompts, in-context learning, best practices, and prompt attacks. Answer first, then expand Show answer.
Part A · Multiple choice
Prompt engineering guides a model's behavior by:
- A Crafting instructions — without changing the model's weights
- B Retraining the model
- C Editing the weights
- D Adding GPUs
Show answer
A. It's the cheapest adaptation technique; try it before finetuning.
The three parts of a prompt are:
- A Task description, example(s), and the task
- B System, user, assistant
- C Input, model, output
- D Prompt, context, answer
Show answer
A. The task description includes the desired role and output format.
In-context learning is significant because the model learns the behavior:
- A From examples in the prompt, with no weight updates
- B By finetuning
- C Only during pre-training
- D By editing its architecture
Show answer
A. Introduced in the GPT-3 paper; a form of continual learning.
Providing five examples in a prompt is called:
- A 5-shot learning
- B Zero-shot learning
- C Fine-tuning
- D Beam search
Show answer
A. No examples = zero-shot; each example is a "shot."
How are the system prompt and user prompt handled by the model?
- A Concatenated into one final prompt via a chat template
- B Sent to two different models
- C The user prompt is ignored
- D Processed in parallel and averaged
Show answer
A. From the model's view they're the same input.
The "needle in a haystack" (NIAH) test measures:
- A Whether a model can retrieve a fact placed at various positions in a long context
- B Training speed
- C Token cost
- D Model size
Show answer
A. Accuracy typically dips for information in the middle.
Breaking a complex task into a chain of smaller prompts is:
- A Prompt decomposition
- B Quantization
- C Jailbreaking
- D Zero-shot prompting
Show answer
A. Easier to debug, monitor, parallelize, and use cheaper models for easy steps.
Prompt injection differs from jailbreaking in that it:
- A Smuggles malicious instructions in via user input or retrieved content
- B Only reveals the system prompt
- C Requires retraining
- D Is always harmless
Show answer
A. Jailbreaking bypasses safety guardrails; injection inserts adversarial instructions (e.g. via a poisoned document).
Part B · True or false
Stronger models tend to be more robust to prompt perturbations, so they need less fiddling.
Show answer
True. An intelligent model understands "5" and "five" mean the same thing.
Using the wrong chat template throws a loud error that's easy to catch.
Show answer
False. It causes silent failures — the model returns something plausible, so print the final prompt to check.
A system-prompt performance boost can come from position (it's first) and post-training prioritization.
Show answer
True. Prioritizing the system prompt also helps defend against prompt attacks.
A prompt tuned for one model will always work identically on another.
Show answer
False. Prompt–model coupling means you may need to rewrite prompts when switching models.
The risk from prompt attacks grows as you give the model more access to tools and private data.
Show answer
True. Defense should scale with capability — least privilege, sandboxing, human-in-the-loop.
Part C · Short answer
Name two ways to "give the model time to think."
Show answer
Chain-of-thought (ask it to reason step by step) and self-critique/self-evaluation (ask it to check its own answer).
Name the three levels at which you can defend against prompt attacks.
Show answer
Model level (safety training / system-prompt prioritization), prompt level (explicit rules, remind it to resist overrides), and system level (isolate & sanitize input, guardrails, least-privilege tools, human-in-the-loop).