Module 3 · Chapter 15 Fundamental Prompting Techniques › Few-Shot Prompting

Few-Shot Prompting

Few-shot prompting gives an AI model several input-output examples before the real task, so it can learn the expected labels, format, and style directly from the demonstrations instead of relying on instructions alone.

Quick takeaway: A good few-shot prompt uses correct, diverse, and balanced examples - including positive, negative, and edge-case demonstrations - ordered to avoid bias. Start with the smallest example set that clearly teaches the pattern, then add examples only to fix observed failures.

Introduction

Few-shot prompting is a prompting technique in which a Large Language Model is given a small number of examples before it receives the actual task.

Each example normally contains:

  • A sample input
  • The expected output
  • A clear relationship between the input and output

The model studies these examples and identifies the expected pattern. It then applies the same pattern to the new input.

Few-shot prompting is useful when a simple instruction is not enough to explain the required output. The examples show the model exactly how the response should be produced.

For example, instead of only asking the model to classify customer feedback, you can provide several sample reviews with their correct categories. The model can then classify a new review by following the demonstrated pattern.

Learning Objectives

After completing this chapter, you will understand:

  • What few-shot prompting means
  • How examples guide a language model
  • How to select useful examples
  • How many examples should be included
  • Why example diversity and ordering matter
  • How to create balanced examples
  • How positive, negative, and edge-case examples improve results
  • How to use few-shot prompting for classification
  • How to use it for data extraction
  • How to use it for text generation
  • How to use it for code generation
  • What advantages and limitations it has
  • How to build a reusable few-shot prompt template

Prerequisites

Before learning few-shot prompting, you should understand:

  • What a prompt is
  • What input and output mean
  • How zero-shot prompting works
  • How one-shot prompting works
  • How instructions guide a language model
  • How output format requirements are defined

Key Terms

TermMeaning
ShotOne complete input-output example
Few-shot promptA prompt containing a small number of examples
DemonstrationAn example that shows the model how to perform the task
InputThe data given to the model
OutputThe response expected from the model
PatternThe relationship between example inputs and outputs
LabelA category assigned during classification
Edge caseAn unusual or difficult input
Positive exampleAn example showing the expected or accepted case
Negative exampleAn example showing an incorrect, rejected, or opposite case
Example diversityVariation across the examples
Context windowThe maximum amount of information the model can process in one request

What Is Few-Shot Prompting?

Few-shot prompting is a technique where a prompt includes multiple examples that demonstrate how a task should be completed.

The word "few" does not represent one fixed number. It usually means a small set of examples, such as:

  • Two examples
  • Three examples
  • Five examples
  • Eight examples

The correct number depends on the task, model, example size, and available context window.

A few-shot prompt normally contains four main parts:

  1. Task instruction
  2. Input-output examples
  3. Actual input
  4. Output requirement

Consider a basic sentiment classification task.

Task: Classify each review as Positive, Negative, or Neutral.

>

Example 1

>

Review: The application is fast and easy to use.

>

Sentiment: Positive

>

Example 2

>

Review: The application crashes every time I open it.

>

Sentiment: Negative

>

Example 3

>

Review: The application has a standard dashboard.

>

Sentiment: Neutral

>

Actual Review: The latest update made the application much smoother.

>

Sentiment:

The model uses the three examples to understand:

  • The available labels
  • The expected output style
  • The relationship between review text and sentiment
  • That only one sentiment label should be returned

Few-shot prompting is also known as:

  • Few-shot learning through prompting
  • In-context learning
  • Demonstration-based prompting
  • Example-based prompting

The model is not permanently trained using these examples. It only uses them within the current prompt.

How Few-Shot Prompting Works

Few-shot prompting works through pattern recognition inside the model's current context.

The model reads the instruction and examples before processing the actual input.

The general process is:

  1. The model reads the task instruction.
  2. It processes the first example.
  3. It identifies the relationship between the example input and output.
  4. It compares this relationship with the remaining examples.
  5. It identifies common rules, labels, formatting, and writing style.
  6. It reads the actual input.
  7. It predicts an output that follows the demonstrated pattern.

