PromptBuilder.example()method

Add an input/output example for few-shot learning and response format demonstration.

USAGE

PromptBuilder.example(input_example, output_example)

Examples are a powerful few-shot learning technique that provides concrete demonstrations of expected input/output patterns, helping the AI understand the desired response format, style, and level of detail. Examples appear in the "EXAMPLES" section near the end of the prompt, allowing the model to learn from specific demonstrations while maintaining the attention hierarchy for core content.

Parameters

input_example : str

Example input that represents a typical or representative case that the AI might encounter. Should be realistic, relevant to the task context, and demonstrate the type and complexity of input the AI will be processing. The input should be specific enough to provide clear guidance while being generalizable to similar scenarios.

output_example : str

Expected output format and content that demonstrates the desired response style, level of detail, structure, and quality. Should exemplify the formatting requirements, analytical depth, and professional standards expected in the actual response. The output should be comprehensive enough to serve as a template while being specific to the input provided.

Returns

PromptBuilder

Self for method chaining, allowing combination with other prompt building methods to create comprehensive, structured prompts.

Research Foundation

Few-Shot Learning Theory. Examples leverage the AI model’s ability to learn from demonstrations without explicit training. By providing concrete input/output pairs, examples enable the model to infer patterns, styles, and expected behaviors that might be difficult to specify through constraints alone.

Response Calibration Mechanism. Examples serve as calibration tools that help establish the appropriate level of detail, technical depth, formatting style, and analytical approach for responses. This is particularly valuable for complex tasks where abstract descriptions of requirements might be ambiguous.

Pattern Recognition Enhancement. Multiple examples can demonstrate variations in approach, showing how different types of inputs should be handled while maintaining consistent output quality and format. This helps the AI generalize appropriately across different scenarios.

Quality Anchoring Psychology. Examples set quality expectations by demonstrating high-quality responses that serve as benchmarks for the AI’s own outputs. This helps maintain consistency and professionalism across different prompt executions.

Integration Notes

  • Few-Shot Learning: leverages AI’s pattern recognition for improved response quality
  • Format Demonstration: shows concrete examples of expected output structure and style
  • Quality Calibration: establishes benchmarks for response depth and professionalism
  • Variation Handling: multiple examples can demonstrate different scenarios and approaches
  • Learning Reinforcement: examples reinforce other prompt elements like constraints and formatting
  • Prompt Positioning: examples appear late in prompt to provide final guidance before response generation

The .example() method provides powerful demonstration-based learning that significantly improves response quality, consistency, and alignment with expectations through concrete input/output pattern recognition rather than abstract instruction following.

Examples


Code review example

Demonstrate expected code review format and depth while providing constructive feedback:

import talk_box as tb

builder = (
    tb.PromptBuilder()
    .persona("senior developer", "code quality and security")
    .task_context("review Python code for security and best practices")
    .core_analysis([
        "security vulnerabilities and risks",
        "code quality and maintainability",
        "performance optimization opportunities",
        "best practice adherence"
    ])
    .example(
        input_example='''
def authenticate_user(username, password):
    query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'"
    result = db.execute(query)
    return len(result) > 0
        ''',
        output_example='''
**CRITICAL SECURITY ISSUE**: SQL Injection Vulnerability
- **Problem**: direct string concatenation in SQL query allows SQL injection attacks
- **Risk Level**: high, and could lead to a data breach or unauthorized access
- **Fix**: use parameterized queries or ORM methods
- **Example Fix**:
  ```python
  query = "SELECT * FROM users WHERE username = %s AND password = %s"
  result = db.execute(query, (username, password))
  ```

**SECURITY ISSUE**: Plain Text Password Storage
- **Problem**: passwords should never be stored or compared in plain text
- **Fix**: implement password hashing with salt (e.g., bcrypt, scrypt)

**CODE QUALITY**: function should return user object, not boolean
**PERFORMANCE**: consider adding database indexes on username field'''
    )
    .output_format([
        "start with critical security issues",
        "include specific code examples and fixes",
        "provide risk assessment for each issue",
        "end with positive feedback where applicable"
    ])
)

print(builder)
You are a senior developer with expertise in code quality and security.

TASK: review Python code for security and best practices

CORE ANALYSIS (Required):
- security vulnerabilities and risks
- code quality and maintainability
- performance optimization opportunities
- best practice adherence

OUTPUT FORMAT:
- start with critical security issues
- include specific code examples and fixes
- provide risk assessment for each issue
- end with positive feedback where applicable

EXAMPLES:

Example 1:
Input: 
def authenticate_user(username, password):
    query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'"
    result = db.execute(query)
    return len(result) > 0
        
Output: 
**CRITICAL SECURITY ISSUE**: SQL Injection Vulnerability
- **Problem**: direct string concatenation in SQL query allows SQL injection attacks
- **Risk Level**: high, and could lead to a data breach or unauthorized access
- **Fix**: use parameterized queries or ORM methods
- **Example Fix**:
  ```python
  query = "SELECT * FROM users WHERE username = %s AND password = %s"
  result = db.execute(query, (username, password))
  ```

