Generated banner for Prompt Engineering Patterns
Generated logo for Prompt Engineering Patterns

Prompt Engineering Patterns

Seth HobsonCommunityCreated by Seth Hobson

  • Skill
  • Guidelines
  • Agent tooling
  • MIT
  • Low risk
  • Has scripts

From the author

This skill should be used when the user asks to "optimize a prompt", "improve prompt performance", "design a prompt template", "write better prompts", "debug prompt issues", "use chain-of-thought", "structured prompting", "few-shot prompting", or wants to apply advanced prompt engineering patterns for production LLM applications.
— the description by Seth Hobson

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a framework for developing and refining prompts for LLM applications. It covers methodologies such as few-shot learning, chain-of-thought reasoning, and structured output generation. The content includes guidance on creating reusable templates, implementing system prompts, and debugging prompt behavior to achieve consistent results.

What it does

  • Provides patterns for few-shot learning and dynamic example selection
  • Explains techniques for eliciting step-by-step reasoning via chain-of-thought
  • Demonstrates how to enforce structured outputs using schemas
  • Offers strategies for iterative prompt optimization and testing
  • Includes methods for building modular and conditional prompt templates
  • Defines approaches for setting model behavior through system prompts

When to use it

  • When designing prompts for complex LLM tasks
  • When needing to improve the consistency of model outputs
  • When implementing reasoning chains for logic or math problems
  • When requiring reliable, machine-readable output formats
  • When creating reusable prompt libraries for applications

Advantages

  • Standardizes prompt development through established patterns
  • Enables more predictable model behavior
  • Supports integration with structured data workflows
  • Facilitates modular design for complex prompt systems

Usage examples

“How can I use few-shot learning to improve my model's classification accuracy?”
The agent provides strategies for selecting relevant examples and constructing effective input-output pairs to guide the model.
“Show me how to force an LLM to return JSON.”
The agent demonstrates how to use schema enforcement and structured output patterns to ensure the model returns valid JSON.
“My prompt is producing inconsistent results, how do I debug it?”
The agent suggests iterative refinement techniques, such as adding reasoning steps or providing better examples to stabilize output.
“How do I implement chain-of-thought in my prompt?”
The agent explains how to use trigger phrases or few-shot reasoning traces to elicit step-by-step logic from the model.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/wshobson/prompt-engineering-patterns/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip prompt-engineering-patterns.zip -d .agents/skills

Documentation by Seth Hobson

Prompt Engineering Patterns

Master advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability.

When to Use This Skill

  • Designing complex prompts for production LLM applications

  • Optimizing prompt performance and consistency

  • Implementing structured reasoning patterns (chain-of-thought, tree-of-thought)

  • Building few-shot learning systems with dynamic example selection

  • Creating reusable prompt templates with variable interpolation

  • Debugging and refining prompts that produce inconsistent outputs

  • Implementing system prompts for specialized AI assistants

  • Using structured outputs (JSON mode) for reliable parsing

Core Capabilities

1. Few-Shot Learning
  • Example selection strategies (semantic similarity, diversity sampling)

  • Balancing example count with context window constraints

  • Constructing effective demonstrations with input-output pairs

  • Dynamic example retrieval from knowledge bases

  • Handling edge cases through strategic example selection

2. Chain-of-Thought Prompting
  • Step-by-step reasoning elicitation

  • Zero-shot CoT with "Let's think step by step"

  • Few-shot CoT with reasoning traces

  • Self-consistency techniques (sampling multiple reasoning paths)

  • Verification and validation steps

3. Structured Outputs
  • JSON mode for reliable parsing

  • Pydantic schema enforcement

  • Type-safe response handling

  • Error handling for malformed outputs

4. Prompt Optimization
  • Iterative refinement workflows

  • A/B testing prompt variations

  • Measuring prompt performance metrics (accuracy, consistency, latency)

  • Reducing token usage while maintaining quality

  • Handling edge cases and failure modes

5. Template Systems
  • Variable interpolation and formatting

  • Conditional prompt sections

  • Multi-turn conversation templates

  • Role-based prompt composition

  • Modular prompt components

6. System Prompt Design
  • Setting model behavior and constraints

  • Defining output formats and structure

  • Establishing role and expertise

  • Safety guidelines and content policies

  • Context setting and background information

Quick Start

from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field

# Define structured output schema
class SQLQuery(BaseModel):
    query: str = Field(description="The SQL query")
    explanation: str = Field(description="Brief explanation of what the query does")
    tables_used: list[str] = Field(description="List of tables referenced")

