Sub topic 2
Putting Examples into Chat Messages
Assume you know what a language model is, can read basic Python, and understand system, user, and assistant chat roles. Few-shot prompting places labeled examples in the conversation before the new user query. The model uses them as temporary instructions about the task and answer format.
Put examples into chat messages
Each example normally has a user message containing an input and an assistant message containing the expected output. Keep the new query as the final user message.
SYSTEM = "Classify each review as positive, negative, or neutral. Answer with one word."
examples = [
("The battery lasts all day.", "positive"),
("The device stopped working.", "negative"),
("The package arrived on Tuesday.", "neutral"),
]
def build_messages(examples, query):
messages = [{"role": "system", "content": SYSTEM}]
for input_text, output_text in examples:
messages.append({"role": "user", "content": input_text})
messages.append({"role": "assistant", "content": output_text})
messages.append({"role": "user", "content": query})
return messages
messages = build_messages(examples, "The screen is bright but the speakers are weak.")
for message in messages:
print(message)The assistant messages are demonstrations, not actual model-generated answers. The model infers the relationship between each input and output, then applies it to the final input.
Choose representative and diverse examples
Examples should cover the inputs the model will actually receive. Include different wording, lengths, and difficulty levels while preserving the same task definition.
| Selection goal | Example choice |
|---|---|
| Representative | Common input with a clear label |
| Diverse | Different wording or edge of the input range |
| Balanced | Similar number of examples for each label |
Do not choose examples only because they are easy. Include ambiguous cases when those cases matter in production.
> callout note > Treat examples as part of the prompt's specification. Incorrect labels can teach the model the wrong rule.
How many examples are enough
Start with a small set, such as two or three examples per label. Add examples only when held-out evaluation shows a real improvement. More examples consume context-window space, increase cost, and can introduce contradictory patterns.
Order and label balance
Balance labels so one class does not dominate the demonstrations. Vary example order across evaluation runs. A model can be sensitive to recency, so place particularly important format or edge-case examples near the end, without relying on position alone.
Exercise
A classifier has six examples: five positive reviews and one negative review. What should you change first?
Show answer
Add representative negative and neutral examples, then evaluate the balanced prompt on held-out data.