Skip to main content
Few-shot learning is a powerful prompting technique where you provide examples of the desired input-output pattern before making your actual request. This approach dramatically improves response quality, consistency, and accuracy by showing the AI exactly what you want.

What is few-shot prompting?

Few-shot prompting involves including one or more examples in your prompt to demonstrate the pattern, style, format, or approach you want the AI to follow.
The term “few-shot” refers to the number of examples:
  • Zero-shot: No examples (just instructions)
  • One-shot: One example
  • Few-shot: Multiple examples (typically 2-5)
  • Many-shot: Many examples (6+)

Why few-shot prompting works

Examples are often more precise than descriptions. Consider these approaches:
Convert this function name to kebab-case.

Function: getUserProfileData
Response may vary in interpretation.
Few-shot prompting is especially effective for tasks involving specific formats, consistent styling, or domain-specific conventions.

Basic few-shot structure

Single example (one-shot)

Use one example for simple pattern demonstration:
Transform this error message to be user-friendly.

Example:
Technical: "ERR_CONN_REFUSED: Connection refused at port 5432"
User-friendly: "We're having trouble connecting to our database. Please try again in a moment."

Now transform:
Technical: "TypeError: Cannot read property 'id' of undefined at line 42"
User-friendly:

Multiple examples (few-shot)

Use 2-5 examples for complex patterns:
Generate API endpoint documentation following this pattern:

Example 1:
Endpoint: POST /api/users
Description: Creates a new user account with the provided details.
Authentication: Required (Bearer token)
Rate limit: 10 requests per minute

Example 2:
Endpoint: GET /api/users/:id
Description: Retrieves detailed information for a specific user by their ID.
Authentication: Required (Bearer token)
Rate limit: 100 requests per minute

Example 3:
Endpoint: DELETE /api/users/:id
Description: Permanently deletes a user account and all associated data.
Authentication: Required (Bearer token + Admin role)
Rate limit: 5 requests per minute

Now document this endpoint:
Endpoint: PATCH /api/users/:id/preferences
[Provide details about updating user preferences]

Few-shot prompting by use case

Code generation

Demonstrate coding style, structure, and conventions:
Write React hooks following these examples:

Example 1:
```javascript
export const useCounter = (initialValue = 0) => {
  const [count, setCount] = useState(initialValue);
  
  const increment = useCallback(() => setCount(c => c + 1), []);
  const decrement = useCallback(() => setCount(c => c - 1), []);
  const reset = useCallback(() => setCount(initialValue), [initialValue]);
  
  return { count, increment, decrement, reset };
};

Data transformation

Show the exact transformation pattern:
Transform these database records into API responses:

Example 1:
Database record:
{
  user_id: 123,
  first_name: "John",
  last_name: "Doe",
  email_address: "[email protected]",
  created_at: "2024-01-15T10:30:00Z",
  is_active: 1
}

API response:
{
  id: 123,
  name: "John Doe",
  email: "[email protected]",
  createdAt: "2024-01-15T10:30:00Z",
  status: "active"
}

Example 2:
Database record:
{
  user_id: 456,
  first_name: "Jane",
  last_name: "Smith",
  email_address: "[email protected]",
  created_at: "2024-02-20T14:45:00Z",
  is_active: 0
}

API response:
{
  id: 456,
  name: "Jane Smith",
  email: "[email protected]",
  createdAt: "2024-02-20T14:45:00Z",
  status: "inactive"
}

Now transform this record:
{
  user_id: 789,
  first_name: "Bob",
  last_name: "Johnson",
  email_address: "[email protected]",
  created_at: "2024-03-10T09:15:00Z",
  is_active: 1
}

Content writing

Demonstrate tone, style, and structure:
Write product feature announcements in this style:

Example 1:
Feature: Dark Mode
We've added dark mode to reduce eye strain during late-night coding sessions. Toggle between light and dark themes in your settings, and your preference will sync across all your devices. Your eyes (and sleep schedule) will thank you.

Example 2:
Feature: Collaborative Editing
Work together in real-time with your team. See cursor positions, edits, and comments as they happen. No more "did you get my latest changes?" messages cluttering your Slack channels.

Example 3:
Feature: Smart Search
Find anything instantly with our new semantic search. Type natural language queries like "authentication bug from last week" instead of hunting through titles and tags. It's like having a conversation with your project history.

Now write an announcement for:
Feature: Auto-save with Version History

Test case generation

Show test structure and coverage patterns:
Write test cases following these examples:

Example 1:
describe('calculateDiscount', () => {
  it('should apply 10% discount for orders over $100', () => {
    const result = calculateDiscount(150);
    expect(result).toBe(135);
  });
  
  it('should apply no discount for orders under $100', () => {
    const result = calculateDiscount(75);
    expect(result).toBe(75);
  });
  
  it('should handle zero amount', () => {
    const result = calculateDiscount(0);
    expect(result).toBe(0);
  });
});

Example 2:
describe('validateEmail', () => {
  it('should return true for valid email addresses', () => {
    expect(validateEmail('[email protected]')).toBe(true);
    expect(validateEmail('[email protected]')).toBe(true);
  });
  
  it('should return false for invalid email addresses', () => {
    expect(validateEmail('invalid')).toBe(false);
    expect(validateEmail('@example.com')).toBe(false);
  });
  
  it('should return false for empty string', () => {
    expect(validateEmail('')).toBe(false);
  });
});

Now write tests for:
function calculateShipping(weight: number, distance: number): number

Advanced few-shot techniques

Progressive complexity

Start with simple examples and increase complexity:
Extract structured data from text following this pattern:

Example 1 (Simple):
Text: "Meeting with John tomorrow at 2pm"
Output:
{
  "type": "meeting",
  "participants": ["John"],
  "date": "tomorrow",
  "time": "14:00"
}

Example 2 (Multiple participants):
Text: "Team standup with Sarah, Mike, and Lisa on Friday at 9am"
Output:
{
  "type": "meeting",
  "participants": ["Sarah", "Mike", "Lisa"],
  "date": "Friday",
  "time": "09:00"
}

Example 3 (With location):
Text: "Product review meeting with the design team next Monday at 3pm in Conference Room B"
Output:
{
  "type": "meeting",
  "participants": ["design team"],
  "date": "next Monday",
  "time": "15:00",
  "location": "Conference Room B"
}

Now extract from:
Text: "Quarterly planning session with all department heads on March 15th at 10:30am via Zoom"

Contrastive examples

Show both correct and incorrect patterns:
Refactor code to use proper TypeScript types:

❌ Incorrect:
function processUser(user: any) {
  return user.name.toUpperCase();
}

✅ Correct:
interface User {
  name: string;
  email: string;
}

function processUser(user: User): string {
  return user.name.toUpperCase();
}

❌ Incorrect:
const config: any = {
  apiUrl: process.env.API_URL,
  timeout: process.env.TIMEOUT
};

✅ Correct:
interface Config {
  apiUrl: string;
  timeout: number;
}

const config: Config = {
  apiUrl: process.env.API_URL || 'https://api.example.com',
  timeout: parseInt(process.env.TIMEOUT || '5000', 10)
};

Now refactor this code:
function fetchData(endpoint: any, options: any) {
  return fetch(endpoint, options);
}

Domain-specific examples

Provide examples using domain terminology:
Generate SQL queries for an e-commerce database:

Example 1 - Find high-value customers:
Query: "customers who spent over $1000 in the last 6 months"
SQL:
SELECT 
  c.customer_id,
  c.email,
  SUM(o.total_amount) as total_spent
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)
GROUP BY c.customer_id, c.email
HAVING SUM(o.total_amount) > 1000
ORDER BY total_spent DESC;

Example 2 - Popular products:
Query: "top 10 products by units sold this month"
SQL:
SELECT 
  p.product_id,
  p.product_name,
  SUM(oi.quantity) as units_sold
FROM products p
JOIN order_items oi ON p.product_id = oi.product_id
JOIN orders o ON oi.order_id = o.order_id
WHERE MONTH(o.order_date) = MONTH(CURRENT_DATE)
  AND YEAR(o.order_date) = YEAR(CURRENT_DATE)
GROUP BY p.product_id, p.product_name
ORDER BY units_sold DESC
LIMIT 10;

Now generate SQL for:
Query: "customers who abandoned carts in the last 24 hours with cart value over $50"

Few-shot with structured prompts

Combine few-shot learning with structured techniques:
<task>Generate API error responses</task>

<examples>
Example 1:
Input: User not found
Output:
{
  "error": {
    "code": "USER_NOT_FOUND",
    "message": "The requested user does not exist.",
    "statusCode": 404,
    "details": {
      "userId": "{{userId}}"
    }
  }
}

Example 2:
Input: Invalid authentication token
Output:
{
  "error": {
    "code": "INVALID_TOKEN",
    "message": "The authentication token is invalid or expired.",
    "statusCode": 401,
    "details": {
      "tokenType": "Bearer"
    }
  }
}

Example 3:
Input: Rate limit exceeded
Output:
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests. Please try again later.",
    "statusCode": 429,
    "details": {
      "limit": 100,
      "window": "1 hour",
      "retryAfter": 3600
    }
  }
}
</examples>

<your_task>
Generate error responses for:
1. Insufficient permissions
2. Resource conflict
3. Validation failure
</your_task>

Optimizing example quality

1

Use diverse examples

Cover different variations and edge cases in your examples to show the full range of expected patterns.
2

Keep examples realistic

Use realistic, production-quality examples rather than overly simplified ones.
3

Annotate when helpful

Add comments or explanations to examples when the pattern might not be obvious:
Example:
Input: calculateTotalPrice(items)
Output: items.reduce((sum, item) => sum + item.price * item.quantity, 0)
// Note: Always handle quantity multiplier and use reduce for summing arrays
4

Balance quantity vs. quality

2-3 high-quality examples usually work better than 10 mediocre ones. More examples aren’t always better.

When to use few-shot prompting

  • Generating code in a specific style or framework
  • Data transformation with consistent formatting
  • Content creation matching a particular tone
  • Test case generation with consistent structure
  • API responses following a standard format
  • Documentation with specific templates
  • Naming conventions and style guides
  • Well-known standard formats (JSON, CSV)
  • Common programming tasks with clear conventions
  • Simple, straightforward requests
  • When zero-shot instructions are sufficient

Token efficiency considerations

Examples consume tokens. Balance thoroughness with efficiency:
Token management tips:
  • Use 2-3 examples for most cases (sweet spot for quality vs. tokens)
  • Reference documentation or specifications for very complex patterns rather than including many examples
  • Consider creating an assistant with embedded examples for repeated use
  • See tokens and limits for more optimization strategies

Combining with other techniques

Few-shot prompting works well with other approaches:
Solve these debugging problems step by step:

Example 1:
Bug: "React component not re-rendering when state changes"

Analysis:
1. Check if state is being mutated directly (mutation won't trigger re-render)
2. Verify useState is being used correctly
3. Confirm component isn't memoized incorrectly

Solution: Replace `items.push(newItem)` with `setItems([...items, newItem])`
Explanation: Direct array mutation doesn't trigger React re-renders. Use immutable updates.

Example 2:
Bug: "API returns 401 but user is logged in"

Analysis:
1. Check if token is being sent in request
2. Verify token hasn't expired
3. Confirm token is in correct format

Solution: Include token in Authorization header: `Authorization: Bearer ${token}`
Explanation: Token must be sent with each API request using proper header format.

Now debug:
Bug: "Form submission triggers twice on button click"

Saving and reusing examples

Make few-shot patterns reusable:
  1. Custom instructions: Add frequently used examples to custom instructions
  2. Assistants: Create specialized assistants with embedded examples for specific tasks
  3. Prompt library: Maintain a collection of effective few-shot prompts

Next steps