Module 3 · Chapter 14 Fundamental Prompting Techniques › One-Shot Prompting

One-Shot Prompting

One-shot prompting provides exactly one example to show an AI model the expected pattern, format, and style for a task. It bridges the gap between zero-shot instructions and few-shot demonstrations, offering strong format control with minimal prompt length.

Quick takeaway: One-shot prompting gives the model a single clear demonstration of the task. The example is the most important part - it must be correct, relevant, and properly formatted. A strong example improves clarity and consistency, while a weak example can guide the model in the wrong direction.

Introduction

One-shot prompting is a prompting technique in which the user gives an AI model exactly one example before asking it to complete a new task.

The example shows the model:

  • What kind of input it will receive
  • What kind of output it should produce
  • How the output should be formatted
  • What level of detail is expected
  • What rules it should follow

The model studies the example and tries to apply the same pattern to the actual input.

One-shot prompting is useful when a simple instruction is not enough, but providing many examples is unnecessary. It gives the model a clear pattern while keeping the prompt relatively short.

A one-shot prompt usually contains four main parts:

  1. Task instruction
  2. One example input
  3. One example output
  4. Actual input

A simple one-shot prompt looks like this:

Prompt
Task: Convert the given sentence into a professional sentence.
Example Input: Send me the report quickly.
Example Output: Please send me the report at your earliest convenience.
Actual Input: Tell me when the issue is fixed.

Expected response:

Prompt
Please let me know once the issue has been resolved.

The model follows the style shown in the example and applies it to the new input.

Learning Objectives

After completing this chapter, you should be able to:

  • Explain what one-shot prompting means
  • Understand how an AI model uses one example
  • Select a useful and representative example
  • Create clear input-output demonstrations
  • Separate examples from actual input
  • Use one-shot prompting for classification
  • Use one-shot prompting for information extraction
  • Use one-shot prompting for content generation
  • Use one-shot prompting for code generation
  • Understand the benefits and limitations of one-shot prompts
  • Create reusable one-shot prompt templates

What Is One-Shot Prompting?

One-shot prompting is a method in which one completed example is included in the prompt to guide the model.

The word one-shot means that only one demonstration is provided.

The model is not retrained using this example. It uses the example only during the current request to understand the required pattern.

A one-shot prompt contains:

  • A clear instruction
  • One sample input
  • One sample output
  • A new input that must be processed

Example:

Prompt
Task: Identify the sentiment of the customer review.
Example Input: The product works perfectly and arrived early.
Example Output: Positive
Actual Input: The application keeps crashing after the update.

Expected output:

Prompt
Negative

The example teaches the model that it should return only a sentiment label instead of writing a long explanation.

Main characteristics of one-shot prompting

  • It includes exactly one example.
  • The example demonstrates the expected task.
  • The actual input is different from the example.
  • The output usually follows the demonstrated structure.
  • It does not update the model permanently.
  • It works within the current prompt context.
  • It can control format, tone, style, and level of detail.

One-shot prompting structure

Prompt
Instruction
Example Input
Example Output
Actual Input

One-shot prompting compared with other techniques

Prompting techniqueNumber of examplesBest use
Zero-shot prompting0Simple and direct tasks
One-shot prompting1Tasks that need one clear pattern
Few-shot prompting2 or moreTasks with complex patterns or several cases

Simple comparison

Zero-shot prompt:

Prompt
Classify the review as Positive, Negative, or Neutral.
Review: The service was slow.

One-shot prompt:

Prompt
Classify the review as Positive, Negative, or Neutral.
Example Review: The support team solved my issue quickly.
Example Output: Positive
Actual Review: The service was slow.

The one-shot version gives the model a clear demonstration of the expected answer format.

How One-Shot Prompting Works

One-shot prompting works by showing the model a pattern and asking it to continue that pattern for a new input.

The model processes both the instruction and the example. It then predicts the most suitable output for the actual input.

Step-by-step working

  1. The model reads the task instruction.
  2. It reads the example input.
  3. It observes the example output.
  4. It identifies the relationship between the example input and output.
  5. It reads the actual input.
  6. It applies the same relationship to the actual input.
  7. It generates an output in a similar format.

Example:

Prompt
Task: Convert the product description into a short marketing tagline.
Example Input: A lightweight laptop with a long-lasting battery for remote professionals.
Example Output: Work anywhere. Stay powered all day.
Actual Input: A secure cloud storage platform for small businesses.

Expected output:

Prompt
Store securely. Grow confidently.

The model notices that the example output is:

  • Short
  • Promotional
  • Divided into two small statements
  • Focused on benefits

It uses the same pattern for the new input.

Pattern recognition in one-shot prompting

The model may learn several things from a single example:

  • Output length
  • Sentence structure
  • Tone
  • Label names
  • Field order
  • Data format
  • Writing style
  • Level of detail
  • Required transformations
  • Expected reasoning depth

How the model processes the example

The model does not copy the example directly. It tries to understand the hidden rule behind it.

For example:

Prompt
Example Input: server_error
Example Output: Server Error
Actual Input: payment_failed

The model may identify the rule as:

  • Replace underscores with spaces
  • Capitalize the first letter of each word

Expected output:

Prompt
Payment Failed

In-context learning

One-shot prompting is a form of in-context learning.

In-context learning means the model learns how to perform a task from information included in the current prompt. The learning is temporary and applies only to the current interaction.

The model parameters are not changed.

Important point

A model may copy the wrong pattern when the example is unclear, incorrect, or unrelated. Therefore, the quality of the example directly affects the quality of the answer.

Selecting a Representative Example

A representative example is an example that clearly shows the main pattern of the task.

The example should be similar enough to the actual input to guide the model, but it should not be identical.

