Sub topic 9
Teaching by Example with User and Assistant Pairs
Few-shot prompting shows the model a few worked examples and then gives it a new input. In a chat API you write each example as a user message followed by an assistant message. This chapter covers how to build those pairs, why they work, and where they go wrong.
This chapter assumes you can read Python lists and dictionaries and that you know the three core roles. It also assumes you know chat APIs are stateless: the model sees only what you send in each request. If those ideas are unfamiliar, review the earlier chapters on roles and history first.
What a few-shot pair is
A few-shot example is one user message containing a sample input, followed by one assistant message containing the output you want. The model reads the whole list as a conversation that already happened. When it generates the next assistant turn, it continues the pattern.
Here is a sentiment classifier with two examples and one real input at the end:
messages = [
{"role": "system", "content": "Classify the sentiment of the text as positive, negative, or neutral. Reply with one word."},
{"role": "user", "content": "The delivery was fast and the box was intact."},
{"role": "assistant", "content": "positive"},
{"role": "user", "content": "The app crashes every time I open it."},
{"role": "assistant", "content": "negative"},
{"role": "user", "content": "The package arrived on Tuesday."},
]The list ends with a user message that has no answer yet. That message is the real task. The pairs before it are the teaching material.
Why pairs work
Models are trained on large amounts of text and on conversations in this format. A pair gives the model two kinds of information at once:
- Task shape. The pair shows what an input looks like and what kind of output follows.
- Output format. The assistant message shows exact wording, casing, length, and punctuation. In the example above, the replies are lowercase single words with no period.
Format is the strongest effect. A system message saying "reply with one word" can still produce "Positive." or "The sentiment is positive." Two or three assistant messages that are clean single words make the correct format much more likely.
Should the system message stay?
Usually yes. Use the system message for the rules, and use the pairs to demonstrate them. The two should agree. If the system message says "reply with one word" and an example assistant message says "Sentiment: positive", the model has conflicting signals and will follow one of them unpredictably.
Building examples from data
Hand-writing message dictionaries gets tedious and invites typos. Store examples as plain data and generate the messages from them. The function below is complete and runs without any API key:
def build_few_shot(system_prompt, examples, new_input):
"""Return a messages list: system, example pairs, then the real input."""
messages = [{"role": "system", "content": system_prompt}]
for example_input, example_output in examples:
messages.append({"role": "user", "content": example_input})
messages.append({"role": "assistant", "content": example_output})
messages.append({"role": "user", "content": new_input})
return messages
EXAMPLES = [
("The delivery was fast and the box was intact.", "positive"),
("The app crashes every time I open it.", "negative"),
("The package arrived on Tuesday.", "neutral"),
]
messages = build_few_shot(
"Classify the sentiment of the text as positive, negative, or neutral. Reply with one word.",
EXAMPLES,
"Support answered quickly but could not fix my problem.",
)
for m in messages:
print(m["role"], "->", m["content"])Running it prints the roles in order: system, then alternating user and assistant, ending with user. Keeping the examples in a list means you can test, reorder, and swap them without touching the code that sends the request.
Sending the request
With an OpenAI-style API, the messages list goes in as-is:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=messages,
temperature=0,
)
print(response.choices[0].message.content)Setting temperature=0 makes the output as repeatable as the provider allows, which is useful for classification. Not every model accepts a temperature setting, so remove it if your model rejects it.
With the Anthropic Messages API, the system prompt is a separate parameter. The pairs still go in messages:
import anthropic
client = anthropic.Anthropic()
system_prompt = "Classify the sentiment of the text as positive, negative, or neutral. Reply with one word."
pairs = [
{"role": "user", "content": "The delivery was fast and the box was intact."},
{"role": "assistant", "content": "positive"},
{"role": "user", "content": "The app crashes every time I open it."},
{"role": "assistant", "content": "negative"},
{"role": "user", "content": "Support answered quickly but could not fix my problem."},
]
response = client.messages.create(
model="MODEL_NAME", # replace with a model available to you
max_tokens=10,
system=system_prompt,
messages=pairs,
)
print(response.content[0].text)The pairs are identical in both APIs. Only the placement of the system prompt differs.
Choosing good examples
The examples are effectively part of your program, and their quality sets the ceiling on the result. These points matter most.
Cover the categories
If every example is positive, the model learns that the answer is "positive". Include each label you expect. Include at least one example of the hard case, such as a neutral statement that mentions a date or product, because that is where the model is most likely to be wrong.
Keep the format identical
Every assistant message must follow exactly the same format. If one says positive and another says Positive!, the model treats both as acceptable and mixes them. If a program parses the output, inconsistent examples will break the parser sooner or later.
Watch the order
Models are sensitive to ordering. Two known effects:
- Recency. The last example before the real input tends to have the most influence. If your final example is "negative", the model leans slightly toward "negative".
- Label runs. Three "positive" examples in a row can bias the next answer toward "positive".
Mix the labels, and check results after reordering. If accuracy changes a lot when you shuffle, the examples are carrying too much weight, and you need more of them or clearer instructions.
Keep them representative
The examples should resemble real inputs in length, tone, and difficulty. If your examples are short and tidy but real inputs are long and messy, the model has less to go on where you need it most.
Count the cost
Every example is sent on every request, and you pay for those tokens each time. They also use part of the context window. Three to five good examples usually beat fifteen mediocre ones. If you need more, consider whether instructions, fine-tuning, or retrieving only the relevant examples is a better fit.
Common errors
Ending on an assistant message
If your list ends with an assistant message, you have usually forgotten to append the real user input. Depending on the provider, the request may be rejected, or the model may treat the final assistant text as the start of its own reply and continue it. Some Anthropic models support deliberately ending on an assistant message to prefill the reply, but that is a separate feature. Do not rely on it by accident.
Broken alternation
Providers differ in how they handle two user messages in a row. Some reject the request, and some merge the messages. Both outcomes can hide a bug where a pair lost its partner. A small check catches this before you send anything:
def check_few_shot(messages):
"""Raise ValueError if the examples are not clean user/assistant pairs
ending in a user message."""
turns = [m for m in messages if m["role"] != "system"]
if not turns:
raise ValueError("no user or assistant messages")
if turns[-1]["role"] != "user":
raise ValueError("the last message should be the real user input")
for index, message in enumerate(turns):
expected = "user" if index % 2 == 0 else "assistant"
if message["role"] != expected:
raise ValueError(
f"turn {index} is {message['role']!r}, expected {expected!r}"
)
check_few_shot(messages) # passes silently for the list built earlierTrimming through the middle of a pair
Long conversations are often trimmed to the latest messages. A trimming function that keeps only the last N messages can cut a pair in half and leave an assistant message first. Trimming also does not distinguish your fixed examples from real history, so it can drop the examples first. Keep the example block separate and add it back after trimming:
def trim_history(messages, max_turn_messages=10):
system_messages = [m for m in messages if m["role"] == "system"]
others = [m for m in messages if m["role"] != "system"]
return system_messages + others[-max_turn_messages:]
def build_request(system_prompt, example_pairs, history, max_history=10):
"""Fixed examples are never trimmed; only live history is."""
fixed = [{"role": "system", "content": system_prompt}]
for example_input, example_output in example_pairs:
fixed.append({"role": "user", "content": example_input})
fixed.append({"role": "assistant", "content": example_output})
recent = trim_history(history, max_history)
return fixed + recentChoose an even max_history so you do not start the live portion with an assistant message. The final element of the history should be the new user message.
Letting untrusted text into examples
Examples that come from user submissions, a database, or a tool are untrusted text. A stored "example" can contain instructions such as "ignore previous rules". Because the model sees examples as earlier conversation, it may follow them. Only use examples you or your team wrote and reviewed. If you select examples dynamically, select from a vetted set.
Examples that leak into the output
Sometimes the model repeats an example verbatim, especially when the real input is similar to one of them. If your examples contain placeholder names or numbers, they may show up in answers. Use realistic but varied examples, and test with inputs unlike any of them.
When not to use few-shot pairs
A clear system message is enough for simple, well-known tasks. Add pairs when the task has a fixed output format, a subtle labeling rule, or a house style that is easier to show than to describe. If you find yourself writing a long paragraph that explains a format, replacing it with two examples is usually clearer and shorter.
Exercise
You build a few-shot request with this list of non-system messages in order: user, assistant, user, assistant, assistant, user. The provider rejects it or behaves oddly. What is wrong, and how would you catch it before sending?
Show answer
The fifth message is an assistant message directly after another assistant message, so the user/assistant alternation is broken. This usually means a user example is missing or a pair was duplicated. Checking that the non-system turns alternate starting with user and ending with user, as check_few_shot does, catches it before the request goes out.
Exercise
Your classifier's examples are all labeled "positive" except the last one, which is labeled "negative". On test input the model answers "negative" too often. Name two causes and one fix.
Show answer
The causes are label imbalance, since most examples teach "positive", and recency bias, since the final example before the real input is "negative" and the model leans toward it. A fix is to rebalance the labels, include a neutral example, and mix the order so no single label comes last or appears in a long run. Then re-test on a set of labeled inputs.
Exercise
Why should fixed few-shot examples be kept separate from the conversation history that you trim?
Show answer
A trimming function that keeps only the latest messages can drop the examples, or cut a pair in half and leave an assistant message first. Keeping the examples in a fixed block and trimming only the live history keeps the pairs intact and the format guidance present on every request.