Skip to content
LearnAI

6.1Prompting, system prompts & few-shot

A prompt is the only thing a model knows about your task. Learn its anatomy, how in-context learning works, and why small wording changes matter.

⏱ 15 minBeginner

Everything the model knows about your task

When you send a message to a chat model, it doesn’t receive “your question”. It receives one long sequence of tokensTokenA chunk of text (a word, part of a word, or a character) that a language model reads and writes as a single unit.: hidden instructions from the application, earlier turns of the conversation, any documents you pasted, and finally your message, all stitched together by a chat template (see SFT & instruction tuning). The model then does what it always does: it predicts the most plausible continuation, one token at a time (see next-token prediction).

That sequence is the promptPromptThe input text (and other content) given to a model to condition its output., and it is the only channel through which you can tell the model about your situation. The model has no idea who your customers are, what your refund policy says, what JSON shape your code expects, or that you’d like a two-sentence answer instead of an essay. Anything you leave out, it fills in with the most statistically typical guess. Often that guess is fine. Sometimes it is confidently, fluently wrong.

So “prompt engineering” is less about magic phrases and more about writing a clear briefing. This lesson takes a prompt apart into its components, shows what each one buys you, and covers the three ideas that matter most in practice: few-shot examples, reasoning cues and structured output.

ANALOGY· Briefing a brilliant temp on day one

Imagine hiring an extremely well-read temp who has read half the internet but knows nothing about your company and forgets everything at the end of each day. Each morning you hand them a briefing sheet. If the sheet says “answer this ticket”, they’ll write something generic and polite. If it says who they work for, quotes the actual refund policy, shows two tickets answered the way you like, and specifies the form to fill in, the work comes back right.

The temp’s reading is the model’s pretraining. The briefing sheet is the prompt. “Who you work for and house rules” is the system prompt, the pasted policy is context, the two solved tickets are few-shot examples, and the form is the output format. Forgetting everything overnight is the model’s lack of memory between calls: every request must carry its own briefing.

The anatomy of a prompt

Most effective prompts are built from the same handful of parts. None is mandatory, but each one answers a question the model would otherwise have to guess:

  • System prompt (role and rules). The system promptSystem promptInstructions placed before the conversation that set the model's role, rules and context. sits in a separate, privileged slot before the conversation. It sets the persona, tone, rules and boundaries: “You are the support assistant for Northwind Audio. Only promise what the policy allows.” Models are trained to give it more weight than user turns, though that priority is a tendency, not a guarantee.
  • Context. Reference material the answer should be based on: a policy, a code file, retrieved search results. Without it, the model answers from memory, which may be outdated or simply not contain your private facts. Supplying the right context automatically is what RAG is about.
  • Task and input. The actual instruction plus the data it applies to. Be specific: “Triage this ticket and draft a reply” beats “help with this”.
  • Examples. One or more worked input → output pairs. They communicate format, label set, tone and edge-case handling more precisely than any description.
  • Output format. What shape the answer should take: “Respond with only a JSON object with keys…”. Essential whenever code, not a human, reads the output.
  • Reasoning cue. An invitation to work through the problem before answering, such as “think step by step about which rule applies”.

Delimiting the parts clearly helps. Wrapping a document in tags such as <policy>…</policy> tells the model where the policy starts and ends and lets your instructions refer to it by name. For long inputs, a common recommendation is to put the documents first and the question last, so the instruction is fresh when generation begins.

INTERACTIVEPrompt anatomy builder
Add to the prompt:
Model type
Assembled prompt≈ 46 tokens
role: user
Task + input~46 tok
Triage this support ticket and draft a reply to the customer. Ticket: "Hi, my Aero 2 headphones arrived 3 weeks ago and the left earcup has stopped working. Can I get my money back?"
Illustrative response≈ 105 tokens

Pre-written to show typical behavior. This is not a live model, and real outputs vary from run to run.

**Category:** Defective product (refund request) **Product:** Aero 2 headphones **Refund eligible:** Probably not **Draft reply:** Hi there, thank you for reaching out, and I'm sorry to hear about your headphones! Refund policies vary, but many retailers only accept returns within 14 days of delivery, so a refund may not be possible at this point. You may want to check the warranty terms. Best regards, [Your Name]
  • noGrounded in the real policy. Invents a "14-day" window: the model never saw the policy.
  • noMachine-parseable. Free-form markdown.
  • noConsistent category labels. Makes up its own label wording.
  • noOn-brand voice. Generic, chatty, ends with "[Your Name]".
Start with only the task, then add components one at a time and watch the response and the checklist change. Try the format spec with and without the reasoning cue, then switch to a reasoning model.