Characteristics of a good example

A good one-shot example should be:

  • Correct
  • Clear
  • Relevant
  • Complete
  • Easy to understand
  • Similar to the actual task
  • Properly formatted
  • Free from unnecessary details
  • Based on the most common case

Example selection process

Before choosing an example, ask:

  1. What transformation should the model perform?
  2. What output format should the model follow?
  3. What rule must be demonstrated?
  4. What mistakes should the example prevent?
  5. Is the example similar to the real input?
  6. Is the example correct in every detail?

Weak example

Task: Convert technical text into simple language.

Prompt
Example Input: The weather is nice.
Example Output: The weather is good.
Actual Input: The application uses asynchronous processing to prevent blocking operations.

The example is weak because it does not demonstrate how to simplify technical language.

Better example

Prompt
Task: Rewrite the technical sentence in simple language.
Example Input: The system uses data encryption to prevent unauthorized access.
Example Output: The system protects the data so that unauthorized people cannot read it.
Actual Input: The application uses asynchronous processing to prevent blocking operations.

Expected output:

Prompt
The application performs some tasks in the background so that other operations can continue without waiting.

The improved example demonstrates the actual transformation.

Avoid unusual examples

Do not select an example that represents a rare case when most inputs follow a simpler pattern.

For example, when demonstrating date conversion, use a normal valid date instead of an unusual or incomplete date.

Good example:

Prompt
Example Input: 06 August 2026
Example Output: 2026-08-06

Less useful example:

Prompt
Example Input: Around the beginning of August
Example Output: Unknown exact date

The second example teaches fallback behaviour instead of the main date conversion pattern.

Match the example with the task type

Task typeSuitable example
ClassificationOne clearly labelled item
ExtractionText containing all required fields
SummarisationA short document and a clear summary
RewritingA sentence before and after improvement
Code generationA similar function with expected style
JSON formattingAn input and correctly structured JSON
Content generationA source description and final content

Use correct edge cases carefully

An edge case is an unusual situation such as missing information, invalid input, or mixed intent.

A single edge-case example may confuse the model if the actual input is a normal case.

When the actual input is an edge case, select an example that demonstrates the same type of edge case.

Input-Output Demonstrations

An input-output demonstration shows the model exactly how an input should be converted into an output.

It is the core part of one-shot prompting.

Basic demonstration format

Prompt
Example Input: [sample data]
Example Output: [expected result]

The example input should represent the data the model will receive.

The example output should represent the exact result the model should produce.

Demonstrating a transformation

Prompt
Task: Convert a sentence into title case.
Example Input: introduction to prompt engineering
Example Output: Introduction to Prompt Engineering
Actual Input: understanding one-shot prompting

Expected output:

Prompt
Understanding One-Shot Prompting

Demonstrating a structured output

Prompt
Task: Extract the person's name and role.
Example Input: Priya Shah works as a Data Analyst at BrightCore.
Example Output:
  Name: Priya Shah
  Role: Data Analyst
Actual Input: Amit Patil joined TechNova as a Java Developer.

Expected output:

Prompt
Name: Amit Patil
Role: Java Developer

Demonstrating output rules

Suppose the required output must contain only a label.

Prompt
Task: Classify the message as Question, Request, Complaint, or Feedback.
Return only the category name.
Example Input: The payment page shows an error every time.
Example Output: Complaint
Actual Input: Can you send me the updated invoice?

Expected output:

Prompt
Request

The example confirms that the model should not include an explanation.

Demonstrating output style

Prompt
Task: Rewrite the message in a polite and professional tone.
Example Input: You did not send the document.
Example Output: I noticed that the document has not been sent yet. Could you please share it when convenient?
Actual Input: Fix this issue today.

Expected output:

Prompt
Could you please resolve this issue today?

Demonstration quality rules

The demonstration should:

  • Follow every instruction
  • Use the exact required format
  • Contain no factual errors
  • Avoid extra fields
  • Avoid mixed output styles
  • Use realistic input
  • Clearly show the intended transformation

Incorrect demonstration problem

Prompt
Task: Return only the product category.
Example Input: Wireless mouse
Example Output: Category: Electronics

The instruction says to return only the category, but the example adds Category:.

The model may follow the example instead of the written instruction.

Correct version:

Prompt
Task: Return only the product category.
Example Input: Wireless mouse
Example Output: Electronics

The instruction and example should always agree.

Formatting the Example

Formatting helps the model understand which content is an instruction, which content is an example, and which content is the actual task.

Poor formatting can cause the model to mix the example with the actual input.

Use clear labels

Useful labels include:

  • Task
  • Instruction
  • Example Input
  • Example Output
  • Actual Input
  • Required Output
  • Rules

Example:

Prompt
Task: Convert the sentence into active voice.
Example Input: The report was prepared by the development team.
Example Output: The development team prepared the report.
Actual Input: The bug was fixed by the support engineer.

Expected output:

Prompt
The support engineer fixed the bug.

Use consistent field names

Do not use different labels for the example and actual input unless there is a clear reason.

Less clear format:

Prompt
Sample Text: The order was delivered.
Result: Positive
User Review: The package was damaged.

Better format:

Prompt
Example Input: The order was delivered on time.
Example Output: Positive
Actual Input: The package was damaged.

Use a stable structure

For structured tasks, keep the field order the same.

Example:

Prompt
Task: Extract issue details.
Example Input: User cannot log in after changing the password.
Example Output:
  Issue: Login failure
  Trigger: Password change
  Affected User: User
Actual Input: Administrator cannot upload files after the storage update.

Expected output:

Prompt
Issue: File upload failure
Trigger: Storage update
Affected User: Administrator

Formatting JSON output

