Module 1 · Chapter 5 Prompt Engineering Foundations › Anatomy of an Effective Prompt

Examples

Telling a model to "write a concise product description" leaves concise open to interpretation - one response might be a sentence, another a full paragraph. A single input-output example turns that vague word into an observable pattern the model can actually copy, which is why examples are one of the most reliable levers in prompt engineering.

Quick takeaway: a prompt with no examples is zero-shot, one example is one-shot, and several examples is few-shot - and the model tends to follow demonstrated examples even when they conflict with written instructions. That makes example accuracy, consistency, and labeling non-negotiable: an unverified or mislabeled example can teach the model the wrong pattern just as effectively as a correct one teaches the right pattern.

Introduction

Examples are one of the most powerful components of an effective prompt. They show the language model what kind of response is expected instead of relying only on written instructions.

A prompt may explain the task clearly, but the model can still interpret details such as tone, format, depth, terminology, classification rules, or output structure differently. Examples reduce this ambiguity by demonstrating the expected behavior.

In prompt engineering, examples are commonly used to guide:

  • Output structure
  • Writing style
  • Classification logic
  • Data transformation
  • Reasoning pattern
  • Response length
  • Formatting conventions
  • Technical depth
  • Handling of special cases
  • Consistency across multiple outputs

Examples are especially valuable when a task cannot be described accurately through instructions alone.

What Are Examples in Prompt Engineering?

Examples are sample input-output pairs included inside a prompt to demonstrate how the model should perform a task.

A typical example contains:

  1. A sample input
  2. The expected output
  3. Optional explanation or reasoning
  4. A clear separator between examples
  5. A final input that the model must process

Basic structure:

Prompt
# Example showing the expected behavior
Input: Convert "hello world" to title case.
Output: Hello World
# Actual task
Input: Convert "prompt engineering guide" to title case.
Output:

The model observes the relationship between the example input and output and applies the same pattern to the actual task.

Why Examples Improve Prompt Quality

Examples improve prompt quality because they convert abstract instructions into observable patterns.

Consider the following instruction:

Prompt
Write a concise product description.

The word concise is subjective. One model response may contain one sentence, while another may contain an entire paragraph.

An example makes the requirement measurable:

Prompt
# Example of the required length and style
Product: Wireless Mouse
Description: A lightweight wireless mouse with silent clicks, adjustable sensitivity, and reliable USB connectivity.
# Actual task
Product: Mechanical Keyboard
Description:

The example demonstrates:

  • Approximate response length
  • Sentence structure
  • Tone
  • Feature-focused wording
  • Level of technical detail

Examples and In-Context Learning

When examples are included in a prompt, the model uses a process commonly called in-context learning.

In-context learning means that the model identifies patterns from the information provided in the current prompt and uses those patterns to generate the response.

The examples do not permanently retrain or modify the model. They influence only the current interaction or the available conversation context.

For example:

Prompt
# Example 1
Input: The application starts quickly.
Sentiment: Positive
# Example 2
Input: The application crashes every few minutes.
Sentiment: Negative
# Actual task
Input: The interface is attractive, but navigation is confusing.
Sentiment:

The examples establish that the task is sentiment classification and that the output should be a short category label.

Zero-Shot, One-Shot, and Few-Shot Prompting

Examples determine whether a prompt is zero-shot, one-shot, or few-shot.

Zero-Shot Prompting

Zero-shot prompting provides instructions without any examples.

Example:

Prompt
Classify the following customer review as Positive, Negative, or Neutral.
Review: The product works as expected, but the packaging was damaged.
Classification:

Zero-shot prompting works well when:

  • The task is straightforward
  • The output format is simple
  • The model already understands the task
  • There are no complex classification rules
  • Minor output variations are acceptable

Its main advantage is that it uses fewer tokens.

Its limitation is that the model must interpret all requirements from instructions alone.

One-Shot Prompting

One-shot prompting provides one example before the actual task.

Example:

Prompt
# Example
Review: The laptop is fast and has excellent battery life.
Classification: Positive
# Actual task
Review: The application is useful, but it frequently freezes.
Classification:

One-shot prompting works well when:

  • One example clearly communicates the expected pattern
  • The task has a predictable output structure
  • Token usage must remain low
  • The task does not contain many edge cases

However, a single example may unintentionally bias the model toward the example's wording, category, or style.

Few-Shot Prompting

Few-shot prompting provides multiple examples before the actual task.

Example:

Prompt
# Example 1
Review: The interface is clean and easy to use.
Classification: Positive
# Example 2
Review: The application is neither impressive nor disappointing.
Classification: Neutral
# Example 3
Review: The software crashes whenever I upload a file.
Classification: Negative
# Actual task
Review: The features are useful, although the setup process is difficult.
Classification:

Few-shot prompting is useful when:

  • The task contains multiple categories
  • The distinction between categories is subtle
  • A specific writing style is required
  • The output must follow a strict structure
  • The task includes domain-specific rules
  • The model must handle several input patterns

Few-shot prompts generally produce more consistent results than zero-shot prompts, but they consume more context tokens.

Main Purposes of Examples

Demonstrating Output Format

Examples can show the exact structure required in the response.

Instruction-only prompt:

Prompt
Extract the product name, price, and availability from the text.

This instruction does not specify how the extracted data should be formatted.

Example-guided prompt:

Prompt
# Example
Text: The SmartWatch Pro is available for ₹4,999 and is currently in stock.
Product Name: SmartWatch Pro
Price: ₹4,999
Availability: In Stock
# Actual task
Text: The NoiseFree Headphones cost ₹2,499 and are currently unavailable.
Product Name:
Price:
Availability:

The example makes the expected field names and output order clear.

Demonstrating Writing Style

Examples can establish tone, vocabulary, sentence length, and communication style.

Prompt
# Example of the required professional tone
Input: Tell the client that the deployment has been delayed.
Output: The deployment has been rescheduled due to additional validation requirements. We will share the revised completion date after the current testing cycle.
# Actual task
Input: Tell the client that the database migration needs more testing.
Output:

The model is likely to follow the same professional and neutral tone.

Demonstrating Classification Rules

Examples are useful when category boundaries are difficult to explain.

Prompt
# Example 1
Message: I forgot my account password.
Category: Account Access
# Example 2
Message: My payment was deducted twice.
Category: Billing
# Example 3
Message: The application closes after login.
Category: Technical Issue
# Actual task
Message: I cannot sign in even after resetting my password.
Category:

The examples show how messages should be mapped to supported categories.

Demonstrating Data Transformation

Examples can show how input data should be converted into another representation.

Prompt
# Example
Input: John Smith, Software Engineer, Pune
Output: {"name":"John Smith","role":"Software Engineer","location":"Pune"}
# Actual task
Input: Priya Sharma, Data Analyst, Mumbai
Output:

This example communicates:

  • Required JSON structure
  • Property names
  • Property order
  • String formatting
  • Absence of additional explanation

Demonstrating Level of Detail

Examples help define how deeply the model should explain a concept.

Prompt
# Example
Question: What is encapsulation?
Answer: Encapsulation is an object-oriented programming principle that combines data and related methods inside a class while restricting direct access to internal state. In Java, it is commonly implemented using private fields and public getter or setter methods.
# Actual task
Question: What is inheritance?
Answer:

The model can infer the desired explanation length and technical level.

Demonstrating Domain-Specific Terminology

Examples teach the model which terms should be used in a specific domain.

Prompt
# Example
Finding: The API accepts requests without validating the authentication token.
Severity: Critical
Impact: An unauthorized user may access protected resources.
Recommendation: Validate the token signature, expiration time, issuer, and intended audience before authorizing the request.
# Actual task
Finding: The application stores passwords in plain text.
Severity:
Impact:
Recommendation:

The example establishes a cybersecurity-oriented vocabulary and reporting structure.

Types of Examples Used in Prompts

Positive Examples

Positive examples demonstrate the correct output.

Prompt
# Positive example
Input: Convert the sentence to active voice: The report was prepared by the analyst.
Output: The analyst prepared the report.

Positive examples are useful for showing:

  • Correct formatting
  • Desired style
  • Expected transformation
  • Valid classifications
  • Appropriate response length

Negative Examples

Negative examples show what the model should avoid.

Prompt
# Incorrect output
Input: Summarize the paragraph in one sentence.
Output: Here is a detailed explanation followed by several supporting points.
# Reason
The output is incorrect because it does not follow the one-sentence requirement.
# Correct output
Output: The paragraph explains how automation reduces repetitive manual work.

Negative examples are helpful when common mistakes are predictable.

However, the prompt must clearly label incorrect examples. Otherwise, the model may treat them as patterns to follow.

Contrastive Examples

Contrastive examples show a weak response and a strong response for the same task.

Prompt
# Weak example
Question: Explain dependency injection.
Answer: Dependency injection is a useful programming technique.
# Strong example
Question: Explain dependency injection.
Answer: Dependency injection is a design technique in which an object's dependencies are supplied from outside rather than created internally, reducing coupling and improving testability.
# Actual task
Question: Explain inversion of control.
Answer:

Contrastive examples help communicate quality expectations that are difficult to express with general instructions.

Boundary Examples

Boundary examples demonstrate how to handle cases near the limit between two categories.

Prompt
# Example 1
Score: 79
Result: Fail
# Example 2
Score: 80
Result: Pass
# Actual task
Score: 80
Result:

These examples are important for:

  • Threshold-based classification
  • Eligibility rules
  • Scoring systems
  • Date boundaries
  • Validation limits
  • Numeric ranges