# Initialize model with structured output
llm = ChatAnthropic(model="claude-sonnet-5")
structured_llm = llm.with_structured_output(SQLQuery)

# Create prompt template
prompt = ChatPromptTemplate.from_messages([
    ("system", """You are an expert SQL developer. Generate efficient, secure SQL queries.
    Always use parameterized queries to prevent SQL injection.
    Explain your reasoning briefly."""),
    ("user", "Convert this to SQL: {query}")
])

# Create chain
chain = prompt | structured_llm

# Use
result = await chain.ainvoke({
    "query": "Find all users who registered in the last 30 days"
})
print(result.query)
print(result.explanation)

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

  1. Be Specific: Vague prompts produce inconsistent results

  2. Show, Don't Tell: Examples are more effective than descriptions

  3. Use Structured Outputs: Enforce schemas with Pydantic for reliability

  4. Test Extensively: Evaluate on diverse, representative inputs

  5. Iterate Rapidly: Small changes can have large impacts

  6. Monitor Performance: Track metrics in production

  7. Version Control: Treat prompts as code with proper versioning

  8. Document Intent: Explain why prompts are structured as they are

Common Pitfalls

  • Over-engineering: Starting with complex prompts before trying simple ones

  • Example pollution: Using examples that don't match the target task

  • Context overflow: Exceeding token limits with excessive examples

  • Ambiguous instructions: Leaving room for multiple interpretations

  • Ignoring edge cases: Not testing on unusual or boundary inputs

  • No error handling: Assuming outputs will always be well-formed

  • Hardcoded values: Not parameterizing prompts for reuse

Success Metrics

Track these KPIs for your prompts:

  • Accuracy: Correctness of outputs

  • Consistency: Reproducibility across similar inputs

  • Latency: Response time (P50, P95, P99)

  • Token Usage: Average tokens per request

  • Success Rate: Percentage of valid, parseable outputs

  • User Satisfaction: Ratings and feedback

Files

references/prompt-optimization.md

Prompt Optimization Guide

Systematic Refinement Process

1. Baseline Establishment
def establish_baseline(prompt, test_cases):
    results = {
        'accuracy': 0,
        'avg_tokens': 0,
        'avg_latency': 0,
        'success_rate': 0
    }

    for test_case in test_cases:
        response = llm.complete(prompt.format(**test_case['input']))

        results['accuracy'] += evaluate_accuracy(response, test_case['expected'])
        results['avg_tokens'] += count_tokens(response)
        results['avg_latency'] += measure_latency(response)
        results['success_rate'] += is_valid_response(response)

    # Average across test cases
    n = len(test_cases)
    return {k: v/n for k, v in results.items()}
2. Iterative Refinement Workflow
Initial Prompt → Test → Analyze Failures → Refine → Test → Repeat
class PromptOptimizer:
    def __init__(self, initial_prompt, test_suite):
        self.prompt = initial_prompt
        self.test_suite = test_suite
        self.history = []

    def optimize(self, max_iterations=10):
        for i in range(max_iterations):
            # Test current prompt
            results = self.evaluate_prompt(self.prompt)
            self.history.append({
                'iteration': i,
                'prompt': self.prompt,
                'results': results
            })

            # Stop if good enough
            if results['accuracy'] > 0.95:
                break

            # Analyze failures
            failures = self.analyze_failures(results)

            # Generate refinement suggestions
            refinements = self.generate_refinements(failures)

            # Apply best refinement
            self.prompt = self.select_best_refinement(refinements)

        return self.get_best_prompt()
3. A/B Testing Framework
class PromptABTest:
    def __init__(self, variant_a, variant_b):
        self.variant_a = variant_a
        self.variant_b = variant_b

    def run_test(self, test_queries, metrics=['accuracy', 'latency']):
        results = {
            'A': {m: [] for m in metrics},
            'B': {m: [] for m in metrics}
        }

        for query in test_queries:
            # Randomly assign variant (50/50 split)
            variant = 'A' if random.random() < 0.5 else 'B'
            prompt = self.variant_a if variant == 'A' else self.variant_b

            response, metrics_data = self.execute_with_metrics(
                prompt.format(query=query['input'])
            )

            for metric in metrics:
                results[variant][metric].append(metrics_data[metric])

        return self.analyze_results(results)

    def analyze_results(self, results):
        from scipy import stats

        analysis = {}
        for metric in results['A'].keys():
            a_values = results['A'][metric]
            b_values = results['B'][metric]

            # Statistical significance test
            t_stat, p_value = stats.ttest_ind(a_values, b_values)

            analysis[metric] = {
                'A_mean': np.mean(a_values),
                'B_mean': np.mean(b_values),
                'improvement': (np.mean(b_values) - np.mean(a_values)) / np.mean(a_values),
                'statistically_significant': p_value < 0.05,
                'p_value': p_value,
                'winner': 'B' if np.mean(b_values) > np.mean(a_values) else 'A'
            }

        return analysis