Prompt
Task: Convert the text into JSON.
Example Input: Rahul is a Python Developer with 4 years of experience.
Example Output:
  {
    "name": "Rahul",
    "role": "Python Developer",
    "experience_years": 4
  }
Actual Input: Sneha is a Java Developer with 6 years of experience.

Expected output:

JSON
{
  "name": "Sneha",
  "role": "Java Developer",
  "experience_years": 6
}

Formatting list output

Prompt
Task: Extract technologies as a bullet list.
Example Input: The project uses Java, Spring Boot, MySQL, and Docker.
Example Output:
  - Java
  - Spring Boot
  - MySQL
  - Docker
Actual Input: The application uses Python, FastAPI, PostgreSQL, and Redis.

Expected output:

Prompt
- Python
- FastAPI
- PostgreSQL
- Redis

Use separators

Separators make the prompt easier to read.

Common separators include:

  • Horizontal lines
  • Labels
  • XML-style tags
  • Triple quotes
  • Brackets
  • Section names

Example using section labels:

Prompt
Task:
Classify the support message.
Example:
Input: I was charged twice for the same order.
Output: Billing Issue
Actual Task:
Input: I cannot reset my password.

Expected output:

Prompt
Account Access Issue

Formatting rules

  • Use the same indentation throughout the prompt.
  • Keep labels simple.
  • Do not combine instructions and data on the same unclear line.
  • Avoid unnecessary decorative symbols.
  • Keep the example close to the actual input.
  • Use the same output format in the example that you expect in the final answer.

Separating Example and Actual Input

The example and actual input must be clearly separated.

Without separation, the model may:

  • Treat the actual input as part of the example
  • Repeat the example output
  • Combine both inputs
  • Generate output for the wrong text
  • Copy values from the example

Clear separation using labels

Prompt
Instruction: Extract the email address.
Example Input: Contact Ravi at ravi@example.com for support.
Example Output: ravi@example.com
Actual Input: Send the final report to neha@company.com.

Expected output:

Prompt
neha@company.com

Clear separation using lines

Prompt
Task: Rewrite the sentence in formal language.
Example Input: Send me the details.
Example Output: Please send me the required details.
Actual Input: Tell me why it failed.

Expected output:

Prompt
Please explain why the process failed.

Clear separation using tags

Prompt
Task: Classify the message as Urgent or Normal.
<example>
<input>The production server is completely unavailable.</input>
<output>Urgent</output>
</example>
<actual-input>The weekly report is ready for review.</actual-input>

Expected output:

Prompt
Normal

Keep example data separate from instructions

Weak structure:

Prompt
Summarize this text like the example The application failed because the database was unavailable Output Database unavailability caused the application failure Now process The payment failed because the gateway timed out.

This structure is difficult to read.

Improved structure:

Prompt
Task: Summarize the cause of the problem in one sentence.
Example Input: The application failed because the database was unavailable.
Example Output: Database unavailability caused the application failure.
Actual Input: The payment failed because the gateway timed out.

Expected output:

Prompt
A payment gateway timeout caused the payment failure.
  1. Task
  2. Rules
  3. Example input
  4. Example output
  5. Actual input

Example:

Prompt
Task: Convert the sentence into a short action item.
Rules:
Use one sentence.
Start with an action verb.
Example Input: The team needs to review the security report before Friday.
Example Output: Review the security report before Friday.
Actual Input: The developer should update the API documentation today.

Expected output:

SQL
Update the API documentation today.

Prevent example copying

Add a clear instruction when the model may copy example values.

Prompt
Use the example only to understand the format.
Do not copy names, numbers, or facts from the example.
Process only the actual input.

This is useful for extraction, structured data, and document generation tasks.

One-Shot Classification

Classification means assigning an input to one category from a defined list.

One-shot classification provides one labelled example before asking the model to classify a new input.

Basic classification structure

Prompt
Task: Classify the input into one category.
Categories: Positive, Negative, Neutral
Example Input: The new update improved the application's performance.
Example Output: Positive
Actual Input: The update did not make any noticeable difference.

Expected output:

Prompt
Neutral

Customer support classification

Prompt
Task: Classify the support request.
Categories: Billing, Technical, Account, Delivery
Return only the category.
Example Input: I was charged twice for one subscription.
Example Output: Billing
Actual Input: The application closes whenever I upload a file.

Expected output:

Prompt
Technical

Email classification

Prompt
Task: Classify the email as Urgent or Normal.
Example Input: The production database is unavailable and customers cannot place orders.
Example Output: Urgent
Actual Input: Please review the meeting notes before next week.

Expected output:

Prompt
Normal

Intent classification

Prompt
Task: Identify the user's intent.
Categories: Check Balance, Transfer Money, Report Fraud, Update Profile
Example Input: I want to send ₹5,000 to my brother.
Example Output: Transfer Money
Actual Input: Someone made an unknown payment using my account.

Expected output:

Prompt
Report Fraud

Topic classification

Prompt
Task: Classify the question into Java, Python, SQL, or DevOps.
Example Input: How does inheritance work in Java?
Example Output: Java
Actual Input: How can I join two tables using a common column?

Expected output:

Prompt
SQL

Multi-label classification

One-shot prompting can also be used when one input may belong to more than one category.

Prompt
Task: Select all matching categories.
Categories: Performance, Security, Database, User Interface
Example Input: The SQL query is slow and causes high database CPU usage.
Example Output: Performance, Database
Actual Input: The login form exposes the password in plain text.

Expected output:

Prompt
Security, User Interface

Best practices for one-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:

Prompt
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:

Prompt
Other

One-Shot Extraction

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

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

Basic extraction example

Prompt
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:

Prompt
Name: Rohit Kumar
Role: DevOps Engineer

