Few-Shot Prompting

La Lakshmi Priya Updated 05 Nov 2026
10 min read ·Lesson 26 of 140

What Is Few-Shot Prompting? Few-shot prompting means including a small number of examples in the prompt, each showing an input and its correct output, before giving the model the actual input to process.

In simple terms: instead of only describing what you want, you show it a few times, and the model follows the pattern.

As introduced in Lesson 16, each example is called a shot:

Technique Examples in the Prompt Zero-shot None One-shot One Few-shot Several, typically 2 to 10 Example Convert each course name into a URL slug.

Course: Python for Absolute Beginners Slug: python-for-absolute-beginners

Course: Django REST APIs & Authentication Slug: django-rest-apis-authentication

Course: C++ Data Structures (2026 Edition) Slug: cpp-data-structures-2026-edition

Course: Node.js & Express: Build Real APIs Slug: Expected output:

nodejs-express-build-real-apis Example Explanation The examples teach several rules that were never written down:

Use lowercase letters. Replace spaces with hyphens. Remove symbols such as &, :, and parentheses. Convert C++ to cpp rather than dropping it. Keep numbers. From the last example alone, the model also learns how to handle unusual cases. For the new input, it applies the same pattern: Node.js loses its dot, & and : are removed, and everything is lowercase. Writing all of these rules in words would take much longer and could still miss cases.

Why Few-Shot Prompting Works In-Context Learning The ability of a language model to pick up a task from examples inside the prompt is called in-context learning. It was demonstrated prominently in the 2020 research paper that introduced GPT-3, titled "Language Models are Few-Shot Learners", which showed that large models could perform new tasks from a handful of examples without additional training.

The important point is that the model is not retrained. Its internal parameters do not change. The examples work entirely through the mechanism you learned in Lesson 2: they become part of the context, and the model predicts output that continues the pattern they establish.

What Examples Communicate Examples carry information that is often hard to state in instructions:

What Examples Show Why Words Struggle Exact format Separators, capitalization, spacing, and order need many rules Label meaning Where one category ends and another begins Style and tone Sentence length, vocabulary, humor, and punctuation Level of detail How long and how deep an answer should be Handling of special cases What to do with symbols, missing values, or unusual inputs This is why few-shot prompting directly addresses several of the zero-shot limitations from Lesson 24: ambiguous boundaries, custom formats, and style matching.

What Examples Cannot Do Examples do not give the model new facts. If the task requires knowledge the model lacks, such as your company's policies, examples of unrelated questions and answers will not help. Provide the facts as context instead (Lesson 19).

The Structure of a Few-Shot Prompt [Instruction] What the task is (optional but recommended) [Example 1] Input → Output [Example 2] Input → Output [Example 3] Input → Output [Actual input] The new input [Output cue] Where the model should begin Instructions Plus Examples Examples alone can work, but combining them with a short instruction is usually more reliable. The instruction states the intent; the examples show the details.

Examples only:

Great course! → Positive Too expensive for what it offers. → Negative The model must infer that the task is sentiment classification, and it does not know what other labels exist.

Instruction plus examples:

Classify the sentiment of each review as Positive, Negative, or Neutral.

Review: Great course! Sentiment: Positive

Review: Too expensive for what it offers. Sentiment: Negative

Review: It covers the basics. Sentiment: Neutral

Review: The projects were challenging and really useful. Sentiment: The instruction defines the full label set, and the examples show how each label is applied, including one example for every label.

A Complete Example: Writing in a Specific Style Style is one of the clearest uses of few-shot prompting.

Zero-Shot Attempt Write a short, friendly push notification reminding a student to continue the Django course. Typical output:

Hi there! 👋 Don't forget to continue your Django course today. Every step brings you closer to your goals. Keep up the great work! 🚀 This is acceptable, but generic.

Few-Shot Version Write a push notification for the given course, in the same style as the examples.

Course: Python Basics Notification: Your Python loops are waiting. 7 minutes to finish Lesson 4?

Course: React Fundamentals Notification: useState misses you. Lesson 6 takes about 10 minutes.

Course: SQL for Beginners Notification: One JOIN away from finishing Module 2. Ready?

Course: Django Web Development Notification: Possible output:

Your models.py is waiting. Lesson 5 takes about 8 minutes. Example Explanation The examples establish a style that would be hard to describe precisely:

A short, playful reference to a concept from that technology (loops, useState, JOIN) A specific lesson or module A small time estimate or a short question No emojis, no exclamation marks, and no motivational phrases The output follows all of these patterns for a new course. Note that the lesson number and time ("Lesson 5", "8 minutes") were invented by the model. In a real application, you would insert the actual next lesson and its duration into the input so the notification is accurate.

Few-Shot Prompting Through an API When calling a model from code, examples can be provided in two common ways.

Method 1: Examples Inside the Instructions All examples are written as text in the system or developer instructions.

Method 2: Examples as Conversation Turns Each example is written as a pair of messages: a user message containing the example input, followed by an assistant message containing the correct output. The model sees a "conversation" in which it already answered correctly several times, and continues the pattern.

Requirements: pip install openai and an OPENAI_API_KEY environment variable.

from openai import OpenAI

client = OpenAI() MODEL = "gpt-5.4" # Replace with a model available in your account

INSTRUCTIONS = ( "Convert the course name into a URL slug: lowercase, words separated by " "hyphens, symbols removed. Reply with the slug only." )

EXAMPLES = [ ("Python for Absolute Beginners", "python-for-absolute-beginners"), ("Django REST APIs & Authentication", "django-rest-apis-authentication"), ("C++ Data Structures (2026 Edition)", "cpp-data-structures-2026-edition"), ]

def build_messages(course_name: str) -> list[dict]: messages = [] for example_input, example_output in EXAMPLES: messages.append({"role": "user", "content": example_input}) messages.append({"role": "assistant", "content": example_output}) messages.append({"role": "user", "content": course_name}) return messages

def make_slug(course_name: str) -> str: response = client.responses.create( model=MODEL, instructions=INSTRUCTIONS, input=build_messages(course_name), ) return response.output_text.strip()

print(make_slug("Node.js & Express: Build Real APIs")) Possible output:

nodejs-express-build-real-apis Code Explanation INSTRUCTIONS States the task and the basic rules. The examples then show details the rules do not cover, such as how to handle C++.

EXAMPLES A list of (input, output) pairs. Keeping examples as data makes them easy to add, remove, and test.

build_messages()

Converts each example into a user message and an assistant message. Appends the real input as the final user message. The resulting list is passed to input. As shown in Lesson 2, the Responses API accepts a list of messages with roles. Why conversation turns work well The model has been trained on conversations, so a history where the "assistant" consistently replied with only a slug strongly suggests that the next reply should also be only a slug. This reduces extra text such as "Here is your slug:".

Which Method to Choose Method Advantages Considerations Examples in instructions Simple; everything in one place; easy to read Examples and instructions share one block Examples as conversation turns Strong signal about the exact form of replies More code; examples look like real conversation history Both methods are widely used. Choose the one that tests best for your task.