Optimization Strategies

Token Reduction
def optimize_for_tokens(prompt):
    optimizations = [
        # Remove redundant phrases
        ('in order to', 'to'),
        ('due to the fact that', 'because'),
        ('at this point in time', 'now'),

        # Consolidate instructions
        ('First, ...\\nThen, ...\\nFinally, ...', 'Steps: 1) ... 2) ... 3) ...'),

        # Use abbreviations (after first definition)
        ('Natural Language Processing (NLP)', 'NLP'),

        # Remove filler words
        (' actually ', ' '),
        (' basically ', ' '),
        (' really ', ' ')
    ]

    optimized = prompt
    for old, new in optimizations:
        optimized = optimized.replace(old, new)

    return optimized
Latency Reduction
def optimize_for_latency(prompt):
    strategies = {
        'shorter_prompt': reduce_token_count(prompt),
        'streaming': enable_streaming_response(prompt),
        'caching': add_cacheable_prefix(prompt),
        'early_stopping': add_stop_sequences(prompt)
    }

    # Test each strategy
    best_strategy = None
    best_latency = float('inf')

    for name, modified_prompt in strategies.items():
        latency = measure_average_latency(modified_prompt)
        if latency < best_latency:
            best_latency = latency
            best_strategy = modified_prompt

    return best_strategy
Accuracy Improvement
def improve_accuracy(prompt, failure_cases):
    improvements = []

    # Add constraints for common failures
    if has_format_errors(failure_cases):
        improvements.append("Output must be valid JSON with no additional text.")

    # Add examples for edge cases
    edge_cases = identify_edge_cases(failure_cases)
    if edge_cases:
        improvements.append(f"Examples of edge cases:\\n{format_examples(edge_cases)}")

    # Add verification step
    if has_logical_errors(failure_cases):
        improvements.append("Before responding, verify your answer is logically consistent.")

    # Strengthen instructions
    if has_ambiguity_errors(failure_cases):
        improvements.append(clarify_ambiguous_instructions(prompt))

    return integrate_improvements(prompt, improvements)

Performance Metrics

Core Metrics
class PromptMetrics:
    @staticmethod
    def accuracy(responses, ground_truth):
        return sum(r == gt for r, gt in zip(responses, ground_truth)) / len(responses)

    @staticmethod
    def consistency(responses):
        # Measure how often identical inputs produce identical outputs
        from collections import defaultdict
        input_responses = defaultdict(list)

        for inp, resp in responses:
            input_responses[inp].append(resp)

        consistency_scores = []
        for inp, resps in input_responses.items():
            if len(resps) > 1:
                # Percentage of responses that match the most common response
                most_common_count = Counter(resps).most_common(1)[0][1]
                consistency_scores.append(most_common_count / len(resps))

        return np.mean(consistency_scores) if consistency_scores else 1.0

    @staticmethod
    def token_efficiency(prompt, responses):
        avg_prompt_tokens = np.mean([count_tokens(prompt.format(**r['input'])) for r in responses])
        avg_response_tokens = np.mean([count_tokens(r['output']) for r in responses])
        return avg_prompt_tokens + avg_response_tokens

    @staticmethod
    def latency_p95(latencies):
        return np.percentile(latencies, 95)
Automated Evaluation
def evaluate_prompt_comprehensively(prompt, test_suite):
    results = {
        'accuracy': [],
        'consistency': [],
        'latency': [],
        'tokens': [],
        'success_rate': []
    }

    # Run each test case multiple times for consistency measurement
    for test_case in test_suite:
        runs = []
        for _ in range(3):  # 3 runs per test case
            start = time.time()
            response = llm.complete(prompt.format(**test_case['input']))
            latency = time.time() - start

            runs.append(response)
            results['latency'].append(latency)
            results['tokens'].append(count_tokens(prompt) + count_tokens(response))

        # Accuracy (best of 3 runs)
        accuracies = [evaluate_accuracy(r, test_case['expected']) for r in runs]
        results['accuracy'].append(max(accuracies))

        # Consistency (how similar are the 3 runs?)
        results['consistency'].append(calculate_similarity(runs))

        # Success rate (all runs successful?)
        results['success_rate'].append(all(is_valid(r) for r in runs))

    return {
        'avg_accuracy': np.mean(results['accuracy']),
        'avg_consistency': np.mean(results['consistency']),
        'p95_latency': np.percentile(results['latency'], 95),
        'avg_tokens': np.mean(results['tokens']),
        'success_rate': np.mean(results['success_rate'])
    }