Edge-Case Examples

Edge-case examples demonstrate how unusual, empty, incomplete, or ambiguous inputs should be handled.

Prompt
# Example 1
Input: user@example.com
Result: Valid
# Example 2
Input:
Result: Invalid - Email address is missing
# Example 3
Input: user@
Result: Invalid - Domain is incomplete
# Actual task
Input: @example.com
Result:

Edge-case examples improve reliability when real-world input may be imperfect.

Examples with Explanations

Some tasks benefit from examples that include both an answer and a brief explanation.

Prompt
# Example
Question: Which Java collection does not allow duplicate elements?
Answer: Set
Explanation: A Set stores unique elements and rejects duplicates according to its equality rules.
# Actual task
Question: Which Java collection stores key-value pairs?
Answer:
Explanation:

Explanations help the model understand the rule behind the answer instead of copying only the surface structure.

How to Structure Examples in a Prompt

A well-structured example should clearly separate instructions, sample data, expected output, and the actual task.

Recommended structure:

Prompt
# Role
You are a technical content editor.
# Task
Rewrite each sentence in clear and professional English.
# Rules
Preserve the original meaning.
Do not add new information.
Return only the rewritten sentence.
# Example 1
Input: Application not working because database have issue.
Output: The application is not working because the database has an issue.
# Example 2
Input: User cannot login after password changed.
Output: The user cannot log in after changing the password.
# Actual task
Input: Server stopped because memory usage was very high.
Output:

This structure prevents different parts of the prompt from becoming mixed together.

Use Consistent Labels

Use the same labels in every example.

Good structure:

Prompt
# Example 1
Input: Java supports object-oriented programming.
Output: Java supports object-oriented programming.
# Example 2
Input: Python support multiple programming paradigms.
Output: Python supports multiple programming paradigms.

Inconsistent structure:

Prompt
Sample: Java supports object-oriented programming.
Corrected Text: Java supports object-oriented programming.
Sentence Two: Python support multiple programming paradigms.
Final Result: Python supports multiple programming paradigms.

Consistent labels help the model identify the pattern more accurately.

Use Clear Separators

Separators help distinguish one example from another.

Common separators include:

  • Example numbers
  • Section headings
  • Input and output labels
  • Triple hyphens
  • XML-style tags
  • Descriptive field names

Example using XML-style sections:

Prompt
<example>
    <input>The order arrived early.</input>
    <output>Positive</output>
</example>
<example>
    <input>The package was empty.</input>
    <output>Negative</output>
</example>
<task>
    <input>The delivery was on time, but the box was damaged.</input>
    <output></output>
</task>

Structured delimiters are particularly useful when inputs contain long paragraphs or multiple fields.

Keep Examples Relevant

Every example should represent the actual task.

Irrelevant examples can introduce unnecessary patterns and reduce response quality.

For a technical interview answer generator, relevant examples should demonstrate:

  • Correct technical terminology
  • Interview-friendly explanation
  • Appropriate answer length
  • Practical examples
  • Important distinctions
  • Common follow-up points

An unrelated creative-writing example would not help the model complete the task.

Keep Examples Representative

Examples should represent the kinds of inputs that the model will process in actual use.

For a customer support classifier, include examples such as:

  • Billing issue
  • Login issue
  • Technical failure
  • Refund request
  • Account cancellation
  • Feature request

Using only one type of example may cause the model to overgeneralize.

Maintain Balanced Examples

For classification tasks, examples should be reasonably balanced across categories.

Unbalanced examples:

Prompt
Positive examples: 8
Neutral examples: 1
Negative examples: 1

The model may become biased toward the most frequently demonstrated category.

A better set would include multiple representative examples for each category.

Balance does not always require an identical number of examples, but every category should be demonstrated clearly.

Use Diverse Wording

Examples should vary in wording while preserving the same task pattern.

Poor example set:

Prompt
Input: The product is excellent.
Output: Positive
Input: The service is excellent.
Output: Positive
Input: The application is excellent.
Output: Positive

Improved example set:

Prompt
Input: The product exceeded my expectations.
Output: Positive
Input: Customer support resolved the issue immediately.
Output: Positive
Input: The application is easy to navigate and performs reliably.
Output: Positive

Diverse wording teaches the underlying relationship instead of encouraging phrase matching.

Avoid Overly Complex Examples

An example should be complex enough to demonstrate the requirement but simple enough to understand quickly.

Overly complicated examples may introduce:

  • Unnecessary entities
  • Conflicting instructions
  • Irrelevant details
  • Multiple tasks in one example
  • Ambiguous reasoning
  • Excessive output length

Start with a clear example and add complexity only when the task requires it.

Place Examples Before the Actual Task

Examples should normally appear before the final input.

Recommended order:

  1. Role
  2. Background context
  3. Task
  4. Rules
  5. Output requirements
  6. Examples
  7. Actual input

