Sub topic 5
Few-shot examples and output structure
This chapter assumes you have called a chat-style LLM API, can read Python, and know what a context window is. It also assumes you read the previous chapter on starting with prompting. Few-shot examples are the next step after a clear instruction. They cost nothing to try, and they show whether prompting alone can reach your target before you consider RAG or fine-tuning.
What few-shot prompting is
A few-shot prompt includes a small number of worked examples of the task, each pairing an input with the output you want. The model reads them and continues the pattern for your real input. A prompt with no examples is zero-shot. A prompt with one example is one-shot.
The model's weights do not change. The examples exist only for the duration of the request, which is called in-context learning. This is why few-shot prompting sits at the cheap end of the three levers: you change the input, not the model and not the data pipeline.
Few-shot examples mostly fix behavior gaps. They teach label vocabulary, tone, length, and format. They do not reliably fix knowledge gaps. If the model does not know your refund policy, showing it two refund tickets will not teach the policy. That is a job for retrieval.
Building a few-shot prompt as chat messages
In a chat API, the usual way to supply examples is as alternating user and assistant messages placed after the system message. The model treats the assistant turns as things it has already said, so it tends to keep answering in the same shape.
def build_messages(question, examples):
messages = [{
"role": "system",
"content": "Classify the support ticket as billing, bug, or other. Reply with one word.",
}]
for text, label in examples:
messages.append({"role": "user", "content": text})
messages.append({"role": "assistant", "content": label})
messages.append({"role": "user", "content": question})
return messages
examples = [
("I was charged twice this month.", "billing"),
("The export button crashes the app.", "bug"),
]
messages = build_messages("My invoice shows the wrong amount.", examples)The structure is: one system message with the rule, then one user/assistant pair per example, then the real question as the final user message. The model's next turn is the answer.
Note what the system message does and what the examples do. The system message states the rule: three labels, one word. The examples demonstrate it. Using both is usually stronger than either alone, because the instruction covers cases the examples do not, and the examples resolve ambiguities the instruction leaves open.
Choosing good examples
The examples are the most influential part of the prompt, so choose them deliberately.
- Cover every label. If the task has three classes, show at least one example of each. A model that never sees
othermay rarely output it. - Include hard cases. Easy examples teach little. Add borderline tickets, such as a billing complaint that mentions a crash, along with the label you want in that case.
- Match the real input distribution. Use text that looks like production traffic, including typos, length, and noise. Clean, invented examples can mislead the model.
- Keep the format identical. Every example should use exactly the output format you want. One inconsistent example can pull the model off pattern.
- Vary the examples. Near-duplicates waste tokens and can make the model copy surface features such as a shared phrase.
- Watch the order. Models can be sensitive to ordering. They sometimes favor the label of the last example, or the most common label in the set. Shuffle or balance the order, and test more than one ordering.
Taking examples from real, reviewed data is better than writing them from memory. It also connects to later chapters: a set of good input and output pairs is the same raw material you would need for fine-tuning, so the work is not wasted if you escalate.
Output structure
Examples teach format by demonstration. You can also state the format directly and make it checkable. Structured output matters because your code, not a person, usually reads the reply. A reply of "I think this is probably a billing issue" breaks a program that expects billing.
Useful techniques, from lightest to strongest:
- State the format in the instruction. "Reply with one word" or "Reply with JSON containing the keys
labelandconfidence." - Demonstrate it in the examples. Every assistant turn uses the format.
- Use delimiters. Wrap input in clear markers, such as triple quotes or XML-style tags, so the model can tell instructions from data. This also reduces the chance that text inside a ticket is read as an instruction.
- Use the API's structured output feature, if your provider has one. Many APIs can constrain the reply to a JSON schema or a fixed set of values. This is stronger than a prompt request, because it limits what the model can generate rather than asking nicely.
- Validate in code. Never trust the format even when you asked for it.
Here is a small validator for the classifier above. It normalizes the reply and falls back safely when the model drifts.
ALLOWED = {"billing", "bug", "other"}
def parse_label(reply):
label = reply.strip().lower().rstrip(".")
if label in ALLOWED:
return label
return None
for reply in ["billing", " Bug.", "This looks like a billing issue."]:
print(repr(reply), "->", parse_label(reply))The first two replies parse to billing and bug. The third returns None, which your code can handle by retrying once, or by routing to other, or by logging the case for review. Counting how often None appears is also a useful quality signal.
Structured instructions
Few-shot examples work best next to a well-organized instruction. A reliable layout has labeled sections:
- Role and task. One or two sentences on what the model is doing.
- Rules. The constraints, such as allowed labels, length limits, and what to do when unsure.
- Format. The exact shape of the output.
- Examples. The worked pairs.
- Input. The real item, clearly delimited.
Give the model an explicit way out. "If the ticket fits none of the labels, answer other" prevents invented labels. For generation tasks, "if the information is not present, write unknown" reduces made-up details.
Costs and limits
Few-shot examples are cheap to try but not free.
| Concern | Effect of few-shot examples |
|---|---|
| Cost | Every example is billed as input tokens on every request. Ten examples of 100 tokens each add 1,000 tokens per call. |
| Latency | A longer prompt takes longer to process, though usually only slightly. |
| Context budget | Examples compete with retrieved passages and conversation history for the same window. |
| Freshness | None gained. Examples do not add facts. |
| Control | Moderate. Behavior follows the examples but is not guaranteed. |
| Maintenance | Easy. Edit the list and re-run your evaluation. |
Some providers cache a repeated prompt prefix, which lowers the cost of a fixed block of examples. Put the static examples first and the changing question last so the prefix stays identical between calls.
Few-shot prompting has limits too. At some point, adding more examples stops helping, or the prompt grows too large to afford. Examples also cannot teach a style so subtle that you cannot explain it in a few samples, and the model may still drift on long or unusual inputs.
Selecting examples dynamically
When you have a larger pool of good examples, you can pick the most relevant ones per request instead of using a fixed set. You embed the incoming question, find the most similar stored examples, and place those in the prompt. This uses the same similarity ranking you will see in the RAG chapters, but retrieves demonstrations instead of facts. It helps when inputs vary widely. It also adds a retrieval step to maintain, and it makes results less predictable, since the prompt differs on every call. Add it only if a fixed set fails on your evaluation.
Common errors
- Examples that contradict the instruction. If the rule says one word and an example gives a sentence, the model follows the example.
- Label leakage from imbalance. If eight of ten examples are
bug, the model leans towardbug. - Testing on your own examples. If an evaluation item also appears in the prompt as an example, your score is inflated. Keep the evaluation set separate from the examples.
- Using examples to carry facts. They are the wrong tool for knowledge. Use retrieval.
- Never measuring. Adding examples feels like progress. Compare the score before and after on a fixed evaluation set, and keep the change only if it helps.
When few-shot is not enough
Escalate when you have measured and still fall short. If outputs are correct only when the model is given facts it lacks, add RAG. If the model still ignores the format or style after careful examples and structured output, and you have hundreds or thousands of good pairs, consider fine-tuning. Fine-tuning bakes the examples into the weights, so you stop paying for them as tokens on each request. Until your evaluation shows that gap, few-shot prompting is the cheapest lever to keep.
Exercise
Your ticket classifier is run with three examples, all labeled bug. It now answers bug for most billing tickets. Name the likely cause, give two changes to the examples, and say how you would check that the fix worked.
Show answer
The cause is label imbalance in the examples, which biases the model toward bug. Add at least one example for each label (billing, bug, other) and balance their counts, and include a borderline case or two, such as a billing complaint that mentions an error. Shuffle the order and test more than one ordering. To check, run the prompt on a fixed evaluation set that does not contain the example tickets, and compare per-label accuracy before and after. Keep the change only if billing accuracy improves without hurting the other labels.
Exercise
A model replies "Sure! This looks like a billing issue." although the instruction says to reply with one word. List three steps, in order of increasing strength, that make the output reliably parseable.
Show answer
First, state the format in the instruction and show it in every example assistant turn. Second, use the API's structured output or constrained generation feature, if available, to limit replies to the allowed labels. Third, validate in code: normalize the reply, accept it only if it is in the allowed set, and retry or route to a fallback otherwise. Also track the rate of invalid replies in your evaluation.