prompt-engineering-patterns▌
wshobson/agents · updated Apr 8, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
Advanced prompt engineering techniques for optimizing LLM performance, reliability, and structured outputs in production.
- ›Covers six core capability areas: few-shot learning with dynamic example selection, chain-of-thought reasoning with self-consistency, structured outputs via JSON and Pydantic schemas, iterative prompt optimization, reusable template systems, and role-based system prompt design
- ›Includes practical patterns for semantic example selection, self-verification workflows, pr
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-4-6")
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)
Key Patterns
Pattern 1: Structured Output with Pydantic
from anthropic import Anthropic
from pydantic import BaseModel, Field
from typing import Literal
import json
class SentimentAnalysis(BaseModel):
sentiment: Literal["positive", "negative", "neutral"]
confidence: float = Field(ge=0, le=1)
key_phrases: list[str]
reasoning: str
async def analyze_sentiment(text: str) -> SentimentAnalysis:
"""Analyze sentiment with structured output."""
client = Anthropic()
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=500,
messages=[{
"role": "user",
"content": f"""Analyze the sentiment of this text.
Text: {text}
Respond with JSON matching this schema:
{{
"sentiment": "positive" | "negative" | "neutral",
"confidence": 0.0-1.0,
"key_phrases": ["phrase1", "phrase2"],
"reasoning": "brief explanation"
}}"""
}]
)
return SentimentAnalysis(**json.loads(message.content[0].text))
Pattern 2: Chain-of-Thought with Self-Verification
from langchain_core.prompts import ChatPromptTemplate
cot_prompt = ChatPromptTemplate.from_template("""
Solve this problem step by step.
Problem: {problem}
Instructions:
1. Break down the problem into clear steps
2. Work through each step showing your reasoning
3. State your final answer
4. Verify your answer by checking it against the original problem
Format your response as:
## Steps
[Your step-by-step reasoning]
## Answer
[Your final answer]
## Verification
[Check that your answer is correct]
""")
Pattern 3: Few-Shot with Dynamic Example Selection
from langchain_voyageai import VoyageAIEmbeddings
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_chroma import Chroma
# Create example selector with semantic similarity
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples=[
{"input": "How do I reset my password?", "output": "Go to Settings > Security > Reset Password"},
{"input": "Where can I see my order history?", "output": "Navigate to Account > Orders"},
{"input": "How do I contact support?", "output": "Click Help > Contact Us or email [email protected]"},
],
embeddings=VoyageAIEmbeddings(model="voyage-3-large"),
vectorstore_cls=Chroma,
k=2 # Select 2 most similar examples
)
async def get_few_shot_prompt(query: str) -> str:
"""Build prompt with dynamically selected examples."""
examples = await example_selector.aselect_examples({"input": query})
examples_text = "\n".join(
f"User: {ex['input']}\nAssistant: {ex['output']}"
for ex in examples
)
return f"""You are a helpful customer support assistant.
Here are some example interactions:
{examples_text}
NoHow to use prompt-engineering-patterns on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add prompt-engineering-patterns
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches prompt-engineering-patterns from GitHub repository wshobson/agents and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate prompt-engineering-patterns. Access the skill through slash commands (e.g., /prompt-engineering-patterns) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
User Story & Requirements Generation
Create detailed user stories, acceptance criteria, and feature specs
Example
Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios
Reduce spec writing time by 50%, ensure comprehensive coverage
Competitive Analysis
Research competitors, compare features, identify gaps
Example
Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities
Complete competitive research in 2 hours instead of 2 days
Roadmap Prioritization
Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs
Example
Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale
Make data-driven prioritization decisions faster
Stakeholder Communication
Draft PRDs, status updates, and stakeholder presentations
Example
Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement
Save 3-5 hours/week on communication overhead
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client
- ›Access to product documentation and roadmap tools (Jira, Notion, etc.)
- ›Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
- ›Stakeholder contact information and communication channels
Time Estimate
30-60 minutes to see productivity improvements
Installation Steps
- 1.Install product management skill
- 2.Start with user story generation for known feature
- 3.Progress to competitive analysis: research 2-3 competitors
- 4.Use for roadmap prioritization: apply RICE/ICE scoring
- 5.Draft stakeholder communications and refine based on feedback
- 6.Build template library for recurring PM tasks
- 7.Share effective prompts with product team
Common Pitfalls
- ⚠Not validating competitive research—verify facts before sharing
- ⚠Accepting user stories without involving engineering team
- ⚠Over-relying on frameworks without qualitative judgment
- ⚠Not customizing outputs to company culture and communication style
- ⚠Skipping stakeholder validation of generated requirements
Best Practices▌
✓ Do
- +Validate research and competitive analysis with real data
- +Collaborate with engineering when generating technical requirements
- +Customize frameworks and templates to your company context
- +Use skill for first drafts, refine with stakeholder input
- +Document successful prompt patterns for PM tasks
- +Combine AI efficiency with human judgment and intuition
✗ Don't
- −Don't publish competitive analysis without fact-checking
- −Don't finalize user stories without engineering review
- −Don't make prioritization decisions solely on AI scoring
- −Don't skip customer validation of generated requirements
- −Don't ignore company-specific context and culture
💡 Pro Tips
- ★Provide context: company goals, constraints, customer feedback
- ★Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
- ★Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
- ★Use skill for 70% generation + 30% customization to company needs
When to Use This▌
✓ Use When
Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.
✗ Avoid When
Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.
Learning Path▌
- 1Basic: user stories, feature specs, status updates
- 2Intermediate: competitive analysis, prioritization frameworks, PRDs
- 3Advanced: product strategy, go-to-market planning, OKR setting
- 4Expert: product vision, market positioning, business model innovation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.7★★★★★42 reviews- ★★★★★Aisha Okafor· Dec 20, 2024
Keeps context tight: prompt-engineering-patterns is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Camila Khan· Dec 20, 2024
I recommend prompt-engineering-patterns for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★James Chawla· Dec 12, 2024
prompt-engineering-patterns has been reliable in day-to-day use. Documentation quality is above average for community skills.
- ★★★★★Camila Diallo· Dec 4, 2024
prompt-engineering-patterns reduced setup friction for our internal harness; good balance of opinion and flexibility.
- ★★★★★Aisha Brown· Nov 11, 2024
Registry listing for prompt-engineering-patterns matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Zaid Martinez· Nov 3, 2024
prompt-engineering-patterns fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
- ★★★★★Liam Chawla· Oct 22, 2024
We added prompt-engineering-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
- ★★★★★Arya Yang· Oct 2, 2024
prompt-engineering-patterns reduced setup friction for our internal harness; good balance of opinion and flexibility.
- ★★★★★James Reddy· Sep 25, 2024
prompt-engineering-patterns fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
- ★★★★★Sakshi Patil· Sep 1, 2024
prompt-engineering-patterns has been reliable in day-to-day use. Documentation quality is above average for community skills.
showing 1-10 of 42