Few-Shot Examples and Chain-of-Thought Prompting
Two of the most powerful prompt engineering techniques are few-shot prompting (showing examples) and chain-of-thought (asking Claude to reason step-by-step before answering).
Few-Shot Prompting
Provide input-output examples to demonstrate the exact format and behavior you want:
import anthropic
client = anthropic.Anthropic()
FEW_SHOT_SYSTEM = """
You extract structured data from unstructured customer feedback.
Always respond with valid JSON matching the schema shown in the examples.
"""
few_shot_messages = [
{
"role": "user",
"content": "Feedback: 'The product arrived broken and customer support was rude.'"
},
{
"role": "assistant",
"content": '{"sentiment": "negative", "issues": ["damaged product", "poor support"], "priority": "high"}'
},
{
"role": "user",
"content": "Feedback: 'Delivery was fast and the packaging was excellent!'"
},
{
"role": "assistant",
"content": '{"sentiment": "positive", "issues": [], "priority": "low"}'
},
{
"role": "user",
"content": "Feedback: 'Good product but the setup instructions were confusing.'"
},
]
response = client.messages.create(
model="claude-haiku-4-5",
max_tokens=256,
system=FEW_SHOT_SYSTEM,
messages=few_shot_messages,
)
print(response.content[0].text)
# {"sentiment": "mixed", "issues": ["unclear instructions"], "priority": "medium"}
Chain-of-Thought Prompting
Asking Claude to reason before answering dramatically improves accuracy on complex tasks:
def solve_problem_with_cot(problem: str) -> dict:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
messages=[{
"role": "user",
"content": f"""Solve this problem step by step.
Problem: {problem}
First, think through the problem carefully in <thinking> tags.
Then provide your final answer in <answer> tags."""
}],
)
text = response.content[0].text
# Parse the structured response
thinking = text.split("<thinking>")[1].split("</thinking>")[0].strip()
answer = text.split("<answer>")[1].split("</answer>")[0].strip()
return {"reasoning": thinking, "answer": answer}
result = solve_problem_with_cot(
"A train leaves City A at 60 mph. Another leaves City B (300 miles away) "
"at 40 mph heading toward City A. When do they meet?"
)
print("Reasoning:", result["reasoning"])
print("Answer:", result["answer"])
Extended Thinking (Claude 3.7+)
For the most demanding reasoning tasks, extended thinking gives Claude dedicated reasoning tokens:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000, # Tokens allocated for internal reasoning
},
messages=[{
"role": "user",
"content": "Prove that there are infinitely many prime numbers."
}],
)
for block in response.content:
if block.type == "thinking":
print("Internal reasoning:", block.thinking[:200], "...")
elif block.type == "text":
print("Final answer:", block.text)
Few-shot examples anchor the output format; chain-of-thought anchors the reasoning quality.