Failure Analysis

Categorizing Failures
class FailureAnalyzer:
    def categorize_failures(self, test_results):
        categories = {
            'format_errors': [],
            'factual_errors': [],
            'logic_errors': [],
            'incomplete_responses': [],
            'hallucinations': [],
            'off_topic': []
        }

        for result in test_results:
            if not result['success']:
                category = self.determine_failure_type(
                    result['response'],
                    result['expected']
                )
                categories[category].append(result)

        return categories

    def generate_fixes(self, categorized_failures):
        fixes = []

        if categorized_failures['format_errors']:
            fixes.append({
                'issue': 'Format errors',
                'fix': 'Add explicit format examples and constraints',
                'priority': 'high'
            })

        if categorized_failures['hallucinations']:
            fixes.append({
                'issue': 'Hallucinations',
                'fix': 'Add grounding instruction: "Base your answer only on provided context"',
                'priority': 'critical'
            })

        if categorized_failures['incomplete_responses']:
            fixes.append({
                'issue': 'Incomplete responses',
                'fix': 'Add: "Ensure your response fully addresses all parts of the question"',
                'priority': 'medium'
            })

        return fixes

Versioning and Rollback

Prompt Version Control
class PromptVersionControl:
    def __init__(self, storage_path):
        self.storage = storage_path
        self.versions = []

    def save_version(self, prompt, metadata):
        version = {
            'id': len(self.versions),
            'prompt': prompt,
            'timestamp': datetime.now(),
            'metrics': metadata.get('metrics', {}),
            'description': metadata.get('description', ''),
            'parent_id': metadata.get('parent_id')
        }
        self.versions.append(version)
        self.persist()
        return version['id']

    def rollback(self, version_id):
        if version_id < len(self.versions):
            return self.versions[version_id]['prompt']
        raise ValueError(f"Version {version_id} not found")

    def compare_versions(self, v1_id, v2_id):
        v1 = self.versions[v1_id]
        v2 = self.versions[v2_id]

        return {
            'diff': generate_diff(v1['prompt'], v2['prompt']),
            'metrics_comparison': {
                metric: {
                    'v1': v1['metrics'].get(metric),
                    'v2': v2['metrics'].get(metric'),
                    'change': v2['metrics'].get(metric, 0) - v1['metrics'].get(metric, 0)
                }
                for metric in set(v1['metrics'].keys()) | set(v2['metrics'].keys())
            }
        }

Best Practices

  1. Establish Baseline: Always measure initial performance

  2. Change One Thing: Isolate variables for clear attribution

  3. Test Thoroughly: Use diverse, representative test cases

  4. Track Metrics: Log all experiments and results

  5. Validate Significance: Use statistical tests for A/B comparisons

  6. Document Changes: Keep detailed notes on what and why

  7. Version Everything: Enable rollback to previous versions

  8. Monitor Production: Continuously evaluate deployed prompts

Common Optimization Patterns

Pattern 1: Add Structure
Before: "Analyze this text"
After: "Analyze this text for:\n1. Main topic\n2. Key arguments\n3. Conclusion"
Pattern 2: Add Examples
Before: "Extract entities"
After: "Extract entities\\n\\nExample:\\nText: Apple released iPhone\\nEntities: {company: Apple, product: iPhone}"
Pattern 3: Add Constraints
Before: "Summarize this"
After: "Summarize in exactly 3 bullet points, 15 words each"
Pattern 4: Add Verification
Before: "Calculate..."
After: "Calculate... Then verify your calculation is correct before responding."

Tools and Utilities

  • Prompt diff tools for version comparison

  • Automated test runners

  • Metric dashboards

  • A/B testing frameworks

  • Token counting utilities

  • Latency profilers

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Seth Hobson
Publisher
Seth Hobson (Community)
Source
wshobson/agents · plugins/llm-application-dev/skills/prompt-engineering-patterns · commit 4bde316
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Seth Hobson.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download prompt-engineering-patterns.zip