Sub topic 5
Putting Examples into Chat Messages
This chapter assumes you know what a prompt and a completion are, can read short Python, and know the three chat roles: system, user, and assistant. It covers how to turn few-shot examples into a chat message list, where each part goes, and the errors that most often break it.
Why chat format changes how you write examples
In a plain-text prompt, the examples are one long string. You choose the delimiters yourself, such as Review: and Sentiment:. The model sees all of it as text to continue.
Chat models receive a list of messages instead. Each message has a role and some content. The API or the model's template then wraps each message in special tokens that mark who is speaking. This gives you a built-in delimiter between examples, so you don't need labels like Review: to separate input from output.
The most common chat encoding for few-shot examples is:
- The system message states the task and the output rules.
- Each example is a user message (the input) followed by an assistant message (the desired output).
- The real query is the last user message.
The model then replies as the assistant, continuing the pattern it has just seen.
Building the message list in code
The helper below follows the structure above. It takes a list of (input, output) pairs and a query, and returns the message list.
SYSTEM = "Classify the sentiment of each review as positive, negative, or neutral. Answer with one word."
examples = [
("The battery lasts all day and charging is fast.", "positive"),
("It stopped working after a week.", "negative"),
("The package arrived on Tuesday.", "neutral"),
]
def build_messages(examples, query):
messages = [{"role": "system", "content": SYSTEM}]
for text, label in examples:
messages.append({"role": "user", "content": text})
messages.append({"role": "assistant", "content": label})
messages.append({"role": "user", "content": query})
return messages
if __name__ == "__main__":
msgs = build_messages(examples, "The screen is bright but the speakers are weak.")
for m in msgs:
print(m["role"], "->", m["content"])Running this prints eight messages: one system message, six example messages, and the final user query. Note that the user content is only the review text. The role already says "this is an input", so no Review: prefix is needed.
You pass this list to whichever chat API you use. The call itself differs between providers, but the list shape is the same. Some APIs take the system text as a separate parameter instead of a message with role system. In that case, remove the first message from the list and pass its content separately.
What goes in the system message and what goes in the examples
The system message and the examples do different jobs, and they work best together.
| Part | Best used for | Weak at |
|---|---|---|
| System message | Task definition, allowed labels, tone, hard rules such as "answer with one word" | Showing subtle style or borderline decisions |
| Example turns | Exact output format, style, how to resolve borderline cases | Stating rules that apply to every input |
If the system message says "one word" and the example outputs are one word, the two signals agree. If they disagree, for example the system message says "one word" but the examples reply with full sentences, the model has to pick one. Examples often win, so the result is unpredictable. Check that both say the same thing.
Keeping example turns clean
Every example turn is a promise about what the real reply looks like. Several details matter.
- The assistant content must be exactly the output you want. If you want
positive, do not writeSentiment: positivein one example andpositivein another. The model copies whatever pattern it sees, including stray prefixes and trailing punctuation. - Do not add commentary to the assistant turns. Text like "Sure! The sentiment is positive." teaches the model to chat. If your code later parses the reply, that chat style breaks the parser.
- Keep the user turns in the same shape as real queries. If real queries are full emails with headers, examples with one-line inputs teach the wrong distribution.
- Use the same roles every time. Each example is exactly one user message followed by one assistant message, in that order. Some providers reject two consecutive messages with the same role. Others accept them but handle them in provider-specific ways.
For structured output, the same rule applies to the content. If you want JSON, every assistant turn should be valid JSON with the same keys. A single example with a missing key can cause the model to omit that key.
import json
SYSTEM = "Extract the product and the issue from the review. Reply with JSON only."
examples = [
("My kettle leaks from the lid.", {"product": "kettle", "issue": "leaks from the lid"}),
("The headphones crackle at high volume.", {"product": "headphones", "issue": "crackle at high volume"}),
]
def build_json_messages(examples, query):
messages = [{"role": "system", "content": SYSTEM}]
for text, result in examples:
messages.append({"role": "user", "content": text})
messages.append({"role": "assistant", "content": json.dumps(result)})
messages.append({"role": "user", "content": query})
return messagesUsing json.dumps on a dictionary guarantees that every example output is valid JSON with consistent quoting. Writing the JSON by hand makes typos more likely.
An alternative: examples inside one user message
You can also place all examples in the system message or in a single user message, using text delimiters as in the plain-text prompt. This is a valid design, and it is sometimes better.
| Approach | Advantages | Drawbacks |
|---|---|---|
| Separate user and assistant turns | Clear role boundaries. The model sees the examples as its own earlier replies. Easy to build and reorder in code. | Uses extra template tokens per example. Needs strict alternation on some APIs. |
| Examples inside one message | Works with any API, including single-prompt completion endpoints. Lets you add notes per example. | You must design and keep consistent your own delimiters. The model can confuse an example with the real query. |
If you use the single-message style, mark where the examples end and the real query begins, for example with a line such as Now classify this review:. Without a clear boundary, models sometimes continue an example instead of answering the query.
Common errors
- Examples leaking into the answer. The model replies with text copied from an example. This is more likely when you have few examples and the query resembles one of them. Add more varied examples and check the output against the example inputs.
- Format drift. The first reply matches the format, but later ones add explanations. This happens when the system message and the assistant turns disagree, or when the last user message contains extra instructions that change the format.
- Stale history in a conversation. In a multi-turn application, the real conversation turns are appended after the examples. If you rebuild the list on each request, keep the examples at the start, before the real history. If you append them at the end, the model may treat them as the latest request.
- Examples counted as real data. Logs, analytics, or storage that record "all assistant messages" may include your fixed examples. Mark them or generate them separately from stored history.
- Token cost on every call. Chat APIs are stateless, so the examples are sent and billed again on every request. Six short examples are cheap. Twenty long ones add up. Later chapters cover how many examples to use and how to trim them.
Verifying the structure
Before you spend time tuning examples, check that the message list is what you think it is. A short test can catch ordering bugs.
def check_messages(messages):
assert messages[0]["role"] == "system"
assert messages[-1]["role"] == "user"
body = messages[1:-1]
assert len(body) % 2 == 0
for i, m in enumerate(body):
expected = "user" if i % 2 == 0 else "assistant"
assert m["role"] == expected, f"message {i} has role {m['role']}"
return TrueCall check_messages(build_messages(examples, "test")) after any change to the builder. It confirms a system message at the start, strict user/assistant alternation in the examples, and a user message at the end.
Exercise
A teammate's few-shot chat prompt returns "Sure! The sentiment is positive." even though the system message says "Answer with one word." Their assistant example turns all read "Sure! The sentiment is positive/negative/neutral." What is the likely cause, and what is the fix?
Show answer
The examples contradict the system message, and the model follows the pattern shown in the examples. The fix is to change every assistant example turn to exactly the desired output, such as "positive", and keep the system message consistent with it.
Exercise
You build the message list with the real query placed before the examples, so the model's last input is an example turn. Why is this wrong, and what order is correct?
Show answer
The model replies to the last message, so it would continue from an example instead of answering the query. The order should be: system message, then alternating user and assistant example turns, then the real query as the final user message.