For example:

Task: Convert informal sentences into professional sentences.

>

Example 1

>

Informal: Send me the report quickly.

>

Professional: Please send me the report at your earliest convenience.

>

Example 2

>

Informal: I cannot attend the meeting.

>

Professional: I will be unable to attend the scheduled meeting.

>

Example 3

>

Informal: Fix this issue today.

>

Professional: Please resolve this issue by the end of today.

>

Actual Input: Tell me when the testing is complete.

>

Professional:

The model can identify several patterns:

  • Informal language is replaced with professional language.
  • The original meaning is preserved.
  • The response remains short.
  • The tone becomes respectful.
  • No additional information is introduced.

The likely output is:

Please let me know when the testing has been completed.

Few-shot prompting does not guarantee perfect reasoning. The model can still misunderstand weak, conflicting, or misleading examples.

The quality of the output strongly depends on:

  • Example quality
  • Example relevance
  • Example consistency
  • Instruction clarity
  • Input complexity
  • Model capability
  • Available context length

Selecting Few-Shot Examples

Selecting the right examples is one of the most important parts of few-shot prompting.

Good examples should accurately represent the task the model must perform.

Characteristics of a Good Example

A useful example should be:

  • Correct
  • Clear
  • Relevant
  • Representative
  • Consistent
  • Easy to understand
  • Similar to real inputs
  • Formatted like the expected output

Use Representative Examples

A representative example reflects the type of input the model will usually receive.

For example, suppose the task is to classify technical support requests into these categories:

  • Account
  • Payment
  • Performance
  • Security

A useful example set should include realistic support requests from these categories.

Example 1

>

Request: I forgot my password and cannot sign in.

>

Category: Account

>

Example 2

>

Request: My card was charged twice for the same subscription.

>

Category: Payment

>

Example 3

>

Request: The dashboard takes more than thirty seconds to load.

>

Category: Performance

>

Example 4

>

Request: I received a login alert from an unknown location.

>

Category: Security

These examples clearly demonstrate the purpose of every category.

Avoid Unrelated Examples

An example should be closely connected to the actual task.

Weak example:

Request: The website looks beautiful.

>

Category: Performance

The input does not clearly represent a performance issue. Such examples can confuse the model.

Use Correct Labels

Incorrect examples are especially dangerous because the model may copy the mistake.

Incorrect demonstration:

Request: I was charged twice.

>

Category: Account

Correct demonstration:

Request: I was charged twice.

>

Category: Payment

Match the Expected Complexity

If actual inputs are long and detailed, examples should not contain only short and simple sentences.

For example, when extracting information from invoices, provide realistic invoice-like examples rather than basic one-line text.

Keep Example Format Consistent

Good format:

Input: The package arrived two days late.

>

Output: Delivery Issue

>

Input: The product stopped working after one week.

>

Output: Product Defect

Inconsistent format:

Text: The package arrived two days late.

>

Category is Delivery Issue.

>

User Input: The product stopped working after one week.

>

Product Defect

Inconsistent labels and structures make pattern recognition more difficult.

Example Selection Checklist

Before adding an example, check:

  • Is the example factually correct?
  • Does it represent a real input?
  • Is its output correct?
  • Does it follow the required format?
  • Does it add a useful pattern?
  • Is it different from the other examples?
  • Could it confuse the model?
  • Is it necessary?

Number of Examples to Include

There is no fixed number of examples that works for every few-shot prompt.

A few-shot prompt may contain:

  • Two examples for a simple format
  • Three to five examples for basic classification
  • Five to ten examples for more complex tasks
  • More examples for tasks with many labels or unusual conditions

Factors That Affect the Number of Examples

The required number depends on:

  • Task complexity
  • Number of categories
  • Difference between categories
  • Input variation
  • Output complexity
  • Model capability
  • Context window size
  • Example length
  • Required accuracy

Simple Task

For a simple formatting task, two or three examples may be enough.

Input: java developer

>