Contact information extraction

Prompt
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:

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

Invoice extraction

Prompt
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:

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

JSON extraction

Prompt
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:

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

Requirement extraction

Prompt
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:

Prompt
Requirement: Support password reset
Deadline: 30 September

Extraction with missing information

The example should demonstrate how missing data must be handled when missing values are common.

Prompt
Task: Extract the candidate name, role, and experience.
Use Not Mentioned for missing information.
Example Input: Neha has 5 years of experience as a Python Developer.
Example Output:
  Name: Neha
  Role: Python Developer
  Experience: 5 years
Actual Input: Arjun is applying for the Data Analyst position.

Expected output:

Prompt
Name: Arjun
Role: Data Analyst
Experience: Not Mentioned

Best practices for one-shot extraction

  • List all required fields.
  • Use fixed field names.
  • Define missing-value behaviour.
  • Do not allow the model to guess missing facts.
  • Show the exact output format.
  • Keep field order consistent.
  • Use realistic sample text.
  • State whether original wording should be preserved.
  • State whether values should be normalized.

One-Shot Content Generation

One-shot content generation uses one example to guide the model's writing style, format, tone, or structure.

It can be used for:

  • Blog introductions
  • Product descriptions
  • Social media posts
  • Email responses
  • Marketing taglines
  • Frequently asked questions
  • Course summaries
  • News summaries
  • Technical explanations

Product description generation

Prompt
Task: Write a two-sentence product description.
Focus on the main benefit and target user.
Example Input: Lightweight laptop with 12-hour battery life for remote workers.
Example Output: Work from anywhere with a lightweight laptop designed for remote professionals. Its 12-hour battery keeps you productive throughout the day.
Actual Input: Noise-cancelling headphones with a comfortable design for frequent travellers.

Expected output:

Prompt
Travel comfortably with noise-cancelling headphones designed for frequent travellers. Their comfortable fit and sound isolation help you enjoy clear audio during long journeys.

Social media caption generation

Prompt
Task: Write a short educational social media caption.
Use simple language.
End with one question.
Example Input: Topic: Why Java is platform independent
Example Output: Java code runs on the Java Virtual Machine, which allows the same compiled program to work on different operating systems. Which Java feature would you like to learn next?
Actual Input: Topic: Why prompt examples improve AI responses

Expected output:

Prompt
Prompt examples show the AI what type of response you expect, including its format, tone, and level of detail. Have you tried adding an example to your prompt?

FAQ generation

Prompt
Task: Create one question and answer from the topic.
Keep the answer under 50 words.
Example Input: Topic: Zero-shot prompting
Example Output:
  Question: What is zero-shot prompting?
  Answer: Zero-shot prompting is a method where an AI model completes a task using only instructions and no examples.
Actual Input: Topic: One-shot prompting

Expected output:

Prompt
Question: What is one-shot prompting?
Answer: One-shot prompting is a method where one example is provided to show the AI how to complete a new task.

Professional email response

Prompt
Task: Write a polite email response in two sentences.
Example Input: The client asked when the issue will be fixed. The expected completion time is tomorrow afternoon.
Example Output: Thank you for your patience. We expect to resolve the issue by tomorrow afternoon and will inform you once the fix is completed.
Actual Input: The manager asked when the report will be ready. It will be completed by Friday.

Expected output:

Prompt
Thank you for checking. The report will be completed by Friday, and I will share it as soon as it is ready.

Technical explanation generation

Prompt
Task: Explain the technical concept in simple language using one short example.
Example Input: Encapsulation in Java
Example Output: Encapsulation means keeping data and the methods that work with that data inside one class. For example, a BankAccount class can keep the balance private and allow access through deposit and withdraw methods.
Actual Input: Inheritance in Java

Expected output:

Prompt
Inheritance allows one Java class to reuse the fields and methods of another class. For example, a Car class can inherit common properties such as speed and color from a Vehicle class.

Style imitation

One-shot prompting can guide a general writing style, but the example should be original and should not request direct imitation of a living writer.

Safe style instruction:

Prompt
Write in a clear educational style using short paragraphs and practical examples.

The model can follow general qualities such as:

  • Formal
  • Friendly
  • Technical
  • Simple
  • Promotional
  • Educational
  • Direct
  • Concise

Best practices for content generation

  • Show the desired length.
  • Show the desired tone.
  • Show the required structure.
  • Use an example from the same content type.
  • Mention the target audience.
  • Define prohibited content.
  • State whether headings or bullet points are required.
  • Avoid examples that are much longer than the expected output.

One-Shot Code Generation

One-shot code generation provides one code example to show the model how new code should be written.

The example may demonstrate:

  • Programming language
  • Naming style
  • Function structure
  • Input and output format
  • Error handling
  • Comments
  • Code formatting
  • Return type
  • Validation rules

Basic one-shot code generation

Python
Task: Create a Python function using the style shown in the example.
Example Requirement: Create a function that adds two numbers.
Example Output:
    def add_numbers(first_number: int, second_number: int) -> int:
        return first_number + second_number
Actual Requirement: Create a function that multiplies two numbers.

Expected output:

Python
def multiply_numbers(first_number: int, second_number: int) -> int:
    return first_number * second_number

Java method generation

Prompt
Task: Generate a Java method using the demonstrated naming and validation style.
Example Requirement: Create a method that returns the larger of two integers.
Example Output:
    public static int findLargerNumber(int firstNumber, int secondNumber) {
        return Math.max(firstNumber, secondNumber);
    }
Actual Requirement: Create a method that returns the smaller of two integers.

Expected output:

Prompt
public static int findSmallerNumber(int firstNumber, int secondNumber) {
    return Math.min(firstNumber, secondNumber);
}