**SECURITY ISSUE**: Plain Text Password Storage
- **Problem**: passwords should never be stored or compared in plain text
- **Fix**: implement password hashing with salt (e.g., bcrypt, scrypt)

**CODE QUALITY**: function should return user object, not boolean
**PERFORMANCE**: consider adding database indexes on username field

Data analysis example

Demonstrate analytical depth and presentation style using structured findings and recommendations:

builder = (
    tb.PromptBuilder()
    .persona("data scientist", "business analytics")
    .task_context("analyze customer behavior data and provide insights")
    .core_analysis([
        "customer segmentation patterns",
        "behavioral trends and anomalies",
        "statistical significance of findings",
        "business recommendations"
    ])
    .example(
        input_example="customer purchase data showing 15% increase in mobile transactions but 8% decrease in desktop purchases over Q3",
        output_example='''
**KEY FINDING**: Mobile-First Customer Behavior Shift

**Statistical Analysis**:
- Mobile transactions: +15% (p < 0.01, statistically significant)
- Desktop transactions: -8% (p < 0.05, statistically significant)
- Net transaction volume: +3.2% overall growth

**Customer Segmentation**:
- Millennials (25-40): 67% mobile preference, driving the increase
- Gen X (41-55): 45% mobile adoption, slower transition
- Baby Boomers (55+): 23% mobile usage, prefer desktop

**Business Implications**:
1. **Mobile Optimization Priority**: Invest in mobile UX improvements
2. **Desktop Support**: Maintain desktop experience for older demographics
3. **Cross-Platform Strategy**: Develop unified experience across devices

**Recommendations**:
- Allocate 70% of UX budget to mobile optimization
- Implement responsive design improvements
- Create mobile-specific promotional campaigns'''
    )
)

print(builder)
You are a data scientist with expertise in business analytics.

TASK: analyze customer behavior data and provide insights

CORE ANALYSIS (Required):
- customer segmentation patterns
- behavioral trends and anomalies
- statistical significance of findings
- business recommendations

EXAMPLES:

Example 1:
Input: customer purchase data showing 15% increase in mobile transactions but 8% decrease in desktop
purchases over Q3
Output: 
**KEY FINDING**: Mobile-First Customer Behavior Shift

**Statistical Analysis**:
- Mobile transactions: +15% (p < 0.01, statistically significant)
- Desktop transactions: -8% (p < 0.05, statistically significant)
- Net transaction volume: +3.2% overall growth

**Customer Segmentation**:
- Millennials (25-40): 67% mobile preference, driving the increase
- Gen X (41-55): 45% mobile adoption, slower transition
- Baby Boomers (55+): 23% mobile usage, prefer desktop

**Business Implications**:
1. **Mobile Optimization Priority**: Invest in mobile UX improvements
2. **Desktop Support**: Maintain desktop experience for older demographics
3. **Cross-Platform Strategy**: Develop unified experience across devices

**Recommendations**:
- Allocate 70% of UX budget to mobile optimization
- Implement responsive design improvements
- Create mobile-specific promotional campaigns

Business analysis example

Demonstrate strategic analysis format in business contexts with clear sections and actionable recommendations:

builder = (
    tb.PromptBuilder()
    .persona("business consultant", "strategic planning")
    .task_context("analyze market expansion opportunity")
    .core_analysis([
        "market size and growth potential",
        "competitive landscape assessment",
        "resource requirements and ROI",
        "risk factors and mitigation"
    ])
    .example(
        input_example="SaaS company considering expansion into European markets, currently serving 50k US customers",
        output_example='''
**EXECUTIVE SUMMARY**: European expansion presents significant opportunity with estimated 3-year ROI of 180%

**MARKET ANALYSIS**:
- Total Addressable Market: €2.3B (growing 12% annually)
- Immediate Serviceable Market: €180M across UK, Germany, France
- Competitive Gap: Limited players in mid-market segment

**FINANCIAL PROJECTION**:
- Year 1: €2M investment, €800K revenue
- Year 2: €1.2M additional investment, €3.2M revenue
- Year 3: €5.8M revenue, 18% profit margin
- Break-even: Month 14

**KEY SUCCESS FACTORS**:
1. GDPR compliance and data localization
2. Local partnerships for market entry
3. Multi-language product localization
4. European customer support team

**RISK MITIGATION**:
- Regulatory: Early GDPR consultation (€50K budget)
- Competition: Differentiated pricing strategy
- Execution: Phased rollout starting with UK market

**RECOMMENDATION**: Proceed with expansion, starting Q2 2024
        '''
    )
)

print(builder)
You are a business consultant with expertise in strategic planning.

TASK: analyze market expansion opportunity

CORE ANALYSIS (Required):
- market size and growth potential
- competitive landscape assessment
- resource requirements and ROI
- risk factors and mitigation

EXAMPLES:

Example 1:
Input: SaaS company considering expansion into European markets, currently serving 50k US customers
Output: 
**EXECUTIVE SUMMARY**: European expansion presents significant opportunity with estimated 3-year ROI
of 180%