Output: Java Developer

>

Input: software tester

>

Output: Software Tester

>

Actual Input: database administrator

>

Output:

The transformation is simple and consistent.

Multi-Class Classification

If the task contains many labels, more examples may be required.

Suppose the available categories are:

  • Billing
  • Login
  • Performance
  • Security
  • Feature Request
  • Data Error

Providing only two examples will not demonstrate all available categories.

A better prompt includes at least one clear example for each important label.

Too Few Examples

Too few examples may cause:

  • Incorrect pattern detection
  • Missing labels
  • Weak format control
  • Poor handling of difficult inputs
  • Inconsistent results

Too Many Examples

Too many examples may cause:

  • Larger token usage
  • Higher API cost
  • Slower processing
  • Reduced space for the actual input
  • Repeated information
  • More chances of conflicting examples
  • Attention being spread across unnecessary content

Practical Starting Point

A practical approach is:

  1. Start with three high-quality examples.
  2. Test the prompt on different inputs.
  3. Identify common failures.
  4. Add examples that directly address those failures.
  5. Remove examples that do not improve the result.

The objective is not to include the highest possible number of examples. The objective is to include the smallest useful set that demonstrates the task clearly.

Example Diversity

Example diversity means including examples that represent different forms of the task.

A diverse example set helps the model understand that the same rule should work across different inputs.

Types of Diversity

Examples can differ in:

  • Sentence length
  • Writing style
  • Vocabulary
  • Input structure
  • Difficulty
  • Category
  • Context
  • Tone
  • Data quality
  • Level of detail

Low-Diversity Example Set

Review: Excellent product.

>

Sentiment: Positive

>

Review: Amazing service.

>

Sentiment: Positive

>

Review: Great experience.

>

Sentiment: Positive

These examples all represent the same class and use similar language. They do not teach the model how to identify neutral or negative feedback.

Diverse Example Set

Review: The support engineer solved my issue within ten minutes.

>

Sentiment: Positive

>

Review: The application logs me out whenever I upload a document.

>

Sentiment: Negative

>

Review: The subscription includes five user accounts.

>

Sentiment: Neutral

>

Review: The product is useful, but the monthly price is too high.

>

Sentiment: Mixed

This set demonstrates:

  • Multiple sentiment classes
  • Different sentence lengths
  • Different topics
  • A mixed case
  • Different writing patterns

Diversity Must Remain Relevant

Diversity does not mean adding random examples.

All examples must still support the same task.

For example, when teaching invoice extraction, useful diversity may include:

  • Different date formats
  • Missing optional fields
  • Different currency symbols
  • Different invoice layouts

Unhelpful diversity would include examples from unrelated tasks such as sentiment classification or text summarisation.

Benefits of Example Diversity

Diverse examples can improve:

  • Generalisation
  • Classification accuracy
  • Edge-case handling
  • Format consistency
  • Understanding of category boundaries

Example Ordering

Example ordering refers to the sequence in which demonstrations appear inside the prompt.

The order can affect the model's output because recent and strongly structured examples may influence the final response more than earlier examples.

Common Ordering Strategies

Examples can be ordered:

  • From simple to complex
  • From common to uncommon
  • By category
  • By similarity to the actual input
  • Randomly
  • From positive to negative
  • From short to long

Simple-to-Complex Ordering

This approach first demonstrates the basic rule and then introduces more difficult cases.

Example 1

>

Input: I love this application.

>

Output: Positive

>

Example 2

>

Input: The application is difficult to use.

>

Output: Negative

>

Example 3

>

Input: The design is excellent, but the application is very slow.

>

Output: Mixed

This structure gradually introduces complexity.

Category-Based Ordering

Examples can be grouped by label.

Account examples

>

Payment examples

>

Performance examples

>

Security examples

This can be useful when categories are clearly separated.

However, grouped examples may create an ordering bias. The model may overpredict the category shown closest to the actual input.

Similar Example Last

Placing the most relevant example near the actual input can sometimes improve pattern matching.

Example 1: General support request

>

