Books/Prompt Engineering Essentials/Techniques: Zero-Shot, Few-Shot, and Chain of Thought

    Techniques: Zero-Shot, Few-Shot, and Chain of Thought

    Techniques: Zero-Shot, Few-Shot, and Chain of Thought

    Now that you understand the anatomy of a good prompt, let's look at the three fundamental techniques for how you structure the actual request. These are the building blocks that professional prompt engineers use every day.

    Technique 1: Zero-Shot Prompting

    Zero-shot means you give the AI a task with no examples. You just ask, and the AI uses its training to figure out what you want.

    When to Use It

    • Simple, well-defined tasks
    • When the task is common enough that AI already understands it
    • Quick questions and straightforward code generation

    Examples

    Translate the following English text to Spanish:
    "The meeting has been rescheduled to 3 PM tomorrow."
    
    Write a TypeScript function that reverses a string without using
    the built-in reverse() method.
    
    Classify the following customer review as "positive," "negative,"
    or "neutral":
    "The product arrived on time but the packaging was damaged.
    The item itself works fine though."
    

    Zero-shot works well because these are tasks AI has seen millions of times during training. It knows what "translate," "write a function," and "classify" mean without needing examples.

    Zero-Shot with an API Call

    const response = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        model: "gpt-4o",
        messages: [
          {
            role: "user",
            content: "Classify this support ticket as 'bug', 'feature-request', or 'question': 'The login button does not respond when I click it on Safari.'"
          }
        ],
      }),
    });

    Limitations

    Zero-shot can fail when:

    • The task requires a specific output format the AI hasn't seen
    • The task is ambiguous or domain-specific
    • You need consistent, structured output across many requests

    That's where few-shot comes in.

    Technique 2: Few-Shot Prompting

    Few-shot means you provide examples of input-output pairs before giving the actual task. The AI learns the pattern from your examples and applies it.

    When to Use It

    • You need a specific output format
    • The task is unusual or domain-specific
    • You want consistent results across multiple inputs
    • Zero-shot isn't producing the right style or format

    Examples

    Classification with examples:

    Classify each customer message into a category.
    
    Message: "I can't log into my account"
    Category: account-access
    
    Message: "Can you add dark mode to the app?"
    Category: feature-request
    
    Message: "The app crashes when I upload a photo"
    Category: bug-report
    
    Message: "How do I export my data as CSV?"
    Category:
    

    The AI sees the pattern (Message -> Category) and correctly outputs how-to-question or feature-request depending on its judgment, following the exact format you established.

    Code transformation with examples:

    Convert JavaScript objects to TypeScript interfaces.
    
    Input:
    const user = { name: "Alice", age: 30, isAdmin: true };
    
    Output:
    interface User {
      name: string;
      age: number;
      isAdmin: boolean;
    }
    
    Input:
    const product = { id: 1, title: "Widget", price: 9.99, tags: ["sale", "new"] };
    
    Output:
    interface Product {
      id: number;
      title: string;
      price: number;
      tags: string[];
    }
    
    Input:
    const order = { orderId: "abc123", items: 3, total: 29.97, shipped: false, address: { street: "123 Main St", city: "Springfield" } };
    
    Output:
    

    Data extraction with examples:

    Extract structured data from these product descriptions.
    
    Description: "Apple MacBook Pro 14-inch, M3 Pro chip, 18GB RAM, 512GB SSD, Space Black"
    Result: { "brand": "Apple", "product": "MacBook Pro", "screen": "14-inch", "processor": "M3 Pro", "ram": "18GB", "storage": "512GB SSD", "color": "Space Black" }
    
    Description: "Samsung Galaxy S24 Ultra, Snapdragon 8 Gen 3, 12GB RAM, 256GB, Titanium Gray"
    Result: { "brand": "Samsung", "product": "Galaxy S24 Ultra", "processor": "Snapdragon 8 Gen 3", "ram": "12GB", "storage": "256GB", "color": "Titanium Gray" }
    
    Description: "Sony WH-1000XM5, wireless noise-canceling headphones, 30-hour battery, silver"
    Result:
    

    Few-Shot with an API Call

    const response = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        model: "gpt-4o",
        messages: [
          {
            role: "system",
            content: "You extract structured data from product descriptions."
          },
          {
            role: "user",
            content: 'Extract data: "Apple MacBook Pro 14-inch, M3 Pro, 18GB RAM, 512GB"'
          },
          {
            role: "assistant",
            content: '{ "brand": "Apple", "product": "MacBook Pro", "screen": "14-inch", "processor": "M3 Pro", "ram": "18GB", "storage": "512GB" }'
          },
          {
            role: "user",
            content: 'Extract data: "Dell XPS 15, Intel i9-13900H, 32GB RAM, 1TB SSD, OLED"'
          }
        ],
      }),
    });

    Notice how the examples are encoded as alternating user/assistant messages. This is the standard pattern for few-shot prompting in chat-based APIs.

    How Many Examples?

    • 1-2 examples — Usually enough for simple format matching
    • 3-5 examples — Good for classification or transformation tasks
    • 5+ examples — For complex or nuanced tasks where edge cases matter

    More examples give the AI a clearer pattern, but they also use more tokens (and cost more). Find the minimum number that produces consistent results.

    Technique 3: Chain-of-Thought Prompting

    Chain-of-thought (CoT) prompting asks the AI to think step by step before giving its final answer. This dramatically improves accuracy on tasks that require reasoning, math, logic, or multi-step problem solving.

    When to Use It

    • Math and logic problems
    • Complex code debugging
    • Architecture and design decisions
    • Any task where the AI needs to reason through multiple steps
    • When zero-shot gives wrong answers on reasoning tasks

    The Simple Version

    Just add "Think step by step" or "Let's work through this step by step" to your prompt:

    A store sells notebooks for $4 each and pens for $2 each.
    Sarah buys 3 notebooks and 5 pens. She pays with a $50 bill.
    How much change does she receive?
    
    Think step by step.
    

    AI response with CoT:

    Let me work through this step by step:
    
    1. Cost of notebooks: 3 x $4 = $12
    2. Cost of pens: 5 x $2 = $10
    3. Total cost: $12 + $10 = $22
    4. Change from $50: $50 - $22 = $28
    
    Sarah receives $28 in change.
    

    Without "think step by step," AI models sometimes jump to wrong answers on math problems. With it, they break the problem down and get it right.

    Chain-of-Thought for Code Debugging

    This React component is re-rendering infinitely. Analyze the code
    step by step to identify the cause:
    
    const UserProfile = ({ userId }) => {
      const [user, setUser] = useState(null);
    
      useEffect(() => {
        fetch(`/api/users/${userId}`)
          .then(res => res.json())
          .then(data => setUser(data));
      });
    
      return <div>{user?.name}</div>;
    };
    
    Walk through the React rendering lifecycle step by step and
    explain why the infinite loop occurs. Then provide the fix.
    

    Chain-of-Thought for Architecture Decisions

    I need to decide between these approaches for real-time notifications
    in my app:
    A) Firestore onSnapshot listeners
    B) WebSocket server
    C) Server-Sent Events (SSE)
    
    My app: React frontend, Firebase backend, ~1000 concurrent users,
    notifications are text-only and arrive 5-10 per user per day.
    
    Think through each option step by step, considering:
    1. Implementation complexity
    2. Cost at my scale
    3. Reliability
    4. How well it fits my existing stack
    
    Then give your recommendation with reasoning.
    

    Chain-of-Thought with an API Call

    const response = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        model: "gpt-4o",
        messages: [
          {
            role: "system",
            content: "You are a software architect. When analyzing problems, always think step by step and show your reasoning before giving a recommendation."
          },
          {
            role: "user",
            content: "Should I use a SQL or NoSQL database for a social media app with user profiles, posts, comments, likes, and a follower system? Think step by step."
          }
        ],
      }),
    });

    Combining Techniques

    The real power comes from combining these techniques:

    Few-shot + Chain-of-thought:

    Analyze each code snippet for security vulnerabilities.
    Think step by step about what could go wrong.
    
    Code: app.get("/user", (req, res) => { const user = db.query("SELECT * FROM users WHERE id = " + req.query.id); res.json(user); });
    Analysis:
    1. The query concatenates user input directly into SQL
    2. This allows SQL injection attacks
    3. An attacker could pass id=1 OR 1=1 to dump all users
    Vulnerability: SQL Injection
    Fix: Use parameterized queries: db.query("SELECT * FROM users WHERE id = $1", [req.query.id])
    
    Code: app.post("/login", (req, res) => { const { password } = req.body; if (password === "admin123") { res.json({ token: jwt.sign({ role: "admin" }, "secret") }); } });
    Analysis:
    

    When to Use Each Technique

    TechniqueBest ForToken CostAccuracy
    Zero-shotSimple, common tasksLowGood for simple tasks
    Few-shotFormat matching, classificationMediumHigh consistency
    Chain-of-thoughtReasoning, math, debuggingHigherBest for complex tasks
    Few-shot + CoTComplex tasks needing both format and reasoningHighestHighest

    Key Takeaways

    1. Start with zero-shot. If the output is good enough, you're done
    2. Add examples (few-shot) when you need consistent formatting or the AI misunderstands your intent
    3. Add "think step by step" (CoT) when the task requires reasoning or when zero-shot gives wrong answers
    4. Combine techniques for the most demanding tasks

    Try it now: Take a task where AI gave you a mediocre answer. Try each technique — zero-shot, few-shot with 2-3 examples, and chain-of-thought. Compare the results and notice which technique produced the best output for your specific task.


    🌐 www.genai-mentor.ai