Few-Shot Prompting
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.