> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zerotwo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Few-Shot Learning and Examples

> Improve AI responses by providing demonstrations and examples in your prompts

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.

<Info>
  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+)
</Info>

## Why few-shot prompting works

Examples are often more precise than descriptions. Consider these approaches:

<Tabs>
  <Tab title="Zero-shot (instructions only)">
    ```text theme={null}
    Convert this function name to kebab-case.

    Function: getUserProfileData
    ```

    Response may vary in interpretation.
  </Tab>

  <Tab title="Few-shot (with examples)">
    ```text theme={null}
    Convert these function names to kebab-case:

    Example 1:
    Input: getUserProfileData
    Output: get-user-profile-data

    Example 2:
    Input: calculateTotalAmount
    Output: calculate-total-amount

    Example 3:
    Input: validateEmailAddress
    Output: validate-email-address

    Now convert:
    Input: fetchOrderHistoryById
    Output:
    ```

    Response will follow the demonstrated pattern exactly.
  </Tab>
</Tabs>

<Tip>
  Few-shot prompting is especially effective for tasks involving specific formats, consistent styling, or domain-specific conventions.
</Tip>

## Basic few-shot structure

### Single example (one-shot)

Use one example for simple pattern demonstration:

```text theme={null}
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:

```text theme={null}
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:

<CodeGroup>
  ````text Function style theme={null}
  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 };
  };
  ````

  Example 2:

  ```javascript theme={null}
  export const useToggle = (initialState = false) => {
    const [state, setState] = useState(initialState);
    
    const toggle = useCallback(() => setState(s => !s), []);
    const setTrue = useCallback(() => setState(true), []);
    const setFalse = useCallback(() => setState(false), []);
    
    return { state, toggle, setTrue, setFalse };
  };
  ```

  Now create a useLocalStorage hook that follows the same pattern.
  \`\`\`

  ````text Error handling theme={null}
  Handle errors following these examples:

  Example 1:
  ```typescript
  try {
    const data = await fetchUserData(userId);
    return { success: true, data };
  } catch (error) {
    if (error instanceof NetworkError) {
      return { 
        success: false, 
        error: 'Unable to connect. Check your internet connection.' 
      };
    }
    throw error;
  }
  ````

  Example 2:

  ```typescript theme={null}
  try {
    const result = await processPayment(amount);
    return { success: true, transactionId: result.id };
  } catch (error) {
    if (error instanceof PaymentError) {
      return {
        success: false,
        error: 'Payment processing failed. Please try a different payment method.'
      };
    }
    throw error;
  }
  ```

  Now write error handling for a file upload function.
  \`\`\`
</CodeGroup>

### Data transformation

Show the exact transformation pattern:

```text theme={null}
Transform these database records into API responses:

Example 1:
Database record:
{
  user_id: 123,
  first_name: "John",
  last_name: "Doe",
  email_address: "john@example.com",
  created_at: "2024-01-15T10:30:00Z",
  is_active: 1
}

API response:
{
  id: 123,
  name: "John Doe",
  email: "john@example.com",
  createdAt: "2024-01-15T10:30:00Z",
  status: "active"
}

Example 2:
Database record:
{
  user_id: 456,
  first_name: "Jane",
  last_name: "Smith",
  email_address: "jane@example.com",
  created_at: "2024-02-20T14:45:00Z",
  is_active: 0
}

API response:
{
  id: 456,
  name: "Jane Smith",
  email: "jane@example.com",
  createdAt: "2024-02-20T14:45:00Z",
  status: "inactive"
}

Now transform this record:
{
  user_id: 789,
  first_name: "Bob",
  last_name: "Johnson",
  email_address: "bob@example.com",
  created_at: "2024-03-10T09:15:00Z",
  is_active: 1
}
```

### Content writing

Demonstrate tone, style, and structure:

```text theme={null}
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:

```typescript theme={null}
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('user@example.com')).toBe(true);
    expect(validateEmail('user.name@example.co.uk')).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:

```text theme={null}
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:

```text theme={null}
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:

```text theme={null}
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](/prompts/structured-techniques):

```xml theme={null}
<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

<Steps>
  <Step title="Use diverse examples">
    Cover different variations and edge cases in your examples to show the full range of expected patterns.
  </Step>

  <Step title="Keep examples realistic">
    Use realistic, production-quality examples rather than overly simplified ones.
  </Step>

  <Step title="Annotate when helpful">
    Add comments or explanations to examples when the pattern might not be obvious:

    ```text theme={null}
    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
    ```
  </Step>

  <Step title="Balance quantity vs. quality">
    2-3 high-quality examples usually work better than 10 mediocre ones. More examples aren't always better.
  </Step>
</Steps>

## When to use few-shot prompting

<AccordionGroup>
  <Accordion title="✅ Ideal use cases">
    * 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
  </Accordion>

  <Accordion title="⚠️ May not be necessary">
    * Well-known standard formats (JSON, CSV)
    * Common programming tasks with clear conventions
    * Simple, straightforward requests
    * When zero-shot instructions are sufficient
  </Accordion>
</AccordionGroup>

## Token efficiency considerations

Examples consume tokens. Balance thoroughness with efficiency:

<Warning>
  **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](/assistants/create) with embedded examples for repeated use
  * See [tokens and limits](/prompts/tokens-and-limits) for more optimization strategies
</Warning>

## Combining with other techniques

Few-shot prompting works well with other approaches:

<Tabs>
  <Tab title="Few-shot + Chain-of-thought">
    ```text theme={null}
    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"
    ```
  </Tab>

  <Tab title="Few-shot + Role-based">
    ````text theme={null}
    As a senior code reviewer, provide code review feedback:

    Example 1:
    Code: `if (user.isActive == true)`
    Feedback: ⚠️ **Unnecessary comparison** - `isActive` is already boolean. Use `if (user.isActive)` instead.
    Impact: Minor - readability
    Suggestion: `if (user.isActive)`

    Example 2:
    Code: `const data = JSON.parse(response);`
    Feedback: 🔴 **Missing error handling** - JSON.parse can throw. Wrap in try-catch.
    Impact: High - potential runtime error
    Suggestion:
    ```javascript
    try {
      const data = JSON.parse(response);
    } catch (error) {
      console.error('Invalid JSON:', error);
    }
    ````

    Now review this code:

    ```javascript theme={null}
    async function updateUser(id, data) {
      await fetch(`/api/users/${id}`, {
        method: 'POST',
        body: data
      });
    }
    ```

    \`\`\`
  </Tab>
</Tabs>

## Saving and reusing examples

<Tip>
  **Make few-shot patterns reusable:**

  1. **Custom instructions**: Add frequently used examples to [custom instructions](/chat/custom-instructions)
  2. **Assistants**: Create [specialized assistants](/assistants/create) with embedded examples for specific tasks
  3. **Prompt library**: Maintain a collection of effective few-shot prompts
</Tip>

## Next steps

<CardGroup cols={2}>
  <Card title="Custom instructions" icon="sliders" href="/prompts/custom-instructions-patterns">
    Save few-shot patterns for reuse
  </Card>

  <Card title="Structured techniques" icon="sitemap" href="/prompts/structured-techniques">
    Combine with structured prompting
  </Card>

  <Card title="Create assistants" icon="robot" href="/assistants/create">
    Build assistants with embedded examples
  </Card>

  <Card title="Token optimization" icon="gauge" href="/prompts/tokens-and-limits">
    Manage example token usage
  </Card>
</CardGroup>