Code generation with validation

Prompt
Task: Generate a Java method using the same validation pattern.
Example Requirement: Divide two numbers.
Example Output:
    public static double divide(double dividend, double divisor) {
        if (divisor == 0) {
            throw new IllegalArgumentException("Divisor cannot be zero");
        }
        return dividend / divisor;
    }
Actual Requirement: Calculate the average of an integer array and reject an empty array.

Expected output:

Prompt
public static double calculateAverage(int[] numbers) {
    if (numbers == null || numbers.length == 0) {
        throw new IllegalArgumentException("Numbers cannot be null or empty");
    }
    int total = 0;
    for (int number : numbers) {
        total += number;
    }
    return (double) total / numbers.length;
}

SQL query generation

Prompt
Task: Write an SQL query using the same format.
Example Requirement: Find active users from the users table.
Example Output:
    SELECT id, name, email
    FROM users
    WHERE status = 'ACTIVE';
Actual Requirement: Find completed orders from the orders table.

Expected output:

SQL
SELECT id, customer_id, total_amount
FROM orders
WHERE status = 'COMPLETED';

API response generation

Prompt
Task: Generate a Spring Boot controller method using the example pattern.
Example Requirement: Return a product by ID.
Example Output:
    @GetMapping("/products/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        Product product = productService.getProductById(id);
        return ResponseEntity.ok(product);
    }
Actual Requirement: Return a customer by ID.

Expected output:

Prompt
@GetMapping("/customers/{id}")
public ResponseEntity<Customer> getCustomerById(@PathVariable Long id) {
    Customer customer = customerService.getCustomerById(id);
    return ResponseEntity.ok(customer);
}

Code review output

One-shot prompting can also guide how code reviews should be written.

Prompt
Task: Review the code and return Issue, Impact, and Fix.
Example Input:
    public int divide(int a, int b) {
        return a / b;
    }
Example Output:
  Issue: The method does not check whether b is zero.
  Impact: A zero value causes an ArithmeticException.
  Fix: Validate b before division and throw a clear exception.
Actual Input:
    public String getName(User user) {
        return user.getName();
    }

Expected output:

Prompt
Issue: The method does not check whether user is null.
Impact: A null value causes a NullPointerException.
Fix: Validate the user object before calling getName.

Important rules for one-shot code generation

  • Use a correct example.
  • Mention the programming language.
  • Specify the expected language version.
  • State whether external libraries are allowed.
  • Show the required naming style.
  • Include validation in the example when validation is required.
  • Define the required output type.
  • Ask for code only when explanations are not needed.
  • Test generated code before using it in production.
  • Never assume generated code is secure without review.

Advantages of One-Shot Prompting

One-shot prompting provides more guidance than zero-shot prompting while using less prompt space than few-shot prompting.

1. Shows the expected pattern

A single example helps the model understand what transformation should be performed.

Instead of only describing a task, the prompt demonstrates it.

2. Improves output formatting

The example can show:

  • Required headings
  • Field order
  • JSON structure
  • Label format
  • Sentence length
  • Bullet style
  • Code structure

This reduces formatting mistakes.

3. Reduces ambiguity

Some instructions can be understood in several ways.

For example:

Prompt
Make the sentence professional.

The word professional may mean formal, polite, concise, or business-friendly.

One example makes the expected meaning clearer.

4. Uses fewer tokens than few-shot prompting

Few-shot prompts contain several examples. One-shot prompts use only one, making them shorter and often less expensive.

5. Useful for simple pattern-based tasks

One-shot prompting works well for:

  • Label classification
  • Field extraction
  • Text rewriting
  • Format conversion
  • Basic summarisation
  • Simple content generation
  • Basic code generation

6. Helps maintain output consistency

The model often follows the structure shown in the example, producing more consistent results across similar requests.

7. Easy to create

A one-shot prompt is usually easy to build because it requires only one correct example.

8. Supports custom output formats

A user can demonstrate a format that may be difficult to explain using instructions alone.

Example:

Prompt
Example Output:
  Risk Level: High
  Reason: Public access is enabled
  Recommended Action: Disable public access

The model can follow the same custom format for new data.

9. Useful for domain-specific tasks

A domain example can show specialized terms and required output.

Domains include:

  • Healthcare
  • Banking
  • Software engineering
  • Education
  • Legal document review
  • Customer support
  • Marketing
  • Human resources

10. Improves style control

The example can guide the model to produce text that is:

  • Short
  • Detailed
  • Formal
  • Friendly
  • Technical
  • Beginner-friendly
  • Action-focused

Limitations of One-Shot Prompting

One-shot prompting is useful, but one example may not fully describe a complex task.

1. One example may not cover all cases

A single example usually shows only one type of input.

It may not explain how to handle:

  • Missing data
  • Invalid values
  • Mixed categories
  • Unusual input
  • Conflicting information
  • Multiple correct outputs

2. Poor examples produce poor results

If the example is incorrect, unclear, or incomplete, the model may learn the wrong pattern.

Example:

Prompt
Task: Extract the city.
Example Input: Rahul lives in Pune.
Example Output: Rahul

The example output is incorrect. The model may return a person's name instead of a city.

3. The model may copy example details

The model may accidentally reuse:

  • Names
  • Numbers
  • Dates
  • Categories
  • Code variables
  • Product details

This risk increases when the actual input is unclear.

4. Complex tasks may need more examples

One example may not be enough for tasks involving:

  • Several categories
  • Many formatting rules
  • Complex reasoning
  • Multiple edge cases
  • Specialized business logic
  • Ambiguous language

Few-shot prompting may work better in such cases.

5. Example bias

The example may strongly influence the output.

If the example is very formal, the model may produce formal text even when the actual input needs a friendly response.