Example:

Prompt
# Role
You are a Java interview trainer.
# Task
Answer the question in an interview-friendly format.
# Rules
Keep the answer technically accurate.
Use simple language.
Include one practical example.
# Example
Question: What is method overloading?
Answer: Method overloading allows a class to define multiple methods with the same name but different parameter lists. The compiler selects the appropriate method based on the supplied arguments. For example, a class may define add(int a, int b) and add(double a, double b).
# Actual task
Question: What is method overriding?
Answer:

Placing examples after the actual input can make the prompt structure less predictable.

Match the Example Format to the Required Output

The actual response generally follows the formatting shown in the examples.

When the required output is JSON, examples should use valid JSON.

Prompt
# Example
Input: Rahul, 28, Developer
Output: {"name":"Rahul","age":28,"profession":"Developer"}
# Actual task
Input: Sneha, 31, Designer
Output:

When the required output is a table, examples should use a table.

When the required output is a numbered list, examples should use a numbered list.

The model usually follows demonstrated formatting more reliably than formatting described only in prose.

Practical Example: Text Classification

Prompt
# Role
You are a customer support ticket classifier.
# Task
Classify each ticket into one category.
# Allowed categories
Account Access
Billing
Technical Issue
Refund
Feature Request
# Example 1
Ticket: I was charged twice for the same subscription.
Category: Billing
# Example 2
Ticket: The application crashes whenever I upload an image.
Category: Technical Issue
# Example 3
Ticket: Please add support for exporting reports to Excel.
Category: Feature Request
# Actual task
Ticket: I cannot sign in after changing my password.
Category:

Why this prompt is effective:

  • The role is clearly defined.
  • The available categories are restricted.
  • Multiple categories are demonstrated.
  • Each example uses identical labels.
  • The actual task follows the same pattern.
  • The expected response is short and predictable.

Practical Example: Information Extraction

Prompt
# Task
Extract the candidate's name, primary skill, experience, and location.
# Output format
Return valid JSON only.
# Example
Input: Amit is a Java developer from Pune with five years of professional experience.
Output: {"name":"Amit","primarySkill":"Java","experienceYears":5,"location":"Pune"}
# Actual task
Input: Neha is a Python engineer based in Bengaluru with three years of industry experience.
Output:

The example defines both the extraction logic and the exact JSON schema.

Practical Example: Content Generation

Prompt
# Role
You are a technical educator.
# Task
explain the given programming concept for beginners.
# Rules
Start with a direct definition.
Explain why the concept is used.
Include one practical example.
Keep the response between 100 and 140 words.
# Example
Topic: Java Interface
Response: A Java interface is a reference type that defines a contract for classes. It specifies methods that implementing classes must provide. Interfaces are used to support abstraction, reduce coupling, and allow unrelated classes to follow the same behavior. For example, a PaymentService interface may define a pay() method, while CreditCardPayment and UpiPayment provide different implementations. The calling code can depend on PaymentService instead of a specific payment class. This makes the application easier to extend, test, and maintain.
# Actual task
Topic: Java Abstract Class
Response:

The example demonstrates structure, depth, terminology, and approximate length.

Practical Example: Data Formatting

Prompt
# Task
Convert the supplied product information into the required format.
# Required format
Product: value
Price: value
Status: value
# Example
Input: The Smart Speaker costs ₹3,499 and is available.
Product: Smart Speaker
Price: ₹3,499
Status: Available
# Actual task
Input: The 27-inch Monitor costs ₹18,999 and is currently out of stock.
Product:
Price:
Status:

This prompt is suitable when the output must remain human-readable instead of using JSON.

Practical Example: Code Generation

Prompt
# Role
You are a senior Java developer.
# Task
Write a Java method based on the requirement.
# Rules
Use meaningful variable names.
Validate invalid input.
Do not use external libraries.
Return only the method.
# Example
Requirement: Return the larger of two integers.
Output:
    public static int findMaximum(int firstNumber, int secondNumber) {
        return Math.max(firstNumber, secondNumber);
    }
# Actual task
Requirement: Return the sum of all positive numbers in an integer array.
Output:

The example communicates naming style, indentation, method visibility, and response scope.

Practical Example: SQL Generation

Prompt
# Role
You are a database developer.
# Task
Write a MySQL query for the given requirement.
# Rules
Use explicit column names.
Use readable aliases.
Do not use SELECT *.
Return only the SQL query.
# Example
Requirement: Find active employees from the sales department.
Output:
    SELECT employee_id, employee_name, department_name
    FROM employees
    WHERE employment_status = 'ACTIVE'
      AND department_name = 'Sales';
# Actual task
Requirement: Find completed orders placed during the last 30 days.
Output:

The example shows the expected SQL style without overexplaining it.

Practical Example: Rewriting