Things to try:

  1. Task only. The reply is chatty, ends with “[Your Name]”, and invents a 14-day return window. Nothing in the prompt said otherwise, so the model reached for a typical retail policy.
  2. Add context. The answer is now grounded in the actual 12-month defect rule. This single change fixes the factual error; no amount of clever wording could.
  3. Add examples, then the format spec. With examples alone, the output copies their key: value layout and label names. The explicit format spec turns it into strict JSON.
  4. Format + reasoning cue on a chat model. The reasoning is useful, but it comes out before the JSON, and a strict parser now fails. Fix: ask for a "reasoning" field inside the JSON, or use a reasoning model whose thinking happens in a separate channel.
  5. Remove the context but keep the reasoning cue. The model reasons carefully… from a wrong assumption. Chain-of-thought improves reasoning, not knowledge.

Zero-shot, few-shot and in-context learning

A zero-shot prompt describes the task and gives no examples. A few-shotFew-shot promptingIncluding a few worked examples in the prompt so the model infers the pattern (in-context learning). prompt includes a handful of demonstrations. The GPT-3 paper (Brown et al., 2020) made this famous: a large enough model, shown a few English → French pairs in its prompt, translates the next sentence, with no change to its weights. This is in-context learning. The “learning” lives entirely in the forward pass: the examples change what the model predicts, and nothing is remembered once the request ends.

What do the examples actually teach? A revealing study by Min et al. (2022) replaced the labels in classification demonstrations with random labels and found that performance often dropped only a little. The examples mattered mostly for showing the format, the label space (which answers are allowed) and the kind of input to expect, more than for teaching the input → label mapping itself. In practice that suggests a few rules:

  • Examples are the strongest format signal you have. The model copies their length, structure, punctuation and tone, sometimes more faithfully than you wanted.
  • Make them diverse. Three near-identical examples teach the model that every answer looks like that. Cover the edge cases you care about: an empty input, a refusal case, a tricky label.
  • Mind order and balance. Models can over-weight the last example or the most common label among the examples.
  • Instructions and examples should agree. If your format spec says JSON but your examples are prose, the model has to pick one, and you won’t like the choice.

Asking for reasoning: chain-of-thought

A transformer spends roughly the same amount of computation on every token it generates. A hard question answered in one word gets one token’s worth of thinking. Asking the model to write out intermediate steps gives it more tokens, and therefore more computation, and lets later steps read the results of earlier ones. This is chain-of-thoughtChain-of-thought (CoT)Having a model write out intermediate reasoning steps before its final answer. (CoT) prompting. Wei et al. (2022) showed it with few-shot examples that include worked reasoning; Kojima et al. (2022) found that simply appending “Let’s think step by step” helped too, on arithmetic and logic benchmarks.

Two caveats. First, CoT improves reasoning over information the model has; it does not add missing facts, as step 5 in the demo shows. Second, the written reasoning is not guaranteed to be the true cause of the answer. It is generated text, and it can be a plausible story told after the fact.

Prompting reasoning models

Modern reasoning models are trained with reinforcement learning to think at length before answering, usually in a separate “thinking” channel. That changes the advice:

  • Skip the “think step by step” cue. The model already does it. Vendor guides for reasoning models generally say explicit CoT instructions are unnecessary.
  • State the goal and the constraints, not the procedure. A detailed step-by-step recipe can make the result worse than letting the model plan its own approach.
  • Control effort with parameters, not prose. Many APIs expose a thinking budget or reasoning-effort setting. More thinking costs more tokens and latency, which is the test-time compute trade-off.
  • Still give context and formats. Thinking harder doesn’t let a model know your refund policy.

Structured output

When software consumes the answer, you need structured outputStructured outputMaking a model's answer follow a machine-readable format such as JSON matching a schema, either by instruction or by constraining decoding so only valid tokens can be generated., almost always JSON matching a schema. There are three levels of strictness:

  1. Ask nicely. Describe the JSON in the prompt and show an example. Works most of the time; occasionally you get a trailing comment, a markdown fence or a missing key.
  2. Validate and retry. Parse the output, check it against a schema (for example with Pydantic), and on failure send the error back and ask again.
  3. Constrained decoding. Many APIs and open-source inference engines can enforce a JSON schema or grammar during generation. At each step, tokens that would make the output invalid are masked out before sampling (see sampling), so the result is guaranteed to parse.

One trap: if you constrain the output to {"answer": ...}, you have also forbidden the model from reasoning first. Put a "reasoning" field before the answer field in the schema, since the model generates keys in order.

Prompt sensitivity: test, don’t guess

Prompts are surprisingly brittle. Sclar et al. (2023) varied only meaningless formatting choices, such as the separator between a field name and its value, capitalization and spacing, and measured accuracy differences of up to 76 points for one model on one task. Larger and instruction-tuned models are typically more robust, but no model is immune, and a prompt tuned for one model can underperform on the next.

The practical response is to treat prompts like code:

  • Keep a small test set of realistic inputs with known good outputs (see evaluation).
  • Change one thing at a time and re-run the whole set, not just the one example you were staring at.
  • Version-control prompts and record which model version each was tested on.
  • Put stable content (system prompt, long documents, examples) at the start and the varying input at the end. Besides being clear, this lets providers reuse the cached computation for the shared prefix (see the KV cache), which cuts cost and latency.
