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/chain-of-thought.md

Chain-of-Thought Prompting

Overview

Chain-of-Thought (CoT) prompting elicits step-by-step reasoning from LLMs, dramatically improving performance on complex reasoning, math, and logic tasks.

Core Techniques

Zero-Shot CoT

Add a simple trigger phrase to elicit reasoning:

def zero_shot_cot(query):
    return f"""{query}

Let's think step by step:"""

# Example
query = "If a train travels 60 mph for 2.5 hours, how far does it go?"
prompt = zero_shot_cot(query)

# Model output:
# "Let's think step by step:
# 1. Speed = 60 miles per hour
# 2. Time = 2.5 hours
# 3. Distance = Speed × Time
# 4. Distance = 60 × 2.5 = 150 miles
# Answer: 150 miles"
Few-Shot CoT

Provide examples with explicit reasoning chains:

few_shot_examples = """
Q: Roger has 5 tennis balls. He buys 2 more cans of tennis balls. Each can has 3 balls. How many tennis balls does he have now?
A: Let's think step by step:
1. Roger starts with 5 balls
2. He buys 2 cans, each with 3 balls
3. Balls from cans: 2 × 3 = 6 balls
4. Total: 5 + 6 = 11 balls
Answer: 11

Q: The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many do they have?
A: Let's think step by step:
1. Started with 23 apples
2. Used 20 for lunch: 23 - 20 = 3 apples left
3. Bought 6 more: 3 + 6 = 9 apples
Answer: 9

Q: {user_query}
A: Let's think step by step:"""
Self-Consistency

Generate multiple reasoning paths and take the majority vote:

import openai
from collections import Counter

def self_consistency_cot(query, n=5, temperature=0.7):
    prompt = f"{query}\n\nLet's think step by step:"

    responses = []
    for _ in range(n):
        response = openai.ChatCompletion.create(
            model="gpt-5.4",
            messages=[{"role": "user", "content": prompt}],
            temperature=temperature
        )
        responses.append(extract_final_answer(response))

    # Take majority vote
    answer_counts = Counter(responses)
    final_answer = answer_counts.most_common(1)[0][0]

    return {
        'answer': final_answer,
        'confidence': answer_counts[final_answer] / n,
        'all_responses': responses
    }

Advanced Patterns

Least-to-Most Prompting

Break complex problems into simpler subproblems:

def least_to_most_prompt(complex_query):
    # Stage 1: Decomposition
    decomp_prompt = f"""Break down this complex problem into simpler subproblems:

Problem: {complex_query}

Subproblems:"""

    subproblems = get_llm_response(decomp_prompt)

    # Stage 2: Sequential solving
    solutions = []
    context = ""

    for subproblem in subproblems:
        solve_prompt = f"""{context}

Solve this subproblem:
{subproblem}

Solution:"""
        solution = get_llm_response(solve_prompt)
        solutions.append(solution)
        context += f"\n\nPreviously solved: {subproblem}\nSolution: {solution}"

    # Stage 3: Final integration
    final_prompt = f"""Given these solutions to subproblems:
{context}

Provide the final answer to: {complex_query}

Final Answer:"""

    return get_llm_response(final_prompt)
Tree-of-Thought (ToT)

Explore multiple reasoning branches:

class TreeOfThought:
    def __init__(self, llm_client, max_depth=3, branches_per_step=3):
        self.client = llm_client
        self.max_depth = max_depth
        self.branches_per_step = branches_per_step

    def solve(self, problem):
        # Generate initial thought branches
        initial_thoughts = self.generate_thoughts(problem, depth=0)

        # Evaluate each branch
        best_path = None
        best_score = -1

        for thought in initial_thoughts:
            path, score = self.explore_branch(problem, thought, depth=1)
            if score > best_score:
                best_score = score
                best_path = path

        return best_path

    def generate_thoughts(self, problem, context="", depth=0):
        prompt = f"""Problem: {problem}
{context}

Generate {self.branches_per_step} different next steps in solving this problem:

1."""
        response = self.client.complete(prompt)
        return self.parse_thoughts(response)

    def evaluate_thought(self, problem, thought_path):
        prompt = f"""Problem: {problem}

Reasoning path so far:
{thought_path}

Rate this reasoning path from 0-10 for:
- Correctness
- Likelihood of reaching solution
- Logical coherence

Score:"""
        return float(self.client.complete(prompt))
Verification Step

Add explicit verification to catch errors:

def cot_with_verification(query):
    # Step 1: Generate reasoning and answer
    reasoning_prompt = f"""{query}

Let's solve this step by step:"""

    reasoning_response = get_llm_response(reasoning_prompt)

    # Step 2: Verify the reasoning
    verification_prompt = f"""Original problem: {query}

Proposed solution:
{reasoning_response}

Verify this solution by:
1. Checking each step for logical errors
2. Verifying arithmetic calculations
3. Ensuring the final answer makes sense

Is this solution correct? If not, what's wrong?

Verification:"""

    verification = get_llm_response(verification_prompt)

    # Step 3: Revise if needed
    if "incorrect" in verification.lower() or "error" in verification.lower():
        revision_prompt = f"""The previous solution had errors:
{verification}

Please provide a corrected solution to: {query}

Corrected solution:"""
        return get_llm_response(revision_prompt)

    return reasoning_response

Domain-Specific CoT

Math Problems
math_cot_template = """
Problem: {problem}

Solution:
Step 1: Identify what we know
- {list_known_values}

Step 2: Identify what we need to find
- {target_variable}

Step 3: Choose relevant formulas
- {formulas}

Step 4: Substitute values
- {substitution}

Step 5: Calculate
- {calculation}

Step 6: Verify and state answer
- {verification}

Answer: {final_answer}
"""
Code Debugging
debug_cot_template = """
Code with error:
{code}

Error message:
{error}

Debugging process:
Step 1: Understand the error message
- {interpret_error}

Step 2: Locate the problematic line
- {identify_line}

Step 3: Analyze why this line fails
- {root_cause}

Step 4: Determine the fix
- {proposed_fix}

Step 5: Verify the fix addresses the error
- {verification}

Fixed code:
{corrected_code}
"""
Logical Reasoning
logic_cot_template = """
Premises:
{premises}

Question: {question}

Reasoning:
Step 1: List all given facts
{facts}

Step 2: Identify logical relationships
{relationships}

Step 3: Apply deductive reasoning
{deductions}

Step 4: Draw conclusion
{conclusion}

Answer: {final_answer}
"""

Performance Optimization

Caching Reasoning Patterns
class ReasoningCache:
    def __init__(self):
        self.cache = {}

    def get_similar_reasoning(self, problem, threshold=0.85):
        problem_embedding = embed(problem)

        for cached_problem, reasoning in self.cache.items():
            similarity = cosine_similarity(
                problem_embedding,
                embed(cached_problem)
            )
            if similarity > threshold:
                return reasoning

        return None

    def add_reasoning(self, problem, reasoning):
        self.cache[problem] = reasoning
Adaptive Reasoning Depth
def adaptive_cot(problem, initial_depth=3):
    depth = initial_depth

    while depth <= 10:  # Max depth
        response = generate_cot(problem, num_steps=depth)

        # Check if solution seems complete
        if is_solution_complete(response):
            return response

        depth += 2  # Increase reasoning depth

    return response  # Return best attempt

Evaluation Metrics

def evaluate_cot_quality(reasoning_chain):
    metrics = {
        'coherence': measure_logical_coherence(reasoning_chain),
        'completeness': check_all_steps_present(reasoning_chain),
        'correctness': verify_final_answer(reasoning_chain),
        'efficiency': count_unnecessary_steps(reasoning_chain),
        'clarity': rate_explanation_clarity(reasoning_chain)
    }
    return metrics

Best Practices

  1. Clear Step Markers: Use numbered steps or clear delimiters

  2. Show All Work: Don't skip steps, even obvious ones

  3. Verify Calculations: Add explicit verification steps

  4. State Assumptions: Make implicit assumptions explicit

  5. Check Edge Cases: Consider boundary conditions

  6. Use Examples: Show the reasoning pattern with examples first

Common Pitfalls

  • Premature Conclusions: Jumping to answer without full reasoning

  • Circular Logic: Using the conclusion to justify the reasoning

  • Missing Steps: Skipping intermediate calculations

  • Overcomplicated: Adding unnecessary steps that confuse

  • Inconsistent Format: Changing step structure mid-reasoning

When to Use CoT

Use CoT for:

  • Math and arithmetic problems

  • Logical reasoning tasks

  • Multi-step planning

  • Code generation and debugging

  • Complex decision making

Skip CoT for:

  • Simple factual queries

  • Direct lookups

  • Creative writing

  • Tasks requiring conciseness

  • Real-time, latency-sensitive applications

Resources

  • Benchmark datasets for CoT evaluation

  • Pre-built CoT prompt templates

  • Reasoning verification tools

  • Step extraction and parsing utilities

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