Prompt
# Task
Rewrite the sentence in clear and professional English.
# Rules
Preserve the original meaning.
Correct grammar and spelling.
Do not add new facts.
Return only the rewritten sentence.
# Example
Input: We not completed deployment because server issue is coming.
Output: We could not complete the deployment because of a server issue.
# Actual task
Input: Client not approved design so development is stopped.
Output:

The example demonstrates the level of correction and expected tone.

Practical Example: Summarization

Prompt
# Task
Summarize the text in one sentence.
# Rules
Include the main problem and final outcome.
Use no more than 30 words.
# Example
Input: The application experienced slow response times because several database queries were not indexed. After adding the required indexes, the average response time decreased significantly.
Output: Adding missing database indexes resolved the application's slow response-time problem.
# Actual task
Input: The deployment failed because an environment variable was missing. The variable was added, and the application was deployed successfully.
Output:

The example establishes both content selection and length.

Practical Example: Question Answering

Prompt
# Role
You are a Spring Boot interview trainer.
# Task
Answer the question in an interview-friendly format.
# Rules
Begin with a direct definition.
Explain the internal behavior.
Include one practical use case.
Keep the answer concise.
# Example
Question: What is dependency injection in Spring?
Answer: Dependency injection is a design technique in which Spring creates and supplies an object's required dependencies instead of the object creating them itself. The Spring container identifies managed beans, resolves their dependencies, and injects them through constructors, setters, or fields. Constructor injection is generally preferred because it supports immutability and easier testing. For example, an OrderService can receive a PaymentService implementation through its constructor.
# Actual task
Question: What is component scanning in Spring Boot?
Answer:

The example helps the model produce an answer suitable for technical interviews rather than a generic textbook definition.

Practical Example: Multiple Output Fields

Java
# Task
Analyze the Java code.
# Required output
Compilation Status
Output
Explanation
# Example
Code:
    public class Main {
        public static void main(String[] args) {
            int value = 10;
            System.out.println(value++);
        }
    }
Compilation Status: Compiles successfully
Output: 10
Explanation: The post-increment operator returns the current value before increasing it from 10 to 11.
# Actual task
Code:
    public class Main {
        public static void main(String[] args) {
            int value = 10;
            System.out.println(++value);
        }
    }
Compilation Status:
Output:
Explanation:

This example guides both technical analysis and response organization.

Using Multiple Examples Effectively

When multiple examples are required, they should cover meaningful variations.

For a Java error-classification task, examples might include:

  • Compilation error
  • Runtime exception
  • Logical error
  • Successful execution
  • Infinite loop
  • Unexpected output caused by type conversion

Example:

Prompt
# Example 1
Code: int number = "10";
Category: Compilation Error
# Example 2
Code: int result = 10 / 0;
Category: Runtime Exception
# Example 3
Code: int result = 10 + 20;
Category: Successful Execution
# Actual task
Code: int[] values = new int[2]; int result = values[3];
Category:

The examples should cover distinct rules rather than repeating nearly identical cases.

Example Ordering

The order of examples may influence the model's interpretation.

A useful ordering strategy is:

  1. Start with the simplest valid case.
  2. Add a common real-world case.
  3. Add a boundary case.
  4. Add an edge case.
  5. Present the actual task.

Example:

Prompt
# Example 1: Simple case
Input: 90
Grade: A
# Example 2: Common case
Input: 75
Grade: B
# Example 3: Boundary case
Input: 60
Grade: C
# Example 4: Invalid case
Input: 105
Grade: Invalid Score
# Actual task
Input: 59
Grade:

A structured progression makes the classification rules easier to infer.

Examples for Ambiguous Tasks

Examples are particularly important when the task contains subjective concepts.

Consider the instruction:

Prompt
Make the sentence simpler.

Simpler could mean:

  • Use fewer words
  • Replace technical terminology
  • Reduce sentence length
  • Remove unnecessary details
  • Rewrite for beginners
  • Preserve only the main idea

An example clarifies the intended transformation:

Prompt
# Example
Input: The implementation of authentication mechanisms is necessary to facilitate the verification of user identities.
Output: Authentication is required to verify user identities.
# Actual task
Input: The utilization of caching mechanisms can facilitate improvements in application response time.
Output:

The model can now infer that simpler means concise, direct, and easier to understand.

Examples for Strict Output Control

Examples can reduce unwanted introductions, explanations, and closing statements.

Prompt
# Task
Extract the programming language from the sentence.
# Output rule
Return only the language name.
# Example
Input: The service was developed using Java.
Output: Java
# Actual task
Input: The automation script was written in Python.
Output:

Without the example, the model might respond with:

Prompt
The programming language is Python.

With the example, it is more likely to return only:

Prompt
Python

Examples for Handling Missing Information

Prompts should demonstrate what to do when the input does not contain required information.