Note: For slug generation specifically, a deterministic function in code (such as Django's slugify) is more reliable than a model, because it is a fixed rule-based transformation. The example is used here because its patterns are easy to see. In practice, use few-shot prompting for tasks that require language understanding, and use code for tasks that can be expressed as exact rules.

How Many Examples? There is no universal number. The right count depends on the task.

Situation Typical Number Showing a simple format 1 to 2 Showing a style 3 to 5 varied examples Classification At least 1 per label, more for confusing labels Complex extraction with many edge cases 3 to 6 covering different cases Trade-Offs More examples usually improve consistency up to a point, then give diminishing returns. Every example adds tokens to every request (Lesson 23). Many similar examples add cost without teaching anything new. Start with a small number, measure results on a test set, and add examples only when they fix observed failures. Lesson 27 compares one-shot and few-shot in detail, and Lesson 28 explains how to choose examples.

When to Use Few-Shot Prompting Use Few-Shot When... Example The format is unusual or strict Custom text formats, specific JSON shapes Labels have subtle boundaries "Mild complaint" vs "neutral feedback" A specific style or voice is required Brand messages, notifications Zero-shot results are inconsistent after improvements Persistent borderline errors Rules are easier to show than to explain Slug rules, naming conventions Do Not Rely on Few-Shot When... Use Instead The model lacks facts Context or RAG The task needs exact computation Code Zero-shot already meets your criteria Keep zero-shot Examples would contain sensitive data Anonymized or synthetic examples Common Mistakes Mistake 1: Examples That Contradict the Instructions What it is: The instruction says "Reply in one sentence", but the examples show three-sentence answers.

Why it happens: Instructions and examples are edited separately.

What it causes: The model often follows the examples rather than the instructions, because examples are a strong signal.

How to fix it: Check that every example follows every instruction exactly.

Mistake 2: Incorrect Examples What it is: An example with a wrong label or a formatting error.

Why it happens: Examples are written quickly or copied from unreviewed data.

What it causes: The model learns the mistake and repeats it on similar inputs.

How to fix it: Review every example as carefully as production code.

Mistake 3: All Examples Look the Same What it is: Three examples that are all short, simple, and similar.

Why it happens: The first examples that come to mind are typical cases.

What it causes: The model has no guidance for long, unusual, or difficult inputs.

How to fix it: Choose varied examples, including at least one non-obvious case (Lesson 28).

Mistake 4: Unclear Separation Between Examples and the Real Input What it is: The real input is formatted differently from the examples, or it is unclear where the examples end.

Why it happens: Prompts are assembled without a consistent format.

What it causes: The model may treat an example as the real input, or fail to recognize the pattern.

How to fix it: Use identical labels and a consistent structure for examples and the real input (Lesson 29).

Best Practices Combine a short instruction with examples. The instruction states intent; the examples show details.

Make examples flawless. The model copies what you show, including mistakes.

Keep examples consistent with the instructions. When they conflict, examples often win.

Use varied examples. Show the range of inputs the prompt will meet.

Use the same structure for examples and the real input. The pattern must continue naturally.

Store examples as data in code. This makes them easy to review, test, and change.

Start with few examples and add only when needed. Measure the benefit against the token cost.

Try It Yourself Exercise 1: Zero-Shot vs Few-Shot Style Write a zero-shot prompt for a one-line course review response from an instructor. Then write three example responses in a distinctive style of your own and create a few-shot version. Generate responses to five new reviews with each version and compare how closely they match your style.

Exercise 2: Discover Hidden Rules Create a few-shot prompt that converts student names into email usernames using examples only, such as Priya Raman → priya.raman, R. Karthik → karthik.r. Test it on names with initials, three-part names, and names with special characters. Note which rules the model inferred correctly and which it guessed, then add an example to fix one wrong guess.

Exercise 3: Compare API Methods Using the slug example in this lesson, implement both methods: examples inside the instructions and examples as conversation turns. Run both on 10 new course names and compare the accuracy and how often extra text appears in the output.

0 Comments

Reviewed before they appear

No comments yet.

Prompt Engineering
Prompt Engineering Introduction How Large Language Models Respond to Prompts Prompting Basics Elements of an Effective Prompt Writing Clear Instructions for AI Models Adding Context to a Prompt Providing Input Data in Prompts Using Output Indicators and Response Formats Prompt Formatting: Questions, Instructions, and Templates General Tips for Designing Better Prompts Common Prompt Engineering Mistakes Iterative Prompt Design and Refinement Understanding Instruction, Context, Input, and Output How Specificity and Conciseness Affect Prompt Quality Breaking Large Tasks into Smaller Prompting Tasks Zero-Shot Prompting Zero-Shot Prompting Examples for Everyday Tasks Zero-Shot Text Classification Zero-Shot Question Answering Zero-Shot Summarization Zero-Shot Translation Zero-Shot Prompting for Information Extraction When to Use Zero-Shot Prompting Limitations of Zero-Shot Prompting Improving Weak Zero-Shot Prompts Few-Shot Prompting One-Shot Prompting vs Few-Shot Prompting Choosing Good Examples for Few-Shot Prompts Formatting Examples in Few-Shot Prompts Few-Shot Classification with Examples Few-Shot Prompting for Structured Output Few-Shot Prompting Zero-Shot vs Few-Shot Prompting Role Prompting and Persona Instructions Instruction-Based Prompting Task-Oriented Prompt Templates Using Delimiters to Separate Prompt Sections Prompt Templates with Variables Chain-of-Thought Prompting Zero-Shot Chain-of-Thought Prompting Few-Shot Chain-of-Thought Prompting Automatic Chain-of-Thought (Auto-CoT) When Chain-of-Thought Prompting Helps Limitations of Chain-of-Thought Prompting Self-Consistency Prompting Comparing Chain-of-Thought and Self-Consistency Tree of Thoughts (ToT) Prompting Exploring Multiple Solutions with Tree of Thoughts Least-to-Most Prompting Complexity-Based Prompting Maieutic Prompting Self-Consistency: Sampling Multiple Reasoning Paths Self-Consistency for Arithmetic and Logic Tasks Tree of Thoughts: Search, Evaluation, and Backtracking Meta Prompting Generate Knowledge Prompting Directional Stimulus Prompting Program-Aided Language Models (PAL) React: Reasoning and Acting with Language Models Reflexion: Improving Agents Through Feedback Prompt Chaining Designing Multi-Step Prompt Chains Decomposing Complex Tasks into Prompt Chains Automatic Prompt Engineer (APE) Active-Prompt: Selecting Useful Reasoning Examples Optimizing Prompts Systematically Prompt Iteration and Versioning Building Reusable Prompt Libraries Testing Prompt Variants Prompt Chaining Fundamentals Passing Outputs Between Prompt Steps Prompt Chains for Summarization and Extraction Validating Intermediate Results in a Prompt Chain Debugging a Multi-Step Prompt Workflow Graph Prompting Multimodal Chain-of-Thought Prompting Automatic Reasoning and Tool-Use (ART) Prompting for Tool Selection and Use Combining Prompting Techniques for Complex Tasks Prompts for Text Summarization Prompts for Information Extraction Prompts for Text Classification Prompts for Question Answering Prompts for Sentiment Analysis Prompts for Rewriting and Editing Prompts for Translation and Localization Prompts for Brainstorming and Creative Writing Prompts for Generating Structured Data Prompts for Explaining Technical Concepts Prompts for Generating and Reviewing Code Prompting for Code Generation Prompting for Code Explanation Prompting for Debugging and Error Analysis Prompting for Unit Test Generation Prompting for SQL Query Generation Prompting for API Documentation Prompting for Technical Documentation Using Prompting to Extract Requirements Creating JSON-Style Structured Responses with Prompts Designing Prompts for Repeatable Developer Workflows Retrieval-Augmented Generation (RAG) How Prompt Engineering Supports RAG Writing Prompts That Use Retrieved Context Grounding Answers in Provided Documents Handling Missing Information in RAG Prompts Reducing Unsupported Claims in Context-Based Answers Prompt Engineering for AI Agents ReAct Prompting for Tool-Using Agents Writing Tool Instructions for AI Agents Prompting Agents to Plan Multi-Step Tasks Prompting Agents to Observe Tool Results Using Feedback and Reflection in Agent Workflows Prompting for Agent Error Recovery How to Evaluate Prompt Quality Creating Test Cases for Prompts Comparing Prompt Outputs with a Rubric Evaluating Accuracy, Relevance, and Completeness Regression Testing for Prompt Changes Building a Prompt Evaluation Dataset Common Causes of Inconsistent Prompt Outputs Prompt Injection: Introduction and Examples Recognizing Prompt Injection Attempts Prompt Leaking and Instruction Disclosure Risks Jailbreaking: Understanding Adversarial Prompts Writing Safer Prompts for Untrusted Inputs Reducing Hallucinations with Clear Instructions and Context Prompt Safety: Limitations and Best Practices Build a Zero-Shot Sentiment Classifier Project Goal Build a Few-Shot Text Classification Prompt Build a Prompt-Based Text Summarizer Project Goal Build a Structured Information Extraction Prompt Build a Prompt Template for Blog Outlines Build a Prompt-Based SQL Assistant Build a Code Explanation Prompt Workflow Build a Multi-Step Research and Summarization Workflow Build a Prompt Comparison and Evaluation Pipeline Build a Prompt-Chaining Workflow for Document Analysis Build a RAG Prompt for Question Answering over Documents Build a Tool-Using ReAct Assistant Create a Reusable Prompt Library for a Web Application
Ask about this post
AI Ask about this post

Ask questions about Few-Shot Prompting and get answers drawn from it.

Signed-in readers only.