Example 2: Payment issue

>

Example 3: Login issue similar to the actual input

>

Actual Input: Another login-related issue

Avoid Hidden Ordering Bias

Consider this prompt:

Example 1: Positive

>

Example 2: Positive

>

Example 3: Positive

>

Example 4: Negative

>

Actual Input: Neutral statement

The model may be influenced by the repeated positive pattern.

To reduce ordering bias:

  • Balance the label distribution.
  • Test multiple example orders.
  • Keep formatting consistent.
  • Avoid placing several identical labels together without a reason.
  • Place the most representative examples near the actual input.
  • Use explicit label definitions.
  1. Begin with a clear and simple example.
  2. Add examples covering the main variations.
  3. Include difficult or edge cases later.
  4. Place the most relevant example close to the actual input.
  5. Test whether changing the order changes the result.

Balanced Examples

Balanced examples give reasonable representation to all important labels, outcomes, or task variations.

Balanced examples are especially important in classification tasks.

Unbalanced Example Set

Suppose a prompt contains:

  • Five Positive examples
  • One Negative example
  • No Neutral examples

The model may develop a bias toward the Positive label.

Balanced Example Set

A basic balanced set may contain:

  • Two Positive examples
  • Two Negative examples
  • Two Neutral examples

Example:

Review: The tool saved several hours of manual work.

>

Sentiment: Positive

>

Review: Customer support responded immediately.

>

Sentiment: Positive

>

Review: The application freezes during payment.

>

Sentiment: Negative

>

Review: The documentation is outdated and incomplete.

>

Sentiment: Negative

>

Review: The application supports CSV export.

>

Sentiment: Neutral

>

Review: The subscription renews every month.

>

Sentiment: Neutral

Balance Does Not Always Mean Equal Numbers

Some tasks do not require an exactly equal number of examples.

For example, if security incidents are rare but important, the prompt may include extra security examples to demonstrate important distinctions.

The goal is to provide enough representation for each meaningful case.

Balance Across More Than Labels

Examples can also be balanced across:

  • Short and long inputs
  • Easy and difficult cases
  • Formal and informal language
  • Valid and invalid data
  • Complete and incomplete records
  • Common and uncommon conditions

Balanced Prompt Design Checklist

Check whether:

  • Every label has at least one clear example.
  • Similar labels have examples showing their differences.
  • One label does not dominate without a reason.
  • Difficult categories receive enough coverage.
  • Common real-world variations are represented.

Positive and Negative Examples

Positive and negative examples help define what should and should not be accepted.

The meaning of positive and negative examples depends on the task.

In a validation task:

  • Positive example: Valid input
  • Negative example: Invalid input

In a moderation task:

  • Positive example: Content that violates a rule
  • Negative example: Content that does not violate the rule

In a writing task:

  • Positive example: Good output
  • Negative example: Weak or prohibited output

Positive Example

A positive example demonstrates the expected behaviour.

Input: [john.doe@example.com](mailto:john.doe@example.com)

>

Validation Result: Valid Email

Negative Example

A negative example demonstrates an invalid or rejected condition.

Input: john.doe@example

>

Validation Result: Invalid Email

>

Reason: The domain extension is missing.

Using Positive and Negative Writing Examples

Task: Write concise product descriptions.

>

Positive Example

>

Product: Wireless keyboard with silent keys and Bluetooth support

>

Description: A compact Bluetooth keyboard with quiet keys for comfortable everyday typing.

>

Negative Example

>

Product: Wireless keyboard with silent keys and Bluetooth support

>

Description: This amazing, fantastic, revolutionary, world-class keyboard is the greatest keyboard ever created.

>

Reason: Avoid exaggerated and unsupported claims.

This prompt teaches the model:

  • What style is expected
  • What style should be avoided
  • Why the negative example is unsuitable

Clearly Label Negative Examples

Without a clear label, the model may copy the negative example.

Weak structure:

Example: Write a long and exaggerated product description.

Better structure:

Incorrect Example: Write a long and exaggerated product description.

>