Prompt
# Example 1
Input: Rahul is a Java developer with four years of experience.
Name: Rahul
Skill: Java
Location: Not Provided
# Example 2
Input: A Python developer from Mumbai is required.
Name: Not Provided
Skill: Python
Location: Mumbai
# Actual task
Input: Sneha has five years of experience and works in Pune.
Name:
Skill:
Location:

This prevents the model from inventing missing values.

Examples for Refusal or Uncertainty

Examples can show how the model should respond when evidence is insufficient.

Prompt
# Example
Context: The report states that the server restarted at 10:00 PM, but it does not explain the cause.
Question: Why did the server restart?
Answer: The cause cannot be determined from the provided information.
# Actual task
Context: The application log shows a failed request but does not contain the response status.
Question: What response status was returned?
Answer:

This is useful for reducing unsupported assumptions and hallucinations.

Common Mistakes When Using Examples

Providing Incorrect Examples

The model may reproduce mistakes contained in examples.

Incorrect example:

Prompt
Input: 10 / 2
Output: 3

Even if the general instruction is correct, the incorrect example may confuse the model.

Every example should be verified before it is included in a production prompt.

Using Ambiguous Examples

An ambiguous example does not clearly demonstrate why an output is correct.

Prompt
Input: The product is okay.
Sentiment: Positive

The word okay may be interpreted as neutral. A clearer example should be used unless the purpose is to demonstrate a specific business rule.

Mixing Different Output Formats

Avoid changing the response format between examples.

Inconsistent format:

Prompt
# Example 1
Output: Positive
# Example 2
Result: {"sentiment":"Negative"}
# Example 3
Classification - Neutral

Consistent format:

Prompt
# Example 1
Classification: Positive
# Example 2
Classification: Negative
# Example 3
Classification: Neutral

Including Too Many Examples

More examples do not always produce better results.

Too many examples can:

  • Increase token consumption
  • Increase API cost
  • Reduce available space for input and output
  • Introduce contradictory patterns
  • Make prompts difficult to maintain
  • Cause the model to focus on irrelevant details

Use the smallest number of examples that sufficiently demonstrates the task.

Repeating Nearly Identical Examples

Repeated examples waste context space and add little instructional value.

Instead of showing five nearly identical positive sentiment examples, demonstrate:

  • Strong positive sentiment
  • Mild positive sentiment
  • Neutral sentiment
  • Mixed sentiment
  • Negative sentiment
  • Ambiguous sentiment

Failing to Label Negative Examples

An incorrect example must be explicitly identified.

Unsafe structure:

Prompt
Input: The service is unavailable.
Output: Positive

Improved structure:

Prompt
# Incorrect example
Input: The service is unavailable.
Output: Positive
# Error
The classification is incorrect because service unavailability expresses a negative experience.
# Correct output
Output: Negative

Allowing Examples to Conflict with Instructions

Examples often influence the model more strongly than abstract instructions.

Instruction:

Prompt
Return only one sentence.

Conflicting example:

Prompt
Output: The first paragraph explains the result.
The second paragraph provides recommendations.

The model may follow the demonstrated two-paragraph structure.

Instructions and examples must reinforce each other.

Using Unrepresentative Examples

An example set should reflect real production inputs.

If real inputs are long customer messages containing multiple issues, single-sentence examples may not be sufficient.

Include examples that represent:

  • Typical input length
  • Common writing style
  • Real data quality
  • Supported categories
  • Likely edge cases
  • Domain terminology

Copying Sensitive Data into Examples

Production prompts should not include unnecessary personal or confidential information.

Avoid using:

  • Real passwords
  • Authentication tokens
  • Private customer details
  • Financial account numbers
  • Confidential source code
  • Medical records
  • Internal business secrets

Use synthetic or anonymized examples whenever possible.

Best Practices for Prompt Examples

Use the Minimum Effective Number

Start with zero-shot prompting.

Add one example when the model misunderstands the format or task.

Add more examples only when they demonstrate distinct cases or rules.

Keep Examples Accurate

Validate every example for:

  • Technical correctness
  • Grammar
  • Formatting
  • Classification
  • Business rules
  • Numeric calculations
  • Expected edge-case behavior

Keep Examples Consistent

Maintain the same:

  • Labels
  • Field order
  • Tone
  • Formatting
  • Output length
  • Terminology
  • Delimiters

Cover Important Variations

Select examples that cover:

  • Common cases
  • Difficult cases
  • Boundary values
  • Missing information
  • Invalid input
  • Ambiguous input
  • Multiple supported categories

Separate Examples from Instructions

Do not mix instructions into the middle of an example.

Poor structure:

Prompt
Input: The application is slow.
Remember to use only one category.
Output: Performance Issue

Improved structure:

Prompt
# Rule
Return only one category.
# Example
Input: The application is slow.
Output: Performance Issue

