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

scripts/optimize-prompt.py

#!/usr/bin/env python3
"""
Prompt Optimization Script

Automatically test and optimize prompts using A/B testing and metrics tracking.
"""

import json
import time
from typing import List, Dict, Any
from dataclasses import dataclass
from concurrent.futures import ThreadPoolExecutor
import numpy as np


@dataclass
class TestCase:
    input: Dict[str, Any]
    expected_output: str
    metadata: Dict[str, Any] = None


class PromptOptimizer:
    def __init__(self, llm_client, test_suite: List[TestCase]):
        self.client = llm_client
        self.test_suite = test_suite
        self.results_history = []
        self.executor = ThreadPoolExecutor()

    def shutdown(self):
        """Shutdown the thread pool executor."""
        self.executor.shutdown(wait=True)

    def evaluate_prompt(self, prompt_template: str, test_cases: List[TestCase] = None) -> Dict[str, float]:
        """Evaluate a prompt template against test cases in parallel."""
        if test_cases is None:
            test_cases = self.test_suite

        metrics = {
            'accuracy': [],
            'latency': [],
            'token_count': [],
            'success_rate': []
        }

        def process_test_case(test_case):
            start_time = time.time()

            # Render prompt with test case inputs
            prompt = prompt_template.format(**test_case.input)

            # Get LLM response
            response = self.client.complete(prompt)

            # Measure latency
            latency = time.time() - start_time

            # Calculate individual metrics
            token_count = len(prompt.split()) + len(response.split())
            success = 1 if response else 0
            accuracy = self.calculate_accuracy(response, test_case.expected_output)

            return {
                'latency': latency,
                'token_count': token_count,
                'success_rate': success,
                'accuracy': accuracy
            }

        # Run test cases in parallel
        results = list(self.executor.map(process_test_case, test_cases))

        # Aggregate metrics
        for result in results:
            metrics['latency'].append(result['latency'])
            metrics['token_count'].append(result['token_count'])
            metrics['success_rate'].append(result['success_rate'])
            metrics['accuracy'].append(result['accuracy'])

        return {
            'avg_accuracy': np.mean(metrics['accuracy']),
            'avg_latency': np.mean(metrics['latency']),
            'p95_latency': np.percentile(metrics['latency'], 95),
            'avg_tokens': np.mean(metrics['token_count']),
            'success_rate': np.mean(metrics['success_rate'])
        }

    def calculate_accuracy(self, response: str, expected: str) -> float:
        """Calculate accuracy score between response and expected output."""
        # Simple exact match
        if response.strip().lower() == expected.strip().lower():
            return 1.0

        # Partial match using word overlap
        response_words = set(response.lower().split())
        expected_words = set(expected.lower().split())

        if not expected_words:
            return 0.0

        overlap = len(response_words & expected_words)
        return overlap / len(expected_words)

    def optimize(self, base_prompt: str, max_iterations: int = 5) -> Dict[str, Any]:
        """Iteratively optimize a prompt."""
        current_prompt = base_prompt
        best_prompt = base_prompt
        best_score = 0
        current_metrics = None

        for iteration in range(max_iterations):
            print(f"\nIteration {iteration + 1}/{max_iterations}")

            # Evaluate current prompt
            # Bolt Optimization: Avoid re-evaluating if we already have metrics from previous iteration
            if current_metrics:
                metrics = current_metrics
            else:
                metrics = self.evaluate_prompt(current_prompt)

            print(f"Accuracy: {metrics['avg_accuracy']:.2f}, Latency: {metrics['avg_latency']:.2f}s")

            # Track results
            self.results_history.append({
                'iteration': iteration,
                'prompt': current_prompt,
                'metrics': metrics
            })

            # Update best if improved
            if metrics['avg_accuracy'] > best_score:
                best_score = metrics['avg_accuracy']
                best_prompt = current_prompt

            # Stop if good enough
            if metrics['avg_accuracy'] > 0.95:
                print("Achieved target accuracy!")
                break

            # Generate variations for next iteration
            variations = self.generate_variations(current_prompt, metrics)

            # Test variations and pick best
            best_variation = current_prompt
            best_variation_score = metrics['avg_accuracy']
            best_variation_metrics = metrics

            for variation in variations:
                var_metrics = self.evaluate_prompt(variation)
                if var_metrics['avg_accuracy'] > best_variation_score:
                    best_variation_score = var_metrics['avg_accuracy']
                    best_variation = variation
                    best_variation_metrics = var_metrics

            # Variations are generated deterministically from the prompt, so a
            # round with no improvement would repeat identical evaluations for
            # every remaining iteration.
            if best_variation == current_prompt:
                print("No improving variation found. Stopping optimization.")
                break

            current_prompt = best_variation
            current_metrics = best_variation_metrics

        return {
            'best_prompt': best_prompt,
            'best_score': best_score,
            'history': self.results_history
        }

    def generate_variations(self, prompt: str, current_metrics: Dict) -> List[str]:
        """Generate prompt variations to test."""
        variations = []

        # Variation 1: Add explicit format instruction
        variations.append(prompt + "\n\nProvide your answer in a clear, concise format.")

        # Variation 2: Add step-by-step instruction
        variations.append("Let's solve this step by step.\n\n" + prompt)

        # Variation 3: Add verification step
        variations.append(prompt + "\n\nVerify your answer before responding.")

        # Variation 4: Make more concise
        concise = self.make_concise(prompt)
        if concise != prompt:
            variations.append(concise)

        # Variation 5: Add examples (if none present)
        if "example" not in prompt.lower():
            variations.append(self.add_examples(prompt))

        return variations[:3]  # Return top 3 variations

    def make_concise(self, prompt: str) -> str:
        """Remove redundant words to make prompt more concise."""
        replacements = [
            ("in order to", "to"),
            ("due to the fact that", "because"),
            ("at this point in time", "now"),
            ("in the event that", "if"),
        ]

        result = prompt
        for old, new in replacements:
            result = result.replace(old, new)

        return result

    def add_examples(self, prompt: str) -> str:
        """Add example section to prompt."""
        return f"""{prompt}

Example:
Input: Sample input
Output: Sample output
"""

    def compare_prompts(self, prompt_a: str, prompt_b: str) -> Dict[str, Any]:
        """A/B test two prompts."""
        print("Testing Prompt A...")
        metrics_a = self.evaluate_prompt(prompt_a)

        print("Testing Prompt B...")
        metrics_b = self.evaluate_prompt(prompt_b)

        return {
            'prompt_a_metrics': metrics_a,
            'prompt_b_metrics': metrics_b,
            'winner': 'A' if metrics_a['avg_accuracy'] > metrics_b['avg_accuracy'] else 'B',
            'improvement': abs(metrics_a['avg_accuracy'] - metrics_b['avg_accuracy'])
        }

    def export_results(self, filename: str):
        """Export optimization results to JSON."""
        with open(filename, 'w') as f:
            json.dump(self.results_history, f, indent=2)


def main():
    # Example usage
    test_suite = [
        TestCase(
            input={'text': 'This movie was amazing!'},
            expected_output='Positive'
        ),
        TestCase(
            input={'text': 'Worst purchase ever.'},
            expected_output='Negative'
        ),
        TestCase(
            input={'text': 'It was okay, nothing special.'},
            expected_output='Neutral'
        )
    ]

    # Mock LLM client for demonstration
    class MockLLMClient:
        def complete(self, prompt):
            # Simulate LLM response
            if 'amazing' in prompt:
                return 'Positive'
            elif 'worst' in prompt.lower():
                return 'Negative'
            else:
                return 'Neutral'

    optimizer = PromptOptimizer(MockLLMClient(), test_suite)

    try:
        base_prompt = "Classify the sentiment of: {text}\nSentiment:"

        results = optimizer.optimize(base_prompt)

        print("\n" + "="*50)
        print("Optimization Complete!")
        print(f"Best Accuracy: {results['best_score']:.2f}")
        print(f"Best Prompt:\n{results['best_prompt']}")

        optimizer.export_results('optimization_results.json')
    finally:
        optimizer.shutdown()


if __name__ == '__main__':
    main()

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