Reason: The output is not concise and contains unsupported claims.

>

Correct Example: Write a short factual description using the provided features.

Best Practices

  • Clearly label correct and incorrect examples.
  • Explain why a negative example is wrong.
  • Do not include harmful mistakes without correction.
  • Keep negative examples relevant to common failures.
  • Finish with a correct example before the actual task when possible.

Edge-Case Examples

An edge case is an unusual input that does not follow the most common pattern.

Edge cases are important because real-world data is often incomplete, unclear, inconsistent, or unexpected.

Common Edge Cases

Edge cases may include:

  • Empty input
  • Missing values
  • Conflicting information
  • Multiple possible labels
  • Very long input
  • Unusual symbols
  • Different date formats
  • Mixed languages
  • Invalid code
  • Unsupported values
  • Ambiguous statements

Classification Edge Case

Review: The application is fast, but it deleted my saved settings.

>

Sentiment: Mixed

>

Reason: The review contains both positive and negative feedback.

Without this example, the model may classify the review as only Positive or Negative.

Data Extraction Edge Case

Input: Invoice Number: Not Provided, Date: 15/07/2026, Total: ₹4,500

>

Output:

>

Invoice Number: null

>

Invoice Date: 2026-07-15

>

Total Amount: 4500

>

Currency: INR

This example teaches the model how to handle a missing field.

Empty Input Edge Case

Input:

>

Output:

>

Status: Invalid

>

Error: Input text is empty.

Conflicting Information Edge Case

Input: The meeting is scheduled for Monday, 12 August. A later note says Tuesday, 13 August.

>

Output:

>

Status: Conflict Found

>

Details: Two different meeting dates are present.

>

Action: Request clarification.

Benefits of Edge-Case Examples

Edge-case demonstrations help the model:

  • Avoid unsupported guesses
  • Return fallback values
  • Identify ambiguity
  • Handle missing information
  • Follow error-handling rules
  • Produce stable output

Do Not Overload the Prompt

Include edge cases that are:

  • Likely to occur
  • Important to handle
  • Difficult for the model
  • Connected to known failures

Do not add every theoretically possible exception. Too many edge cases can make the prompt unnecessarily large.

Few-Shot Classification

Few-shot classification assigns an input to one or more categories using demonstrated examples.

Common classification tasks include:

  • Sentiment classification
  • Email classification
  • Support-ticket routing
  • Intent detection
  • Content moderation
  • Topic classification
  • Urgency detection
  • Document classification

Basic Structure

Task: Classify the input using one of the allowed labels.

>

Allowed Labels: Label A, Label B, Label C

>

Example 1

>

Input: Sample text

>

Label: Label A

>

Example 2

>

Input: Sample text

>

Label: Label B

>

Actual Input: New text

>

Label:

Customer-Support Classification Example

Task: Classify each customer request into one category.

>

Allowed Categories: Account, Billing, Performance, Security, Feature Request

>

Example 1

>

Request: I cannot reset my account password.

>

Category: Account

>

Example 2

>

Request: My subscription payment was processed twice.

>

Category: Billing

>

Example 3

>

Request: The dashboard takes too long to load.

>

Category: Performance

>

Example 4

>

Request: Someone logged into my account from another country.

>

Category: Security

>

Example 5

>

Request: Please add an option to export reports as PDF.

>

Category: Feature Request

>

Actual Request: The application becomes unresponsive when I open the analytics page.

>

Category:

Expected output:

Performance

Multi-Label Classification

Some inputs may belong to multiple categories.

Task: Assign all matching categories.

>

Allowed Categories: Billing, Account, Security, Performance

>

Example 1

>

Request: I cannot log in after changing my password.

>

Categories: Account

>

Example 2

>

Request: My card was charged after I cancelled the subscription.

>

Categories: Billing

>

Example 3

>

Request: My account is slow, and I received an unknown login alert.

>

Categories: Performance, Security

>

Actual Request: I cannot access my account, and I received a password reset email that I did not request.

>

Categories:

Expected output:

Account, Security