Avoid Unnecessary Explanation

When the required output is short, keep examples short.

For simple extraction or classification tasks, lengthy explanations may teach the model to produce unwanted text.

Use Realistic Synthetic Data

Synthetic examples should resemble actual input without exposing private information.

Example:

Prompt
Customer ID: CUST-1042
Issue: Payment completed, but the subscription remains inactive.

This looks realistic while avoiding the use of a real customer's data.

Test Example Sensitivity

Change or reorder examples during testing to determine whether the model relies too heavily on a specific example.

Test questions include:

  • Does the response change when example order changes?
  • Does one category appear too frequently?
  • Does the model copy names or phrases from examples?
  • Does the model follow edge-case examples?
  • Does the model maintain the required output format?
  • Does the prompt work with unseen input patterns?

Examples and Token Usage

Every example consumes part of the model's context window.

A larger example set leaves less room for:

  • User input
  • Retrieved documents
  • Conversation history
  • Generated output
  • Additional instructions

For large-scale applications, examples should be concise and selected carefully.

A useful prompt does not contain the largest possible example set. It contains the most informative example set.

Dynamic Example Selection

In advanced applications, examples can be selected dynamically based on the current input.

For example, a system may:

  1. Store approved examples in a database.
  2. Convert the current input into an embedding.
  3. Find semantically similar examples.
  4. Insert the most relevant examples into the prompt.
  5. Send the completed prompt to the language model.

This technique is sometimes called example retrieval or dynamic few-shot prompting.

It can improve performance when:

  • The domain contains many categories
  • Inputs vary significantly
  • A fixed prompt would become too large
  • Relevant examples differ for each request
  • Domain-specific terminology is important

However, retrieved examples must still be accurate, safe, and relevant.

Example Selection Criteria

A good example should be evaluated using the following criteria:

CriterionQuestion
RelevanceDoes the example match the actual task?
CorrectnessIs the expected output technically accurate?
ClarityIs the relationship between input and output obvious?
CoverageDoes it demonstrate an important case or rule?
ConsistencyDoes it follow the same format as other examples?
BrevityIs it concise without losing essential information?
DiversityDoes it add a new pattern instead of repeating another example?
SafetyDoes it avoid private, confidential, or harmful information?
MaintainabilityCan the example be updated easily when requirements change?

Testing an Example-Based Prompt

A prompt should be tested against inputs that are not already represented by the examples.

Recommended test categories:

  1. Normal input
  2. Long input
  3. Short input
  4. Empty input
  5. Invalid input
  6. Ambiguous input
  7. Boundary input
  8. Multi-topic input
  9. Domain-specific input
  10. Input containing distracting instructions

Testing only the examples already present in the prompt does not prove that the prompt generalizes correctly.

Example-Based Prompt Template

Prompt
# Role
You are a [role or persona].
# Background
[Provide relevant context.]
# Task
[Describe the exact task.]
# Rules
[Rule 1]
[Rule 2]
[Rule 3]
# Output Requirements
[Define format, length, tone, and required fields.]
# Example 1
Input: [Sample input]
Output: [Expected output]
# Example 2
Input: [Sample input]
Output: [Expected output]
# Edge-Case Example
Input: [Unusual or incomplete input]
Output: [Expected handling]
# Actual Task
Input: [Real input]
Output:

This template can be adapted for classification, extraction, generation, rewriting, summarization, coding, analysis, and question answering.

Complete Example of an Effective Prompt

Prompt
# Role
You are an experienced Java technical interviewer.
# Background
The response will be used by a developer preparing for a Java interview.
# Task
Answer the supplied Java interview question.
# Rules
Begin with a direct definition.
Explain the internal working where relevant.
Use technically accurate Java terminology.
Include one practical example.
Mention one common interview mistake.
Do not include unrelated concepts.
# Output Requirements
Use the headings Interview Answer, Practical Example, and Common Mistake.
Keep the response between 150 and 220 words.
# Example
Question: What is method overloading?
Interview Answer: Method overloading allows a class to define multiple methods with the same name but different parameter lists. The methods may differ by the number, type, or order of parameters. Java resolves overloaded method calls at compile time, which is why method overloading is considered compile-time polymorphism. Changing only the return type does not create a valid overloaded method.
Practical Example: A Calculator class may define add(int first, int second) and add(double first, double second). The compiler selects the appropriate method according to the argument types.
Common Mistake: Candidates often say that methods can be overloaded by changing only the return type, but Java does not allow this because the return type is not considered during method selection.
# Actual Task
Question: What is method overriding?
Interview Answer:

This prompt is effective because its examples align with its role, rules, output requirements, terminology, and target audience.

When Examples Are Not Necessary

Examples may not be required when:

  • The task is extremely simple
  • The output is a single factual value
  • The required format is already unambiguous
  • Token usage must be minimized
  • The model consistently performs the task correctly
  • The task changes too frequently for fixed examples
  • The input itself already contains the required pattern