6. Limited error handling

A normal example does not show what to do when the input is incomplete or invalid.

Fallback instructions should be added separately.

Example:

Prompt
If the required information is missing, return Insufficient Information.
Do not guess missing values.

7. More prompt length than zero-shot prompting

Although one-shot prompts are shorter than few-shot prompts, they still use more tokens than zero-shot prompts.

8. Format following is not guaranteed

The model may still add:

  • Explanations
  • Extra headings
  • Markdown
  • Notes
  • Warnings
  • Unrequested fields

Clear instructions such as Return only the JSON object can reduce this problem.

9. Code may contain errors

A correct example does not guarantee that generated code will be:

  • Secure
  • Efficient
  • Tested
  • Compatible
  • Free from bugs
  • Suitable for production

Human review is still required.

10. Sensitive information risk

Examples should not contain:

  • Real passwords
  • API keys
  • Private customer data
  • Confidential company details
  • Personal health information
  • Financial account details

Use fictional or masked data in examples.

One-Shot Prompt Examples

The following examples demonstrate one-shot prompting across different tasks.

Example 1: Text simplification

Prompt
Task: Rewrite the technical sentence in simple language.
Example Input: The system authenticates users before granting access to protected resources.
Example Output: The system checks who the user is before allowing access to protected information.
Actual Input: The application caches frequently requested data to reduce database load.

Expected output:

Prompt
The application stores commonly requested data temporarily so that it does not need to contact the database every time.

Example 2: Sentiment classification

Prompt
Task: Classify the review as Positive, Negative, or Neutral.
Return only the label.
Example Input: The delivery was quick and the product quality was excellent.
Example Output: Positive
Actual Input: The item arrived with a broken screen.

Expected output:

Prompt
Negative

Example 3: Keyword extraction

Prompt
Task: Extract the main technologies as a comma-separated list.
Example Input: The backend uses Java, Spring Boot, MySQL, and Redis.
Example Output: Java, Spring Boot, MySQL, Redis
Actual Input: The analytics service uses Python, Pandas, PostgreSQL, and Docker.

Expected output:

Prompt
Python, Pandas, PostgreSQL, Docker

Example 4: Professional rewriting

Prompt
Task: Rewrite the message in a polite and professional tone.
Example Input: You forgot to attach the file.
Example Output: It appears that the file was not attached. Could you please send it again?
Actual Input: Your team did not fix the issue.

Expected output:

Prompt
It appears that the issue has not yet been resolved. Could your team please review it again?

Example 5: Summarisation

Prompt
Task: Summarize the text in one sentence.
Example Input: The development team completed the login feature, tested it successfully, and deployed it to the test environment.
Example Output: The login feature was completed, tested, and deployed to the test environment.
Actual Input: The support team investigated the payment issue, found a gateway timeout, and applied a configuration fix.

Expected output:

Prompt
The support team identified a payment gateway timeout and resolved it through a configuration change.

Example 6: Data conversion

Prompt
Task: Convert the date into YYYY-MM-DD format.
Example Input: 5 August 2026
Example Output: 2026-08-05
Actual Input: 21 December 2026

Expected output:

Prompt
2026-12-21

Example 7: JSON generation

Prompt
Task: Convert the employee information into JSON.
Example Input: Name: Asha, Role: Tester, Experience: 3 years
Example Output:
  {
    "name": "Asha",
    "role": "Tester",
    "experience_years": 3
  }
Actual Input: Name: Rohan, Role: Java Developer, Experience: 5 years

Expected output:

JSON
{
  "name": "Rohan",
  "role": "Java Developer",
  "experience_years": 5
}

Example 8: SQL generation

Prompt
Task: Write an SQL query based on the requirement.
Example Requirement: Find all active employees.
Example Output:
    SELECT *
    FROM employees
    WHERE status = 'ACTIVE';
Actual Requirement: Find all pending orders.

Expected output:

SQL
SELECT *
FROM orders
WHERE status = 'PENDING';

Example 9: Java code generation

Prompt
Task: Generate a Java method using camelCase naming.
Example Requirement: Check whether a number is positive.
Example Output:
    public static boolean isPositive(int number) {
        return number > 0;
    }
Actual Requirement: Check whether a number is even.

Expected output:

Prompt
public static boolean isEven(int number) {
    return number % 2 == 0;
}

Example 10: Python code generation

Python
Task: Generate a Python function with type hints.
Example Requirement: Return the square of a number.
Example Output:
    def calculate_square(number: float) -> float:
        return number * number
Actual Requirement: Return the cube of a number.

Expected output:

Python
def calculate_cube(number: float) -> float:
    return number * number * number

Example 11: Support response generation

Prompt
Task: Write a helpful customer support response.
Example Input: The customer says the password reset link has expired.
Example Output: Please request a new password reset link from the login page. The new link should be used within the allowed time period.
Actual Input: The customer says the verification code is not arriving.

Expected output:

Prompt
Please confirm that the registered phone number or email address is correct and request a new verification code. Also check the spam folder and wait a few minutes before trying again.

Example 12: Bug report formatting

Prompt
Task: Convert the issue into a structured bug report.
Example Input: The application crashes when the user uploads a file larger than 20 MB.
Example Output:
  Title: Application crashes during large file upload
  Steps: Upload a file larger than 20 MB
  Actual Result: Application crashes
  Expected Result: Application should reject the file with a clear message
Actual Input: The login button remains disabled after the user enters a valid email and password.

Expected output:

Prompt
Title: Login button remains disabled with valid credentials
Steps: Enter a valid email and password
Actual Result: Login button remains disabled
Expected Result: Login button should become enabled

One-Shot Prompt Template

A reusable one-shot prompt template helps maintain a clear and stable structure.