Best Practices for Few-Shot Classification

  • Define all possible categories.
  • Use exact category names.
  • Show the expected output style.
  • Select an example with a clear label.
  • Avoid examples that could belong to several categories.
  • State whether multiple labels are allowed.
  • State whether explanations are required.
  • Add a fallback category when needed.

Example with fallback:

Task: Classify the message.

>

Categories: Billing, Technical, Delivery, Other

>

Example Input: My card was charged but the order was not created.

>

Example Output: Billing

>

Actual Input: I want to know whether your company provides internships.

Expected output:

Other

Few-Shot Data Extraction

Extraction means finding specific information inside a larger piece of text.

Few-shot extraction shows the model which fields to find and how to return them.

Basic Extraction Example

Task: Extract the person's name and job role.

>

Example Input: Anjali Mehta works as a Business Analyst at NovaTech.

>

Example Output: Name: Anjali Mehta Role: Business Analyst

>

Actual Input: Rohit Kumar joined CloudCore as a DevOps Engineer.

Expected output:

Name: Rohit Kumar Role: DevOps Engineer

Contact Information Extraction

Task: Extract the name, email, and phone number. Use Not Available when a value is missing.

>

Example Input: Contact Meera Joshi at meera@example.com or 9876543210.

>

Example Output: Name: Meera Joshi Email: meera@example.com Phone: 9876543210

>

Actual Input: For assistance, contact Amit Shah at amit@company.com.

Expected output:

Name: Amit Shah Email: amit@company.com Phone: Not Available

Invoice Extraction

Task: Extract invoice details.

>

Example Input: Invoice INV-1005 was issued to BrightTech on 05 August 2026 for ₹25,000.

>

Example Output: Invoice Number: INV-1005 Customer: BrightTech Date: 05 August 2026 Amount: ₹25,000

>

Actual Input: Invoice INV-1042 was issued to CloudNova on 06 August 2026 for ₹48,500.

Expected output:

Invoice Number: INV-1042 Customer: CloudNova Date: 06 August 2026 Amount: ₹48,500

JSON Extraction

Task: Extract project details as JSON.

>

Example Input: Project Atlas uses Java and Spring Boot. The project status is Active.

>

Example Output: { "project_name": "Atlas", "technologies": ["Java", "Spring Boot"], "status": "Active" }

>

Actual Input: Project Orion uses Python, FastAPI, and PostgreSQL. The project status is In Development.

Expected output:

{ "project_name": "Orion", "technologies": ["Python", "FastAPI", "PostgreSQL"], "status": "In Development" }

Requirement Extraction

Task: Extract the functional requirement and deadline.

>

Example Input: The system must allow users to download invoices before 15 August.

>

Example Output: Requirement: Allow users to download invoices Deadline: 15 August

>

Actual Input: The application must support password reset before 30 September.

Expected output:

Requirement: Support password reset Deadline: 30 September

Few-Shot Text Generation

Few-shot prompting can guide the model to generate text in a specific style, format, or tone.

Style Transfer

Task: Rewrite the sentence in a professional tone.

>

Example Input: Send me the file now.

>

Example Output: Could you please send me the file at your earliest convenience?

>

Actual Input: Fix this bug today.

Expected output:

Could you please resolve this bug today?

Marketing Copy Generation

Task: Write a short marketing tagline for the product.

>

Example Input: A noise-cancelling headphone with 30-hour battery life.

>

Example Output: Silence the noise. Listen longer.

>

Actual Input: A lightweight laptop designed for travel.

Expected output:

Travel light. Work anywhere.

Email Generation

Task: Write a follow-up email based on the context.

>

Example Input: The client has not replied to the proposal sent three days ago.

>

Example Output: Subject: Following up on our proposal

>

Hi [Client Name],

>

I wanted to follow up on the proposal I sent on [Date]. Please let me know if you have any questions or need further details.

>

Best regards, [Your Name]

>

Actual Input: The candidate completed the interview but has not received feedback yet.

Expected output:

Subject: Interview follow-up

>

Hi [Candidate Name],

