← Building with AI

Showing examples (few-shot prompts)

Teach the format by example inside the messages.

Start this lesson

Sometimes the easiest way to explain what you want is to show it. A few-shot prompt includes a few example inputs with the answers you want, written as earlier user and assistant turns. The model sees the pattern and copies it for the new input. This works well for labels, short formats and a particular writing style.

# To run on your own computer with an API key (it cannot run in this browser).
# First: pip install anthropic, and set the ANTHROPIC_API_KEY environment variable.
import anthropic
client = anthropic.Anthropic()

messages = [
    {"role": "user", "content": "Review: Fast delivery, works perfectly."},
    {"role": "assistant", "content": "positive"},
    {"role": "user", "content": "Review: Arrived cracked."},
    {"role": "assistant", "content": "negative"},
    {"role": "user", "content": "Review: The battery lasts all week!"},
]
reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=5, messages=messages)
print(reply.content[0].text)   # most likely: positive

The two example pairs show the model that the answer is one lowercase word.

Two to five examples are usually enough. Pick examples that are different from each other, and include the tricky cases.

The pretend model notices when all example answers are one word and then answers with one word too.