MATH CORNER · optionalIn-context learning as inference over tasks, with a worked example

One useful lens (Xie et al., 2021) treats in-context learning as implicit Bayesian inference. During pretraining the model saw many documents, each generated by some latent “task” or concept cc. Given a prompt of examples (x1,y1),…,(xn,yn)(x_1,y_1),\dots,(x_n,y_n) and a new input xx, a well-trained model approximately computes

p(y∣x,examples)=∑cp(y∣x,c)  p(c∣examples),p(y \mid x, \text{examples}) = \sum_{c} p(y \mid x, c)\; p(c \mid \text{examples}),p(c∣examples)∝p(c)∏i=1np(yi∣xi,c).p(c \mid \text{examples}) \propto p(c) \prod_{i=1}^{n} p(y_i \mid x_i, c).

Each example is evidence that sharpens the posterior over which task you mean.

Worked example. Suppose the model entertains three tasks for inputs that are short reviews: c1c_1 = sentiment (positive/negative), c2c_2 = topic (food, film, …), c3c_3 = formality (formal/casual). Uniform prior, 1/31/3 each. The likelihood of each demonstrated label under each task:

c1c_1 sentimentc2c_2 topicc3c_3 formality
prior0.3330.3330.333
ex. 1: “The soup was cold” → negative0.80.10.1
posterior after ex. 10.8000.1000.100
ex. 2: “Loved this film” → positive0.80.10.2
posterior after ex. 20.9550.0150.030

After ex. 2 the unnormalized weights are 0.8⋅0.8=0.640.8\cdot0.8=0.64, 0.1⋅0.1=0.010.1\cdot0.1=0.01 and 0.1⋅0.2=0.020.1\cdot0.2=0.02, summing to 0.670.67. Two examples took the model from a three-way guess to 95% confidence that you mean sentiment. Notice that the labels did most of the work by revealing the label space, consistent with the random-label finding above. This is a cartoon (real models don’t enumerate tasks), but it explains why a few examples help so much and why many more help less.

Token budgeting. For English text, a rough rule is 1 token ≈ 4 characters ≈ 0.75 words. A prompt with a 400-word policy, 5 examples of 60 words and a 50-word task is about (400+300+50)/0.75≈1,000(400 + 300 + 50)/0.75 \approx 1{,}000 tokens, paid on every single request unless it is cached.

In code

A typical call with a system prompt, delimited context, a few-shot example as prior turns, and JSON output validated on the way back. The shape is similar across provider SDKs; this one follows the Anthropic Messages API.

import json, anthropic
client = anthropic.Anthropic()

system = "You are the support assistant for Northwind Audio. Only promise what the policy allows."
policy = open("refund_policy.txt").read()

messages = [
    # few-shot example as a prior user/assistant exchange
    {"role": "user", "content": 'Ticket: "My cable frayed after 2 months."'},
    {"role": "assistant", "content": '{"reasoning": "Defect within 12 months.", "category": "hardware_defect", "refund_eligible": true}'},
    # the real request: context first, question last
    {"role": "user", "content": f"<policy>\n{policy}\n</policy>\n\nTicket: \"{ticket}\"\n"
        'Reply with only JSON: {"reasoning": str, "category": str, "refund_eligible": bool}'},
]
resp = client.messages.create(model=MODEL, max_tokens=500, system=system, messages=messages)
data = json.loads(resp.content[0].text)   # validate; on failure, send the error back and retry
COMMON MISCONCEPTIONS
  • “There are magic words that unlock better answers.” Most gains come from supplying missing information: context, examples, constraints and the output format. Phrasing tricks that help one model often do nothing, or harm, on the next.
  • “Few-shot examples train the model.” Nothing about the weights changes. The examples only condition this one forward pass, and they are forgotten when the request ends.
  • “Chain-of-thought makes the model know more.” It gives the model room to compute with what it already knows or was given. If the needed fact is missing, it will reason fluently from a wrong premise.
  • “The system prompt is a security boundary.” Models are trained to prioritize it, but text inside user input or retrieved documents can still override it. Enforce real permissions in code, not in prose.
  • “A prompt that works on my three examples works.” Prompt behavior varies with formatting, ordering and model version. Only a test set tells you whether a change helped.

Check your understanding

0/4 answered
  1. Q1.A support bot confidently states a 14-day return window, but your real policy is 30 days. What is the most effective fix?

  2. Q2.Researchers replaced the labels in few-shot demonstrations with random labels and performance often dropped only slightly. What does this suggest examples mainly teach?

  3. Q3.You force a chat model to output JSON of the form {"answer": ...} with constrained decoding, and accuracy on math questions drops. Why?

  4. Q4.Which advice fits prompting a dedicated reasoning model?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.