**MARKET ANALYSIS**:
- Total Addressable Market: €2.3B (growing 12% annually)
- Immediate Serviceable Market: €180M across UK, Germany, France
- Competitive Gap: Limited players in mid-market segment

**FINANCIAL PROJECTION**:
- Year 1: €2M investment, €800K revenue
- Year 2: €1.2M additional investment, €3.2M revenue
- Year 3: €5.8M revenue, 18% profit margin
- Break-even: Month 14

**KEY SUCCESS FACTORS**:
1. GDPR compliance and data localization
2. Local partnerships for market entry
3. Multi-language product localization
4. European customer support team

**RISK MITIGATION**:
- Regulatory: Early GDPR consultation (€50K budget)
- Competition: Differentiated pricing strategy
- Execution: Phased rollout starting with UK market

**RECOMMENDATION**: Proceed with expansion, starting Q2 2024
        

Educational content example

Show educational content format with clear learning objectives and hands-on exercises:

builder = (
    tb.PromptBuilder()
    .persona("programming instructor", "Python education")
    .task_context("Create lesson on Python data structures")
    .core_analysis([
        "Concept explanation with clear examples",
        "Progressive skill building exercises",
        "Common mistakes and debugging",
        "Real-world applications"
    ])
    .example(
        input_example="Teach Python dictionaries to intermediate beginners",
        output_example='''
**LEARNING OBJECTIVE**: Master Python dictionaries for data organization and lookup

**CONCEPT EXPLANATION**:
Dictionaries store key-value pairs, like a real-world dictionary where you look up words (keys) to find definitions (values).

```python
# Creating a dictionary
student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}
```

**HANDS-ON EXERCISE**:
```python
# Task: Create an inventory system
inventory = {"apples": 50, "bananas": 30, "oranges": 25}

# Add new item
inventory["grapes"] = 40

# Update quantity
inventory["apples"] += 10

# Check if item exists
if "mangoes" in inventory:
    print(f"Mangoes: {inventory['mangoes']}")
else:
    print("Mangoes not in stock")
```

**COMMON MISTAKES**:
1. Using mutable objects as keys (lists, other dictionaries)
2. Forgetting that dictionaries are unordered (Python < 3.7)
3. KeyError when accessing non-existent keys

**REAL-WORLD APPLICATION**: User authentication, configuration settings, caching data
        '''
    )
)

print(builder)
You are a programming instructor with expertise in Python education.

TASK: Create lesson on Python data structures

CORE ANALYSIS (Required):
- Concept explanation with clear examples
- Progressive skill building exercises
- Common mistakes and debugging
- Real-world applications

EXAMPLES:

Example 1:
Input: Teach Python dictionaries to intermediate beginners
Output: 
**LEARNING OBJECTIVE**: Master Python dictionaries for data organization and lookup

**CONCEPT EXPLANATION**:
Dictionaries store key-value pairs, like a real-world dictionary where you look up words (keys) to
find definitions (values).

```python
# Creating a dictionary
student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}
```

**HANDS-ON EXERCISE**:
```python
# Task: Create an inventory system
inventory = {"apples": 50, "bananas": 30, "oranges": 25}

# Add new item
inventory["grapes"] = 40

# Update quantity
inventory["apples"] += 10

# Check if item exists
if "mangoes" in inventory:
    print(f"Mangoes: {inventory['mangoes']}")
else:
    print("Mangoes not in stock")
```

**COMMON MISTAKES**:
1. Using mutable objects as keys (lists, other dictionaries)
2. Forgetting that dictionaries are unordered (Python < 3.7)
3. KeyError when accessing non-existent keys

**REAL-WORLD APPLICATION**: User authentication, configuration settings, caching data
        

Multiple examples for variation

Use multiple examples to show different scenarios and approaches within the same prompt:

builder = (
    tb.PromptBuilder()
    .persona("senior developer", "code mentorship")
    .task_context("provide educational code review for junior developers")
    .core_analysis([
        "code correctness and logic",
        "best practices and patterns",
        "performance considerations",
        "learning opportunities"
    ])
    .example(
        input_example="simple function with basic logic error",
        output_example="focus on explaining the logic error clearly with corrected version and learning points"
    )
    .example(
        input_example="complex function with performance issues",
        output_example="analyze algorithmic complexity, suggest optimizations, explain trade-offs between readability and performance"
    )
    .example(
        input_example="well-written code with minor style issues",
        output_example="acknowledge good practices, suggest minor improvements, reinforce positive patterns"
    )
)

print(builder)
You are a senior developer with expertise in code mentorship.

TASK: provide educational code review for junior developers

CORE ANALYSIS (Required):
- code correctness and logic
- best practices and patterns
- performance considerations
- learning opportunities

EXAMPLES:

Example 1:
Input: simple function with basic logic error
Output: focus on explaining the logic error clearly with corrected version and learning points

Example 2:
Input: complex function with performance issues
Output: analyze algorithmic complexity, suggest optimizations, explain trade-offs between
readability and performance

Example 3:
Input: well-written code with minor style issues
Output: acknowledge good practices, suggest minor improvements, reinforce positive patterns