General one-shot template

Prompt
Task:
[Clearly describe what the model must do.]
Rules:
[Rule 1]
[Rule 2]
[Rule 3]
Example Input:
[Provide one representative input.]
Example Output:
[Provide the correct expected output.]
Actual Input:
[Insert the new input.]
Output Requirement:
[State the exact required output format.]

Classification template

Prompt
Task:
Classify the actual input into one category.
Categories:
[Category 1]
[Category 2]
[Category 3]
Rules:
Return only the category name.
Do not add an explanation.
Example Input:
[Sample input]
Example Output:
[Correct category]
Actual Input:
[Input to classify]

Extraction template

Prompt
Task:
Extract the required fields from the actual input.
Required Fields:
[Field 1]
[Field 2]
[Field 3]
Rules:
Use Not Available when a value is missing.
Do not guess missing information.
Preserve values from the actual input.
Example Input:
[Sample text]
Example Output:
  [Field 1]: [Value]
  [Field 2]: [Value]
  [Field 3]: [Value]
Actual Input:
[Text to process]

Content generation template

Prompt
Task:
Create [content type] for [target audience].
Requirements:
Use a [tone] tone.
Keep the output under [word count] words.
Include [required elements].
Do not include [prohibited elements].
Example Input:
[Sample topic or source information]
Example Output:
[Complete example response]
Actual Input:
[New topic or source information]

Code generation template

Prompt
Task:
Generate code for the actual requirement.
Programming Language:
[Language and version]
Requirements:
Follow the style shown in the example.
Use clear variable and method names.
Add required validation.
Do not use external libraries unless allowed.
Return only the code.
Example Requirement:
[Sample coding requirement]
Example Output:
    [Correct sample code]
Actual Requirement:
[New coding requirement]

JSON output template

Prompt
Task:
Convert the actual input into JSON.
Rules:
Use valid JSON.
Use the exact field names shown in the example.
Do not add fields.
Use null for missing values.
Example Input:
[Sample text]
Example Output:
  {
    "field_one": "value",
    "field_two": "value"
  }
Actual Input:
[New text]

Best Practices for One-Shot Prompting

Use a clear instruction

The model should understand the task before reading the example.

Weak instruction:

Prompt
Process this text.

Better instruction:

Prompt
Extract the customer's name, order number, and complaint from the text.

Use one high-quality example

The example should accurately represent the expected task.

A correct and relevant example is more useful than a complicated example.

Make the instruction and example agree

Do not ask for one output style and demonstrate another.

Incorrect:

Prompt
Instruction: Return only the label.
Example Output: The label is Positive because the customer liked the service.

Correct:

Prompt
Instruction: Return only the label.
Example Output: Positive

Define the output format

State whether the output should be:

  • Plain text
  • JSON
  • XML
  • Markdown
  • A table
  • A numbered list
  • A category label
  • Source code

Include fallback instructions

Tell the model what to do when the answer is not available.

Example:

Prompt
If the text does not contain the required information, return Not Found.
Do not create or guess information.

Keep the example relevant

For technical text, use a technical example.

For customer support classification, use a customer support example.

For code generation, use the same language and coding style.

Avoid unnecessary information

Too much context can hide the main pattern.

Include only information that helps the model complete the task.

Test with different inputs

Test the prompt using:

  • Normal input
  • Short input
  • Long input
  • Missing information
  • Invalid input
  • Unusual wording

Check output consistency

Run the prompt several times when consistency is important.

A probabilistic model may produce slightly different outputs across runs.

Add validation rules

For structured output, define strict rules.

Example:

Prompt
Return valid JSON only.
Do not include Markdown.
Do not add comments.
Use null for missing values.

Common One-Shot Prompting Mistakes

Mistake 1: Using an unrelated example

The example does not represent the actual task.

Mistake 2: Providing an incorrect example output

The model may repeat the same error.

Mistake 3: Mixing the example with actual input

Without labels or separators, the model may not know which content to process.

Mistake 4: Using inconsistent formatting

Different field names and structures make the pattern unclear.

Mistake 5: Demonstrating only an edge case

A rare example may not teach the normal task correctly.

Mistake 6: Asking for a complex task with one simple example

Some tasks need multiple examples to cover different patterns.

Mistake 7: Forgetting missing-value rules

The model may guess information when the source does not contain it.

Mistake 8: Including sensitive data

Real confidential data should not be used as example content.

Mistake 9: Not defining the output length

The model may generate more detail than required.

Mistake 10: Trusting generated code without testing

Generated code must be reviewed, tested, and checked for security issues.

One-Shot Prompting vs Zero-Shot Prompting

PointZero-shot promptingOne-shot prompting
ExamplesNo exampleOne example
Prompt lengthShorterSlightly longer
Pattern guidanceBased only on instructionsBased on instructions and demonstration
Format controlModerateBetter
Best forSimple tasksTasks needing a clear pattern
Preparation effortLowModerate
Risk of example biasNonePresent

Zero-shot example

Prompt
Classify the message as Billing, Technical, or Account.
Message: I cannot log in after changing my password.

One-shot example

Prompt
Classify the message as Billing, Technical, or Account.
Example Input: I was charged twice for the same subscription.
Example Output: Billing
Actual Input: I cannot log in after changing my password.

The one-shot version provides stronger guidance about the required output.

One-Shot Prompting vs Few-Shot Prompting

PointOne-shot promptingFew-shot prompting
Number of examplesOneTwo or more
Token usageLowerHigher
Pattern coverageLimitedBroader
Edge-case handlingLimitedBetter
Prompt creationEasierMore effort
Best forSimple stable patternsComplex or varied patterns