Example:

Prompt
Convert 25 degrees Celsius to Fahrenheit.
Return only the numeric result.

Adding several examples to such a simple task may not provide meaningful value.

Examples are strongly recommended when:

  • Output formatting must be exact
  • The task uses custom categories
  • Category boundaries are subtle
  • A specific tone must be reproduced
  • The response must follow an internal business rule
  • Inputs contain missing or ambiguous information
  • The model repeatedly misunderstands instructions
  • The task requires domain-specific terminology
  • The output will be processed by software
  • Consistency is more important than creativity

Quick Checklist for Prompt Examples

Before using examples in a prompt, verify the following:

  • The examples are technically correct.
  • Each example demonstrates a useful rule.
  • Input and output labels are consistent.
  • The examples match the actual task.
  • The output format matches production requirements.
  • Important categories are represented.
  • Boundary and edge cases are included where necessary.
  • Negative examples are clearly marked.
  • Instructions and examples do not conflict.
  • Sensitive data has been removed.
  • Repetitive examples have been eliminated.
  • Token usage remains reasonable.
  • The final task is clearly separated from the examples.
  • The prompt has been tested with unseen inputs.

Key Takeaways

  • Examples demonstrate expected behavior more clearly than abstract instructions alone.
  • A prompt without examples is zero-shot, a prompt with one example is one-shot, and a prompt with multiple examples is few-shot.
  • Examples influence the current context but do not permanently retrain the model.
  • Good examples clarify output format, tone, depth, classification rules, and edge-case handling.
  • Positive, negative, contrastive, boundary, and edge-case examples serve different purposes.
  • Examples should be accurate, relevant, consistent, diverse, and concise.
  • The model may follow demonstrated examples even when they conflict with written instructions.
  • Too many examples can increase cost, consume context space, and introduce contradictions.
  • Dynamic example retrieval can provide relevant examples for complex production systems.
  • The best example set is not the largest set; it is the smallest set that clearly demonstrates all important behaviors.

Conclusion

Examples are a critical part of the anatomy of an effective prompt because they transform expectations into visible patterns. They help the model understand not only what task to perform but also how the result should look, sound, and behave.

Well-designed examples reduce ambiguity, improve consistency, enforce structure, and guide the model through difficult classifications or transformations. Poor examples can have the opposite effect by introducing incorrect rules, formatting conflicts, bias, or irrelevant patterns.

Effective prompt engineering therefore requires careful example selection. Each example should have a specific purpose, represent realistic input, demonstrate an accurate output, and align with every other instruction in the prompt.

Frequently Asked Questions

What are examples in prompt engineering?

Examples are sample input-output pairs included inside a prompt to demonstrate how the model should perform a task. They show the model what kind of response is expected instead of relying only on written instructions.

What is the difference between zero-shot, one-shot, and few-shot prompting?

Zero-shot prompting provides instructions without any examples. One-shot prompting provides exactly one example before the actual task. Few-shot prompting provides multiple examples before the actual task, which generally produces more consistent results but consumes more context tokens.

What is in-context learning?

In-context learning is the process by which a model identifies patterns from the information provided in the current prompt and uses those patterns to generate a response. Examples do not permanently retrain or modify the model; they influence only the current interaction.

What are positive and negative examples?

Positive examples demonstrate the correct output, such as valid formatting or classification. Negative examples show what the model should avoid, but they must be clearly labeled as incorrect, otherwise the model may treat them as a pattern to follow.

What is a contrastive example?

A contrastive example shows a weak response and a strong response for the same task. It helps communicate quality expectations, such as depth or precision, that are difficult to express through general instructions alone.

Why are edge-case and boundary examples important?

Boundary examples demonstrate how to handle cases near the limit between two categories, such as a score exactly at a passing threshold. Edge-case examples demonstrate how unusual, empty, incomplete, or ambiguous inputs should be handled, which improves reliability when real-world input is imperfect.

Where should examples be placed in a prompt?

Examples should normally appear after the role, background, task, rules, and output requirements, but before the actual input that the model must process. Placing examples after the actual input can make the prompt structure less predictable.

What are common mistakes when using examples?

Common mistakes include providing incorrect or unverified examples, using ambiguous examples, mixing different output formats between examples, including too many repetitive examples, and failing to clearly label negative examples.

Can too many examples hurt a prompt?

Yes. Too many examples can increase token consumption and API cost, reduce available space for input and output, introduce contradictory patterns, and make prompts harder to maintain. The goal is the smallest example set that clearly demonstrates the task, not the largest one.

What is dynamic example selection?

Dynamic example selection, also called example retrieval or dynamic few-shot prompting, selects the most relevant examples for each request based on the current input, typically using embeddings to find semantically similar approved examples stored in a database.