>

Thank you for completing the interview on [Date]. We are currently reviewing all candidates and will share feedback by [Timeline].

>

Best regards, [Recruiter Name]

Few-Shot Code Generation

Few-shot prompting can demonstrate the expected code style, structure, and patterns.

Function Generation

Task: Write a Java function that validates an email address.

>

Example Input: Write a function that checks if a string contains only digits.

>

Example Output: ``java public boolean isNumeric(String input) { if (input == null || input.isEmpty()) { return false; } for (char c : input.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } ``

>

Actual Input: Write a function that validates an email format.

Expected output:

``java public boolean isValidEmail(String email) { if (email == null || email.isEmpty()) { return false; } String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"; return email.matches(emailRegex); } ``

API Endpoint Generation

Task: Create a REST endpoint for the given requirement.

>

Example Input: Create a GET endpoint that returns all users.

>

Example Output: ``java @GetMapping("/users") public ResponseEntity<List<User>> getAllUsers() { List<User> users = userService.findAll(); return ResponseEntity.ok(users); } ``

>

Actual Input: Create a POST endpoint to create a new order.

Expected output:

``java @PostMapping("/orders") public ResponseEntity<Order> createOrder(@RequestBody OrderRequest request) { Order order = orderService.create(request); return ResponseEntity.status(HttpStatus.CREATED).body(order); } ``

SQL Query Generation

Task: Write a SQL query for the given requirement.

>

Example Input: Find all users who registered in the last 30 days.

>

Example Output: ``sql SELECT * FROM users WHERE created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY); ``

>

Actual Input: Find the total number of orders per customer.

Expected output:

``sql SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id; ``

Advantages and Limitations

Advantages

  • Provides clear guidance without permanent model changes.
  • Works with any model that supports in-context learning.
  • Allows rapid experimentation with different examples.
  • Can handle tasks that are difficult to describe in pure instructions.
  • Demonstrates exact output format and style.
  • Helps the model understand edge cases and exceptions.
  • Reduces ambiguity in complex tasks.
  • Enables non-technical users to guide model behaviour.

Limitations

  • Consumes context window space.
  • Increases token usage and cost.
  • Does not guarantee correct reasoning.
  • Quality depends heavily on example selection.
  • May overfit to the provided examples.
  • Can be sensitive to example ordering.
  • Does not update model knowledge.
  • Large example sets can slow down inference.
  • Examples must be manually created and maintained.
  • May not generalise well to unseen variations.

Few-Shot Prompt Template

A reusable template helps create consistent few-shot prompts.

Basic Template

Prompt
Task: [Clear description of what the model should do]

Rules:
[Any constraints, format requirements, or special instructions]

Examples:
Example 1
Input: [Sample input 1]
Output: [Expected output 1]

Example 2
Input: [Sample input 2]
Output: [Expected output 2]

Example 3
Input: [Sample input 3]
Output: [Expected output 3]

Actual Input:
[The real input to process]

Output:

Classification Template

Prompt
Task: Classify the input into one of the allowed categories.

Allowed Categories: [Category A, Category B, Category C, ...]

Rules:
- Return only the category name.
- Use exact category spelling.
- If no category matches, return "Other".

Examples:
Example 1
Input: [Sample text]
Category: [Category A]

Example 2
Input: [Sample text]
Category: [Category B]

Example 3
Input: [Sample text]
Category: [Category C]

Actual Input:
[New text to classify]

Category:

Extraction Template

Prompt
Task: Extract the following fields from the input text.

Fields: [Field 1, Field 2, Field 3, ...]

Rules:
- Use "Not Available" when a field is missing.
- Return each field on a new line.
- Format: Field Name: Value

Examples:
Example 1
Input: [Sample text containing all fields]
Output:
  Field 1: [Value]
  Field 2: [Value]
  Field 3: [Value]

Example 2
Input: [Sample text with missing field]
Output:
  Field 1: [Value]
  Field 2: Not Available
  Field 3: [Value]

Actual Input:
[New text to process]

Output:

Generation Template

Prompt
Task: Generate [type of content] based on the input.

Style: [Professional, casual, technical, marketing, etc.]
Format: [Paragraph, bullet points, JSON, etc.]
Length: [Approximate word count or character limit]

Examples:
Example 1
Input: [Source description 1]
Output: [Generated content 1]

Example 2
Input: [Source description 2]
Output: [Generated content 2]

Actual Input:
[New source description]

Output:

Code Generation Template

Prompt
Task: Write a [language] function that [requirement].

Requirements:
- Follow [coding standard or style guide].
- Include error handling.
- Add comments for complex logic.
- Use [specific library or pattern if needed].

Examples:
Example 1
Input: Write a function that [similar requirement].
Output:

[Complete function code]

Prompt

Actual Input:
Write a function that [actual requirement].

Output:

Final Summary

Few-shot prompting is a powerful technique that uses a small set of input-output examples to guide a language model toward the desired behaviour.

Key principles for effective few-shot prompting:

  • Select representative, correct, and diverse examples.
  • Balance examples across all important labels and variations.
  • Include positive, negative, and edge-case examples when relevant.
  • Order examples thoughtfully to reduce bias.
  • Keep the example set as small as possible while covering the task.
  • Ensure the instruction and examples agree on format and rules.
  • Test the prompt with different inputs before deploying.
  • Use templates to maintain consistency across similar tasks.

Few-shot prompting bridges the gap between zero-shot instructions and full fine-tuning. It provides immediate, flexible control over model output without changing the model itself.

When used carefully, few-shot prompting can significantly improve accuracy, consistency, and format adherence for classification, extraction, generation, and code tasks.

Frequently Asked Questions

What is few-shot prompting?

Few-shot prompting is a technique where you give a language model a small number of input-output examples before the actual task. The model studies the pattern in the examples and applies the same pattern to the new input.

How many examples should a few-shot prompt include?

There is no fixed number. Simple formatting tasks may need only two or three examples, while multi-class classification or complex extraction tasks may need five to ten. Start with three high-quality examples, test the prompt, and add more only to fix observed failures.

Why does example diversity matter in few-shot prompting?

Diverse examples show the model that the same rule applies across different sentence lengths, topics, and difficulty levels. Low-diversity example sets, such as several nearly identical positive reviews, fail to teach the model how to handle neutral, negative, or mixed cases.

Does the order of examples affect the model output?

Yes. Recent or repeated examples can influence the response more than earlier ones. Grouping many examples of the same label together can bias the model toward that label, so it helps to balance the label distribution and place the most relevant example closest to the actual input.

What are balanced examples in a few-shot prompt?

Balanced examples give reasonable representation to every important label or outcome instead of favoring one. For example, a sentiment classifier prompt should include Positive, Negative, and Neutral examples rather than mostly Positive ones, which would bias the model toward that label.

What is the difference between positive and negative examples?

A positive example demonstrates the expected or accepted output, while a negative example demonstrates an incorrect, rejected, or opposite case. Negative examples should be clearly labeled and explained so the model does not accidentally copy the undesired behaviour.

Why are edge-case examples important in few-shot prompting?

Edge cases such as empty input, missing values, or conflicting information are common in real-world data. Including a few clear edge-case demonstrations teaches the model to return fallback values or flag ambiguity instead of guessing.

Can few-shot prompting be used for code generation?

Yes. A few-shot code generation prompt shows one or more example functions or endpoints in the desired language, naming style, and structure. The model then applies the same coding pattern to a new requirement.

What are the main limitations of few-shot prompting?

Few-shot prompts consume context window space, increase token usage and cost, and do not guarantee correct reasoning. Output quality depends heavily on example selection, examples must be manually maintained, and the model can be sensitive to example ordering and bias.

How is few-shot prompting different from one-shot prompting?

One-shot prompting provides exactly one example, while few-shot prompting provides several examples covering different labels, styles, or edge cases. Few-shot prompting generally gives better coverage for complex or multi-category tasks at the cost of a longer prompt.