Use one-shot prompting when:

  • One example clearly explains the task
  • Inputs follow a common pattern
  • The output structure is simple
  • Prompt length should remain small

Use few-shot prompting when:

  • Several categories are difficult to distinguish
  • Inputs have different formats
  • Edge cases are common
  • The output requires complex reasoning
  • One example does not provide enough guidance

When to Use One-Shot Prompting

One-shot prompting is suitable when:

  • A zero-shot prompt gives inconsistent output
  • The output format is difficult to explain
  • One example can clearly show the task
  • The task follows a simple transformation pattern
  • A specific style is required
  • The model must return structured data
  • The prompt should remain shorter than a few-shot prompt

Common use cases include:

  • Sentiment classification
  • Intent detection
  • Named information extraction
  • Data formatting
  • Text rewriting
  • Product description writing
  • Email response generation
  • SQL query generation
  • Basic function generation
  • Bug report formatting
  • Resume information extraction
  • Customer support routing

When One-Shot Prompting May Not Be Enough

One-shot prompting may not be enough when:

  • The task has many possible patterns
  • Categories overlap
  • The input contains several edge cases
  • Detailed domain reasoning is required
  • The output depends on multiple business rules
  • High accuracy is required for sensitive decisions
  • The example cannot represent the full task
  • The task requires external or current information

In such cases, consider:

  • Few-shot prompting
  • Retrieval-augmented generation
  • Tool usage
  • Rule-based validation
  • Structured output schemas
  • Human review
  • Model fine-tuning for large repeated workloads

One-Shot Prompt Validation Checklist

Before using a one-shot prompt, verify the following points:

  • The task instruction is clear.
  • The prompt contains exactly one example.
  • The example input is relevant.
  • The example output is correct.
  • The example follows every rule.
  • The actual input is clearly separated.
  • The output format is defined.
  • Missing-value behaviour is defined.
  • The model is told not to guess facts.
  • The model is told not to copy example values.
  • Sensitive information is removed.
  • The prompt has been tested with multiple inputs.
  • Generated code is reviewed and tested.
  • The prompt does not contain conflicting instructions.
  • The result meets the required completion criteria.

Complete One-Shot Prompt Example

The following prompt combines instructions, rules, one demonstration, actual input, and output requirements.

Prompt
Role:
Act as a technical support ticket classifier.
Task:
Classify the actual support message into one category.
Categories:
Account Access
Billing
Technical Issue
Feature Request
Rules:
Return only one category name.
Do not provide an explanation.
Use the example only to understand the task.
Do not copy details from the example.
Example Input:
I was charged for the premium plan twice this month.
Example Output:
Billing
Actual Input:
The application freezes whenever I open the analytics dashboard.

Expected output:

Prompt
Technical Issue

This prompt works well because it:

  • Defines the model's role
  • Explains the task
  • Lists the valid categories
  • Defines strict output rules
  • Includes one relevant example
  • Separates the example from the actual input
  • Prevents copying
  • Specifies the exact output style

Conclusion

One-shot prompting is a practical method for guiding an AI model with one clear example.

It is more informative than zero-shot prompting and shorter than few-shot prompting. The example helps the model understand the required transformation, output format, style, tone, and level of detail.

A successful one-shot prompt should contain:

  1. A clear task instruction
  2. One correct and representative example
  3. A properly formatted example output
  4. A clearly separated actual input
  5. Exact output rules
  6. Fallback instructions for missing information

The example is the most important part of a one-shot prompt. A strong example improves clarity and consistency, while a weak example can guide the model in the wrong direction.

One-shot prompting is especially effective for classification, extraction, rewriting, formatting, content generation, and basic code generation. For tasks with several patterns, edge cases, or complex rules, few-shot prompting or other advanced methods may provide better results.

Frequently Asked Questions

What is one-shot prompting?

One-shot prompting is a technique where you provide exactly one example to show an AI model how to complete a task. The model uses the example to understand the expected pattern, format, and style for the actual input.

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

Zero-shot prompting provides only instructions with no examples. One-shot prompting adds one complete input-output example to demonstrate the expected pattern, which improves format control and reduces ambiguity.

When should I use one-shot prompting instead of few-shot prompting?

Use one-shot prompting when one clear example is enough to explain the task, the output structure is simple, and you want to keep the prompt short. Use few-shot prompting for complex tasks with multiple patterns, edge cases, or categories that are difficult to distinguish.

Can one-shot prompting be used for code generation?

Yes. One-shot code generation provides one code example showing the desired language, naming style, structure, validation, and formatting. The model then applies the same pattern to a new requirement.

What makes a good one-shot example?

A good example is correct, clear, relevant, complete, properly formatted, similar to the actual task, and based on the most common case. It should demonstrate the exact transformation and output format you expect.

How do I prevent the model from copying values from the example?

Add explicit instructions such as: "Use the example only to understand the format. Do not copy names, numbers, or facts from the example. Process only the actual input."

What are the main limitations of one-shot prompting?

One example may not cover all cases, poor examples produce poor results, the model may copy example details, complex tasks may need more examples, example bias can influence output style, and format following is not guaranteed.

How should I format the example in a one-shot prompt?

Use clear labels (Task, Example Input, Example Output, Actual Input), consistent field names, stable structure, and separators. Keep the example close to the actual input and use the same output format you expect in the final answer.

Can one-shot prompting handle missing information?

Yes, but you must define the missing-value behaviour in the example or rules. For example: "Use Not Available when a value is missing. Do not guess missing information."

Is one-shot prompting suitable for all tasks?

No. One-shot prompting works best for simple, stable patterns like classification, extraction, rewriting, and basic code generation. Complex tasks with multiple patterns, edge cases, or ambiguous language may require few-shot prompting or other methods.