Prompt Engineering Patterns
Seth HobsonCommunityCreated by Seth Hobson
- Skill
- Guidelines
- Agent tooling
- MIT
- Low risk
- Has scripts
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/wshobson/prompt-engineering-patterns/downloadUnzip 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
Be Specific: Vague prompts produce inconsistent results
Show, Don't Tell: Examples are more effective than descriptions
Use Structured Outputs: Enforce schemas with Pydantic for reliability
Test Extensively: Evaluate on diverse, representative inputs
Iterate Rapidly: Small changes can have large impacts
Monitor Performance: Track metrics in production
Version Control: Treat prompts as code with proper versioning
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
- ATTRIBUTION.mdAdded by AutoGineer1019 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md5.1 KiB
- assets/few-shot-examples.json4.1 KiB
- assets/prompt-template-library.md3.2 KiB
- references/chain-of-thought.md9.2 KiB
- references/details.md9.0 KiB
- references/few-shot-learning.md10.9 KiB
- references/prompt-optimization.md12.5 KiB
- references/prompt-templates.md11.1 KiB
- references/system-prompts.md5.3 KiB
- scripts/optimize-prompt.pyScript9.3 KiB
references/few-shot-learning.md
Few-Shot Learning Guide
Overview
Few-shot learning enables LLMs to perform tasks by providing a small number of examples (typically 1-10) within the prompt. This technique is highly effective for tasks requiring specific formats, styles, or domain knowledge.
Example Selection Strategies
1. Semantic Similarity
Select examples most similar to the input query using embedding-based retrieval.
from sentence_transformers import SentenceTransformer
import numpy as np
class SemanticExampleSelector:
def __init__(self, examples, model_name='all-MiniLM-L6-v2'):
self.model = SentenceTransformer(model_name)
self.examples = examples
self.example_embeddings = self.model.encode([ex['input'] for ex in examples])
def select(self, query, k=3):
query_embedding = self.model.encode([query])
similarities = np.dot(self.example_embeddings, query_embedding.T).flatten()
top_indices = np.argsort(similarities)[-k:][::-1]
return [self.examples[i] for i in top_indices]Best For: Question answering, text classification, extraction tasks
2. Diversity Sampling
Maximize coverage of different patterns and edge cases.
from sklearn.cluster import KMeans
class DiversityExampleSelector:
def __init__(self, examples, model_name='all-MiniLM-L6-v2'):
self.model = SentenceTransformer(model_name)
self.examples = examples
self.embeddings = self.model.encode([ex['input'] for ex in examples])
def select(self, k=5):
# Use k-means to find diverse cluster centers
kmeans = KMeans(n_clusters=k, random_state=42)
kmeans.fit(self.embeddings)
# Select example closest to each cluster center
diverse_examples = []
for center in kmeans.cluster_centers_:
distances = np.linalg.norm(self.embeddings - center, axis=1)
closest_idx = np.argmin(distances)
diverse_examples.append(self.examples[closest_idx])
return diverse_examplesBest For: Demonstrating task variability, edge case handling
3. Difficulty-Based Selection
Gradually increase example complexity to scaffold learning.
class ProgressiveExampleSelector:
def __init__(self, examples):
# Examples should have 'difficulty' scores (0-1)
self.examples = sorted(examples, key=lambda x: x['difficulty'])
def select(self, k=3):
# Select examples with linearly increasing difficulty
step = len(self.examples) // k
return [self.examples[i * step] for i in range(k)]Best For: Complex reasoning tasks, code generation
4. Error-Based Selection
Include examples that address common failure modes.
class ErrorGuidedSelector:
def __init__(self, examples, error_patterns):
self.examples = examples
self.error_patterns = error_patterns # Common mistakes to avoid
def select(self, query, k=3):
# Select examples demonstrating correct handling of error patterns
selected = []
for pattern in self.error_patterns[:k]:
matching = [ex for ex in self.examples if pattern in ex['demonstrates']]
if matching:
selected.append(matching[0])
return selectedBest For: Tasks with known failure patterns, safety-critical applications
Example Construction Best Practices
Format Consistency
All examples should follow identical formatting:
# Good: Consistent format
examples = [
{
"input": "What is the capital of France?",
"output": "Paris"
},
{
"input": "What is the capital of Germany?",
"output": "Berlin"
}
]
# Bad: Inconsistent format
examples = [
"Q: What is the capital of France? A: Paris",
{"question": "What is the capital of Germany?", "answer": "Berlin"}
]Input-Output Alignment
Ensure examples demonstrate the exact task you want the model to perform:
# Good: Clear input-output relationship
example = {
"input": "Sentiment: The movie was terrible and boring.",
"output": "Negative"
}
# Bad: Ambiguous relationship
example = {
"input": "The movie was terrible and boring.",
"output": "This review expresses negative sentiment toward the film."
}Complexity Balance
Include examples spanning the expected difficulty range:
examples = [
# Simple case
{"input": "2 + 2", "output": "4"},
# Moderate case
{"input": "15 * 3 + 8", "output": "53"},
# Complex case
{"input": "(12 + 8) * 3 - 15 / 5", "output": "57"}
]Context Window Management
Token Budget Allocation
Typical distribution for a 4K context window:
System Prompt: 500 tokens (12%)
Few-Shot Examples: 1500 tokens (38%)
User Input: 500 tokens (12%)
Response: 1500 tokens (38%)Dynamic Example Truncation
class TokenAwareSelector:
def __init__(self, examples, tokenizer, max_tokens=1500):
self.examples = examples
self.tokenizer = tokenizer
self.max_tokens = max_tokens
def select(self, query, k=5):
selected = []
total_tokens = 0
# Start with most relevant examples
candidates = self.rank_by_relevance(query)
for example in candidates[:k]:
example_tokens = len(self.tokenizer.encode(
f"Input: {example['input']}\nOutput: {example['output']}\n\n"
))
if total_tokens + example_tokens <= self.max_tokens:
selected.append(example)
total_tokens += example_tokens
else:
break
return selectedEdge Case Handling
Include Boundary Examples
edge_case_examples = [
# Empty input
{"input": "", "output": "Please provide input text."},
# Very long input (truncated in example)
{"input": "..." + "word " * 1000, "output": "Input exceeds maximum length."},
# Ambiguous input
{"input": "bank", "output": "Ambiguous: Could refer to financial institution or river bank."},
# Invalid input
{"input": "!@#$%", "output": "Invalid input format. Please provide valid text."}
]Few-Shot Prompt Templates
Classification Template
def build_classification_prompt(examples, query, labels):
prompt = f"Classify the text into one of these categories: {', '.join(labels)}\n\n"
for ex in examples:
prompt += f"Text: {ex['input']}\nCategory: {ex['output']}\n\n"
prompt += f"Text: {query}\nCategory:"
return promptExtraction Template
def build_extraction_prompt(examples, query):
prompt = "Extract structured information from the text.\n\n"
for ex in examples:
prompt += f"Text: {ex['input']}\nExtracted: {json.dumps(ex['output'])}\n\n"
prompt += f"Text: {query}\nExtracted:"
return promptTransformation Template
def build_transformation_prompt(examples, query):
prompt = "Transform the input according to the pattern shown in examples.\n\n"
for ex in examples:
prompt += f"Input: {ex['input']}\nOutput: {ex['output']}\n\n"
prompt += f"Input: {query}\nOutput:"
return promptEvaluation and Optimization
Example Quality Metrics
def evaluate_example_quality(example, validation_set):
metrics = {
'clarity': rate_clarity(example), # 0-1 score
'representativeness': calculate_similarity_to_validation(example, validation_set),
'difficulty': estimate_difficulty(example),
'uniqueness': calculate_uniqueness(example, other_examples)
}
return metricsA/B Testing Example Sets
class ExampleSetTester:
def __init__(self, llm_client):
self.client = llm_client
def compare_example_sets(self, set_a, set_b, test_queries):
results_a = self.evaluate_set(set_a, test_queries)
results_b = self.evaluate_set(set_b, test_queries)
return {
'set_a_accuracy': results_a['accuracy'],
'set_b_accuracy': results_b['accuracy'],
'winner': 'A' if results_a['accuracy'] > results_b['accuracy'] else 'B',
'improvement': abs(results_a['accuracy'] - results_b['accuracy'])
}
def evaluate_set(self, examples, test_queries):
correct = 0
for query in test_queries:
prompt = build_prompt(examples, query['input'])
response = self.client.complete(prompt)
if response == query['expected_output']:
correct += 1
return {'accuracy': correct / len(test_queries)}Advanced Techniques
Meta-Learning (Learning to Select)
Train a small model to predict which examples will be most effective:
from sklearn.ensemble import RandomForestClassifier
class LearnedExampleSelector:
def __init__(self):
self.selector_model = RandomForestClassifier()
def train(self, training_data):
# training_data: list of (query, example, success) tuples
features = []
labels = []
for query, example, success in training_data:
features.append(self.extract_features(query, example))
labels.append(1 if success else 0)
self.selector_model.fit(features, labels)
def extract_features(self, query, example):
return [
semantic_similarity(query, example['input']),
len(example['input']),
len(example['output']),
keyword_overlap(query, example['input'])
]
def select(self, query, candidates, k=3):
scores = []
for example in candidates:
features = self.extract_features(query, example)
score = self.selector_model.predict_proba([features])[0][1]
scores.append((score, example))
return [ex for _, ex in sorted(scores, reverse=True)[:k]]Adaptive Example Count
Dynamically adjust the number of examples based on task difficulty:
class AdaptiveExampleSelector:
def __init__(self, examples):
self.examples = examples
def select(self, query, max_examples=5):
# Start with 1 example
for k in range(1, max_examples + 1):
selected = self.get_top_k(query, k)
# Quick confidence check (could use a lightweight model)
if self.estimated_confidence(query, selected) > 0.9:
return selected
return selected # Return max_examples if never confident enoughCommon Mistakes
Too Many Examples: More isn't always better; can dilute focus
Irrelevant Examples: Examples should match the target task closely
Inconsistent Formatting: Confuses the model about output format
Overfitting to Examples: Model copies example patterns too literally
Ignoring Token Limits: Running out of space for actual input/output
Resources
Example dataset repositories
Pre-built example selectors for common tasks
Evaluation frameworks for few-shot performance
Token counting utilities for different models
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 or Seth Hobson.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download prompt-engineering-patterns.zip