Few-shot prompting is like teaching by example. Instead of explaining what you want, you show the AI model a few examples of the task you want it to do, and it learns the pattern.
Think of it like teaching a child to recognize animals. You don't just say "this is a cat" - you show them pictures of cats, dogs, and birds, and they learn to tell them apart.
What is Few-Shot Prompting?
Few-shot prompting gives an AI model 2-5 examples of input and output pairs. The model learns the pattern and applies it to new, similar tasks.
Why it works:
- AI models are pattern recognition machines - Examples are clearer than instructions - Models learn the "rules" from the examples - Works better than trying to explain complex tasks in words.
Basic Example: Text Classification
Let's teach an AI to classify emails as urgent or not urgent:
import { generateText } from "ai"
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Classify these emails as "urgent" or "not urgent":
Email: "The server is down and customers can't access the website"
Classification: urgent
Email: "Here's the weekly report from last week"
Classification: not urgent
Email: "Can you review this document when you have time?"
Classification: not urgent
Email: "Security breach detected - immediate action required"
Classification: urgent
Email: "The quarterly budget meeting has been moved to next Tuesday"
Classification: urgent
Now classify this email: "Please send me the project timeline by end of day"`,
})
The AI learns from the examples and correctly identifies the pattern: urgent emails contain time-sensitive or critical information.
Structured Data Extraction
Few-shot prompting excels at extracting structured data from unstructured text:
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Extract contact information from these messages:
Message: "Hi, I'm Sarah Johnson. My email is sarah@company.com and you can reach me at 555-1234."
Contact: {"name": "Sarah Johnson", "email": "sarah@company.com", "phone": "555-1234"}
Message: "Call me at 555-9876. I'm Mike Chen from TechCorp."
Contact: {"name": "Mike Chen", "email": null, "phone": "555-9876"}
Message: "This is Lisa Wang, lisa.wang@email.com, phone number 555-4567."
Contact: {"name": "Lisa Wang", "email": "lisa.wang@email.com", "phone": "555-4567"}
Now extract from: "Reach out to David Kim at david.kim@startup.io or 555-7890"`,
})
Code Generation
Teach the AI to generate code in a specific style:
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Generate React components with these patterns:
Task: Create a button component
Code:
\`\`\`tsx
interface ButtonProps {
children: React.ReactNode
variant?: 'primary' | 'secondary'
onClick?: () => void
}
export function Button({ children, variant = 'primary', onClick }: ButtonProps) {
return (
<button
className={\`btn btn-\${variant}\`}
onClick={onClick}
>
{children}
</button>
)
}
\`\`\`
Task: Create a card component
Code:
\`\`\`tsx
interface CardProps {
title: string
children: React.ReactNode
className?: string
}
export function Card({ title, children, className }: CardProps) {
return (
<div className={\`card \${className || ''}\`}>
<h3 className="card-title">{title}</h3>
<div className="card-content">{children}</div>
</div>
)
}
\`\`\`
Now create a modal component:`,
})
Writing Style Adaptation
Show the AI how to write in different styles:
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Rewrite these sentences in a professional, technical style:
Original: "This thing is really fast and works great"
Technical: "The system demonstrates exceptional performance with optimized processing capabilities"
Original: "The app is easy to use and looks nice"
Technical: "The application features an intuitive user interface with modern design principles"
Original: "It's super reliable and never breaks"
Technical: "The platform maintains high availability with robust error handling mechanisms"
Now rewrite: "This tool is awesome and saves tons of time"`,
})
Best Practices
1. Choose Good Examples
2. Use Consistent Formatting
Good examples:
- Show clear patterns - Cover different variations - Are representative of real use cases - Have consistent formatting
Bad examples:
- Too similar to each other - Don't show edge cases - Have inconsistent formats - Are unrealistic
// Good: Consistent structure
const prompt = `Task: [description]
Input: [example input]
Output: [example output]
Task: [description]
Input: [example input]
Output: [example output]
Task: [description]
Input: [new input]
Output:`
// Bad: Inconsistent structure
const prompt = `Do this: example1 -> result1
Now do: example2 -> result2
Please: example3 -> result3`
3. Include Edge Cases
Show the AI how to handle unusual situations:
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Extract the main topic from these sentences:
Sentence: "The weather is nice today"
Topic: weather
Sentence: "I can't find my keys anywhere"
Topic: lost items
Sentence: "The meeting was postponed until next week"
Topic: meeting
Sentence: "I don't know what to do about this problem"
Topic: uncertainty
Sentence: "Can you help me with this?"
Topic: request for help
Now extract from: "This is confusing and I'm not sure what's happening"`,
})
4. Test Your Examples
// Test your examples first
const testResult = await generateText({
model: "openai/gpt-5-nano",
prompt: `Your few-shot examples here...`,
})
console.log("Test result:", testResult.text)
// Verify the output matches your expectations
Common Patterns
Pattern 1: Input → Output
Perfect for transformations and conversions:
const prompt = `Convert these temperatures:
Input: 32°F
Output: 0°C
Input: 68°F
Output: 20°C
Input: 100°F
Output: 37.8°C
Convert: 75°F`
Pattern 2: Question → Answer
Great for Q&A and problem-solving:
const prompt = `Answer these questions about React:
Q: What is JSX?
A: JSX is a syntax extension that lets you write HTML-like code in JavaScript
Q: What is a component?
A: A component is a reusable piece of UI that can accept props and return JSX
Q: What is state?
A: State is data that can change over time and affects how a component renders
Q: What is useEffect?`
Pattern 3: Context → Action
Ideal for decision-making and recommendations:
const prompt = `Given this situation, what should I do?
Situation: User reports the app crashes when uploading large files
Action: Investigate file size limits and implement proper error handling
Situation: Database queries are running slowly
Action: Add database indexes and optimize query performance
Situation: Users can't find the settings menu
Action: Improve navigation design and add search functionality
Situation: Payment processing fails for international users`
Advanced Techniques
Chain of Thought
Show the AI how to think through problems step by step:
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `Solve these math problems step by step:
Problem: If a train travels 120 miles in 2 hours, what's its speed?
Solution:
Step 1: Distance = 120 miles
Step 2: Time = 2 hours
Step 3: Speed = Distance ÷ Time = 120 ÷ 2 = 60 mph
Answer: 60 mph
Problem: A rectangle has length 8 and width 5. What's its area?
Solution:
Step 1: Length = 8
Step 2: Width = 5
Step 3: Area = Length × Width = 8 × 5 = 40
Answer: 40 square units
Problem: If 3 apples cost $6, how much do 7 apples cost?`,
})
Role-Based Prompting
Define a specific role for the AI:
const result = await generateText({
model: "openai/gpt-5-nano",
prompt: `You are a helpful coding tutor. Teach concepts with examples:
Student: "What is a function?"
Tutor: "A function is a reusable block of code. Here's an example:
\`\`\`javascript
function greet(name) {
return \`Hello, \${name}!\`
}
console.log(greet('Alice')) // Output: Hello, Alice!
\`\`\`
Functions take inputs (parameters) and return outputs."
Student: "What is an array?"
Tutor: "An array is a list of items. Here's how to use one:
\`\`\`javascript
const fruits = ['apple', 'banana', 'orange']
console.log(fruits[0]) // Output: apple
console.log(fruits.length) // Output: 3
\`\`\`
Arrays store multiple values in order."
Student: "What is a loop?"`,
})
Integration with AI SDK
Using Few-Shot Prompts in Agents
import { Experimental_Agent as Agent } from "ai"
const codingAgent = new Agent({
model: "openai/gpt-5-nano",
system: `You are a coding assistant. Follow these patterns:
Task: Create a function
Pattern: Write clean, well-documented functions with TypeScript types
Task: Debug code
Pattern: Identify the issue, explain why it happens, provide a fix
Task: Optimize performance
Pattern: Analyze bottlenecks, suggest improvements, show before/after`,
tools: {
// Your tools here
},
})
const result = await codingAgent.generate({
prompt: "Create a function that validates email addresses",
})
Dynamic Few-Shot Examples
Load examples from your database or API:
async function generateWithDynamicExamples(task: string) {
// Load relevant examples from your database
const examples = await loadExamplesForTask(task)
const prompt = `Here are examples of ${task}:
${examples.map((ex) => `Input: ${ex.input}\nOutput: ${ex.output}`).join("\n\n")}
Now process: ${task}`
const result = await generateText({
model: "openai/gpt-5-nano",
prompt,
})
return result.text
}
Troubleshooting
Problem: AI ignores examples
Solution: Make examples more prominent and consistent:
// Bad: Examples buried in text
const prompt = `Please help me classify emails. Here are some examples: urgent emails are important, not urgent ones aren't. Classify this email...`
// Good: Clear, structured examples
const prompt = `Classify emails as "urgent" or "not urgent":
Email: "Server is down"
Classification: urgent
Email: "Weekly report attached"
Classification: not urgent
Email: "Security breach detected"
Classification: urgent
Classify: "Meeting moved to tomorrow"`
Problem: AI produces inconsistent output
Solution: Add more examples and be more specific:
const prompt = `Generate JSON responses in this exact format:
Input: "What's the weather?"
Output: {"type": "weather", "response": "I can help you check the weather"}
Input: "Set a reminder"
Output: {"type": "reminder", "response": "I'll help you set a reminder"}
Input: "Play music"
Output: {"type": "music", "response": "I can help you play music"}
Input: "What time is it?"`
Problem: Examples are too complex
// Start with basic examples
const simplePrompt = `Extract names:
Text: "Hello, I'm John"
Name: John
Text: "My name is Sarah"
Name: Sarah
Text: "I'm Mike"`
// Then add complexity
const complexPrompt = `Extract contact info:
Text: "Hi, I'm John Smith, call me at 555-1234"
Contact: {"name": "John Smith", "phone": "555-1234"}
Text: "Sarah Johnson here, email me at sarah@email.com"
Contact: {"name": "Sarah Johnson", "email": "sarah@email.com"}
Text: "Mike Chen, 555-9876, mike@company.com"`
Next Steps
- AI Elements - UI components for building AI interfaces
- AI Agents - Build intelligent agents with tools and loops
- AI SDK Blocks - Pre-built AI applications and patterns
Examples
Explore our collection of few-shot prompting implementations:
- Text Classification Block - Classify text with examples
- Data Extraction Block - Extract structured data from text
- Code Generation Block - Generate code with style examples
On This Page
What is Few-Shot Prompting?Basic Example: Text ClassificationStructured Data ExtractionCode GenerationWriting Style AdaptationBest Practices1. Choose Good Examples2. Use Consistent Formatting3. Include Edge Cases4. Test Your ExamplesCommon PatternsPattern 1: Input → OutputPattern 2: Question → AnswerPattern 3: Context → ActionAdvanced TechniquesChain of ThoughtRole-Based PromptingIntegration with AI SDKUsing Few-Shot Prompts in AgentsDynamic Few-Shot ExamplesTroubleshootingProblem: AI ignores examplesProblem: AI produces inconsistent outputProblem: Examples are too complexNext StepsExamples