File: README.md
Context Engineering Template
A comprehensive template for getting started with Context Engineering - the discipline of engineering context for AI coding assistants so they have the information necessary to get the job done end to end.
Context Engineering is 10x better than prompt engineering and 100x better than vibe coding.
🚀 Quick Start
# 1. Clone this template
git clone https://github.com/coleam00/Context-Engineering-Intro.git
cd Context-Engineering-Intro
# 2. Set up your project rules (optional - template provided)
# Edit CLAUDE.md to add your project-specific guidelines
# 3. Add examples (highly recommended)
# Place relevant code examples in the examples/ folder
# 4. Create your initial feature request
# Edit INITIAL.md with your feature requirements
# 5. Generate a comprehensive PRP (Product Requirements Prompt)
# In Claude Code, run:
/generate-prp INITIAL.md
# 6. Execute the PRP to implement your feature
# In Claude Code, run:
/execute-prp PRPs/your-feature-name.md📚 Table of Contents
- What is Context Engineering?
- Template Structure
- Step-by-Step Guide
- Writing Effective INITIAL.md Files
- The PRP Workflow
- Using Examples Effectively
- Best Practices
What is Context Engineering?
Context Engineering represents a paradigm shift from traditional prompt engineering:
Prompt Engineering vs Context Engineering
Prompt Engineering:
- Focuses on clever wording and specific phrasing
- Limited to how you phrase a task
- Like giving someone a sticky note
Context Engineering:
- A complete system for providing comprehensive context
- Includes documentation, examples, rules, patterns, and validation
- Like writing a full screenplay with all the details
Why Context Engineering Matters
- Reduces AI Failures: Most agent failures aren't model failures - they're context failures
- Ensures Consistency: AI follows your project patterns and conventions
- Enables Complex Features: AI can handle multi-step implementations with proper context
- Self-Correcting: Validation loops allow AI to fix its own mistakes
Template Structure
context-engineering-intro/
├── .claude/
│ ├── commands/
│ │ ├── generate-prp.md # Generates comprehensive PRPs
│ │ └── execute-prp.md # Executes PRPs to implement features
│ └── settings.local.json # Claude Code permissions
├── PRPs/
│ ├── templates/
│ │ └── prp_base.md # Base template for PRPs
│ └── EXAMPLE_multi_agent_prp.md # Example of a complete PRP
├── examples/ # Your code examples (critical!)
├── CLAUDE.md # Global rules for AI assistant
├── INITIAL.md # Template for feature requests
├── INITIAL_EXAMPLE.md # Example feature request
└── README.md # This fileThis template doesn't focus on RAG and tools with context engineering because I have a LOT more in store for that soon. ;)
Step-by-Step Guide
1. Set Up Global Rules (CLAUDE.md)
The CLAUDE.md file contains project-wide rules that the AI assistant will follow in every conversation. The template includes:
- Project awareness: Reading planning docs, checking tasks
- Code structure: File size limits, module organization
- Testing requirements: Unit test patterns, coverage expectations
- Style conventions: Language preferences, formatting rules
- Documentation standards: Docstring formats, commenting practices
You can use the provided template as-is or customize it for your project.
2. Create Your Initial Feature Request
Edit INITIAL.md to describe what you want to build:
## FEATURE:
[Describe what you want to build - be specific about functionality and requirements]
## EXAMPLES:
[List any example files in the examples/ folder and explain how they should be used]
## DOCUMENTATION:
[Include links to relevant documentation, APIs, or MCP server resources]
## OTHER CONSIDERATIONS:
[Mention any gotchas, specific requirements, or things AI assistants commonly miss]See INITIAL_EXAMPLE.md for a complete example.
3. Generate the PRP
PRPs (Product Requirements Prompts) are comprehensive implementation blueprints that include:
- Complete context and documentation
- Implementation steps with validation
- Error handling patterns
- Test requirements
They are similar to PRDs (Product Requirements Documents) but are crafted more specifically to instruct an AI coding assistant.
Run in Claude Code:
/generate-prp INITIAL.mdNote: The slash commands are custom commands defined in .claude/commands/. You can view their implementation:
.claude/commands/generate-prp.md- See how it researches and creates PRPs.claude/commands/execute-prp.md- See how it implements features from PRPs
The $ARGUMENTS variable in these commands receives whatever you pass after the command name (e.g., INITIAL.md or PRPs/your-feature.md).
This command will:
- Read your feature request
- Research the codebase for patterns
- Search for relevant documentation
- Create a comprehensive PRP in
PRPs/your-feature-name.md
4. Execute the PRP
Once generated, execute the PRP to implement your feature:
/execute-prp PRPs/your-feature-name.mdThe AI coding assistant will:
- Read all context from the PRP
- Create a detailed implementation plan
- Execute each step with validation
- Run tests and fix any issues
- Ensure all success criteria are met
Writing Effective INITIAL.md Files
Key Sections Explained
FEATURE: Be specific and comprehensive
- ❌ "Build a web scraper"
- ✅ "Build an async web scraper using BeautifulSoup that extracts product data from e-commerce sites, handles rate limiting, and stores results in PostgreSQL"
EXAMPLES: Leverage the examples/ folder
- Place relevant code patterns in
examples/ - Reference specific files and patterns to follow
- Explain what aspects should be mimicked
DOCUMENTATION: Include all relevant resources
- API documentation URLs
- Library guides
- MCP server documentation
- Database schemas
OTHER CONSIDERATIONS: Capture important details
- Authentication requirements
- Rate limits or quotas
- Common pitfalls
- Performance requirements
The PRP Workflow
How /generate-prp Works
The command follows this process:
Research Phase
- Analyzes your codebase for patterns
- Searches for similar implementations
- Identifies conventions to follow
Documentation Gathering
- Fetches relevant API docs
- Includes library documentation
- Adds gotchas and quirks
Blueprint Creation
- Creates step-by-step implementation plan
- Includes validation gates
- Adds test requirements
Quality Check
- Scores confidence level (1-10)
- Ensures all context is included
How /execute-prp Works
- Load Context: Reads the entire PRP
- Plan: Creates detailed task list using TodoWrite
- Execute: Implements each component
- Validate: Runs tests and linting
- Iterate: Fixes any issues found
- Complete: Ensures all requirements met
See PRPs/EXAMPLE_multi_agent_prp.md for a complete example of what gets generated.
Using Examples Effectively
The examples/ folder is critical for success. AI coding assistants perform much better when they can see patterns to follow.
What to Include in Examples
Code Structure Patterns
- How you organize modules
- Import conventions
- Class/function patterns
Testing Patterns
- Test file structure
- Mocking approaches
- Assertion styles
Integration Patterns
- API client implementations
- Database connections
- Authentication flows
CLI Patterns
- Argument parsing
- Output formatting
- Error handling
Example Structure
examples/
├── README.md # Explains what each example demonstrates
├── cli.py # CLI implementation pattern
├── agent/ # Agent architecture patterns
│ ├── agent.py # Agent creation pattern
│ ├── tools.py # Tool implementation pattern
│ └── providers.py # Multi-provider pattern
└── tests/ # Testing patterns
├── test_agent.py # Unit test patterns
└── conftest.py # Pytest configurationBest Practices
1. Be Explicit in INITIAL.md
- Don't assume the AI knows your preferences
- Include specific requirements and constraints
- Reference examples liberally
2. Provide Comprehensive Examples
- More examples = better implementations
- Show both what to do AND what not to do
- Include error handling patterns
3. Use Validation Gates
- PRPs include test commands that must pass
- AI will iterate until all validations succeed
- This ensures working code on first try
4. Leverage Documentation
- Include official API docs
- Add MCP server resources
- Reference specific documentation sections
5. Customize CLAUDE.md
- Add your conventions
- Include project-specific rules
- Define coding standards
Resources
File: claude-code-full-guide/README.md
🚀 Full Guide to Using Claude Code
Everything you need to know to crush building anything with Claude Code! This guide takes you from installation through advanced context engineering, subagents, hooks, and parallel agent workflows.
📋 Prerequisites
- Terminal/Command line access
- Node.js installed (for Claude Code installation)
- GitHub account (for GitHub CLI integration)
- Text editor (VS Code recommended)
🔧 Installation
macOS/Linux:
npm install @anthropic-ai/claude-codeWindows (WSL recommended):
See detailed instructions in install_claude_code_windows.md
Verify installation:
claude --version✅ TIP 1: CREATE AND OPTIMIZE CLAUDE.md FILES
Set up context files that Claude automatically pulls into every conversation, containing project-specific information, commands, and guidelines.
mkdir your-folder-name && cd your-folder-name
claudeUse the built-in command:
/initOr create your own CLAUDE.md file based on the template in this repository. See CLAUDE.md for a Python specific example structure that includes:
- Project awareness and context rules
- Code structure guidelines
- Testing requirements
- Task completion workflow
- Style conventions
- Documentation standards
Advanced Prompting Techniques
Power Keywords: Claude responds to certain keywords with enhanced behavior (information dense keywords):
- IMPORTANT: Emphasizes critical instructions that should not be overlooked
- Proactively: Encourages Claude to take initiative and suggest improvements
- Ultra-think: Can trigger more thorough analysis (use sparingly)
Essential Prompt Engineering Tips:
- Avoid prompting for "production-ready" code - this often leads to over-engineering
- Prompt Claude to write scripts to check its work: "After implementing, create a validation script"
- Avoid backward compatibility unless specifically needed - Claude tends to preserve old code unnecessarily
- Focus on clarity and specific requirements rather than vague quality descriptors
File Placement Strategies
Claude automatically reads CLAUDE.md files from multiple locations:
# Root of repository (most common)
./CLAUDE.md # Checked into git, shared with team
./CLAUDE.local.md # Local only, add to .gitignore
# Parent directories (for monorepos)
root/CLAUDE.md # General project info
root/frontend/CLAUDE.md # Frontend-specific context
root/backend/CLAUDE.md # Backend-specific context
# Reference external files for flexibility
echo "Follow best practices in: ~/company/engineering-standards.md" > CLAUDE.mdPro Tip: Many teams keep their CLAUDE.md minimal and reference a shared standards document. This makes it easy to:
- Switch between AI coding assistants
- Update standards without changing every project
- Share best practices across teams
Note: While Claude Code reads CLAUDE.md automatically, other AI coding assistants can use similar context files (such as .cursorrules for Cursor)
✅ TIP 2: SET UP PERMISSION MANAGEMENT
Configure tool allowlists to streamline development while maintaining security for file operations and system commands.
Method 1: Interactive Allowlist
When Claude asks for permission, select "Always allow" for common operations.
Method 2: Use /permissions command
/permissionsThen add:
Edit(for file edits)Bash(git commit:*)(for git commits)Bash(npm:*)(for npm commands)Read(for reading files)Write(for creating files)
Method 3: Create project settings file
Create .claude/settings.local.json:
{
"allowedTools": [
"Edit",
"Read",
"Write",
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(npm:*)",
"Bash(python:*)",
"Bash(pytest:*)"
]
}Security Best Practices:
- Never allow
Bash(rm -rf:*)or similar destructive commands - Use specific command patterns rather than
Bash(*) - Review permissions regularly
- Use different permission sets for different projects
Note: All AI coding assistants have permission management - some built-in, others require manual approval for each action.
✅ TIP 3: MASTER CUSTOM SLASH COMMANDS
Slash commands are the key to adding your own workflows into Claude Code. They live in .claude/commands/ and enable you to create reusable, parameterized workflows.
Built-in Commands
/init- Generate initial CLAUDE.md/permissions- Manage tool permissions/clear- Clear context between tasks/agents- Manage subagents/help- Get help with Claude Code
Custom Command Example
Repository Analysis:
/primerPerforms comprehensive repository analysis to prime Claude Code on your codebase so you can start implemention fixes or new features and it has all the necessary context to do so.
Creating Your Own Commands
- Create a markdown file in
.claude/commands/:
# Command: analyze-performance
Analyze the performance of the file specified in $ARGUMENTS.
## Steps:
1. Read the file at path: $ARGUMENTS
2. Identify performance bottlenecks
3. Suggest optimizations
4. Create a benchmark script- Use the command:
/analyze-performance src/heavy-computation.jsCommands can use $ARGUMENTS to receive parameters and can invoke any of Claude's tools.
Note: Other AI coding assistants can use these commands as regular prompts - just copy the command content and paste it with your arguments.
✅ TIP 4: INTEGRATE MCP SERVERS
Connect Claude Code to Model Context Protocol (MCP) servers for enhanced functionality. Learn more in the MCP documentation.
Add Serena MCP Server - The most powerful coding toolkit:
Make sure you install uvx first. Here is how you do that in WSL with Windows:
sudo snap install astral-uv --classicThen add Serena using the command:
# Install Serena for semantic code analysis and editing
claude mcp add serena -- uvx --from git+https://github.com/oraios/serena serena start-mcp-server --context ide-assistant --project $(pwd)Serena transforms Claude Code into a fully-featured coding agent with:
- Semantic code retrieval and analysis
- Advanced editing capabilities using Language Server Protocol (LSP)
- Support for Python, TypeScript/JavaScript, PHP, Go, Rust, C/C++, Java
- Free and open-source alternative to subscription-based coding assistants
Manage MCP servers:
# List all configured servers
claude mcp list
# Get details about a specific server
claude mcp get serena
# Remove a server
claude mcp remove serenaComing Soon: Archon V2 (HUGE Overhaul) - A comprehensive knowledge and task management backbone for AI coding assistants - enabling true human-AI collaboration on code for the first time.
Note: MCP is integrated with every major AI coding assistant and the servers are managed in a very similar way.
✅ TIP 5: CONTEXT ENGINEERING WITH EXAMPLES
Transform your development workflow from simple prompting to comprehensive context engineering - providing AI with all the information needed for end-to-end implementation.
Quick Start
The PRP (Product Requirements Prompt) framework is a simple 3-step strategy for context engineering:
# 1. Define your requirements with examples and context
# Edit INITIAL.md to include example code and patterns
# 2. Generate a comprehensive PRP
/generate-prp INITIAL.md
# 3. Execute the PRP to implement your feature
/execute-prp PRPs/your-feature-name.mdDefining Your Requirements
Your INITIAL.md should always include:
## FEATURE
Build a user authentication system
## EXAMPLES
- Authentication flow: `examples/auth-flow.js`
- Similar API endpoint: `src/api/users.js`
- Database schema pattern: `src/models/base-model.js`
- Validation approach: `src/validators/user-validator.js`
## DOCUMENTATION
- JWT library docs: https://github.com/auth0/node-jsonwebtoken
- Our API standards: `docs/api-guidelines.md`
## OTHER CONSIDERATIONS
- Use existing error handling patterns
- Follow our standard response format
- Include rate limitingCritical PRP Strategies
Examples: The most powerful tool - provide code snippets, similar features, and patterns to follow
Validation Gates: Ensure comprehensive testing and iteration until all tests pass
No Vibe Coding: Validate PRPs before executing them and the code after execution!
The more specific examples you provide, the better Claude can match your existing patterns and style.
Note: Context engineering works with any AI coding assistant - the PRP framework and example-driven approach are universal principles.
✅ TIP 6: LEVERAGE SUBAGENTS FOR SPECIALIZED TASKS
Subagents are specialized AI assistants that operate in separate context windows with focused expertise. They enable Claude to delegate specific tasks to experts, improving quality and efficiency.
Understanding Subagents
Each subagent:
- Has its own context window (no pollution from main conversation)
- Operates with specialized system prompts
- Can be limited to specific tools
- Works autonomously on delegated tasks
Example Subagents in This Repository
Documentation Manager (.claude/agents/documentation-manager.md):
- Automatically updates docs when code changes
- Ensures README accuracy
- Maintains API documentation
- Creates migration guides
Validation Gates (.claude/agents/validation-gates.md):
- Runs all tests after changes
- Iterates on fixes until tests pass
- Enforces code quality standards
- Never marks tasks complete with failing tests
Creating Your Own Subagents
- Use the
/agentscommand or create a file in.claude/agents/:
---
name: security-auditor
tools: Read, Grep, Glob
---
You are a security auditing specialist focused on identifying and preventing security vulnerabilities...
## Core Responsibilities
1. Review code for OWASP Top 10 vulnerabilities
2. Check for exposed secrets or credentials
3. Validate input sanitization
4. Ensure proper authentication/authorization
...Subagent Best Practices
1. Focused Expertise: Each subagent should have one clear specialty
2. Proactive Descriptions: Use "proactively" in descriptions for automatic invocation:
3. Tool Limitations: Only give subagents the tools they need:
tools: Read, Grep # No write access for review-only agents4. Information Flow Design: Understand how information flows from primary agent → subagent → primary agent. The subagent description is crucial because it tells your primary Claude Code agent when and how to use it. Include clear instructions in the description for how the primary agent should prompt this subagent.
5. One-Shot Context: Subagents don't have full conversation history - they receive a single prompt from your primary agent. Design your subagents with this limitation in mind.
Learn more in the Subagents documentation.
Note: While other AI assistants don't have formal subagents, you can achieve similar results by creating specialized prompts and switching between different conversation contexts.
✅ TIP 7: AUTOMATE WITH HOOKS
Hooks provide deterministic control over Claude Code's behavior through user-defined shell commands that execute at predefined lifecycle events.
Available Hook Events
Claude Code provides several predefined actions you can hook into:
- PreToolUse: Before tool execution (can block operations)
- PostToolUse: After successful tool completion
- UserPromptSubmit: When user submits a prompt
- SubagentStop: When a subagent completes its task
- Stop: When the main agent finishes responding
- SessionStart: At session initialization
- PreCompact: Before context compaction
- Notification: During system notifications
Learn more in the Hooks documentation.
Example Hook: Tool Usage Logging
This repository includes a simple hook example in .claude/hooks/:
log-tool-usage.sh - Logs all tool usage for tracking and debugging:
#!/bin/bash
# Logs tool usage with timestamps
# Creates .claude/logs/tool-usage.log
# No external dependencies requiredSetting Up Hooks
- Create hook script in
.claude/hooks/ - Make it executable:
chmod +x your-hook.sh - Add to settings in
.claude/settings.local.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": ".claude/hooks/log-tool-usage.sh"
}
]
}
]
}
}Hooks ensure certain actions always happen, rather than relying on the AI to remember - perfect for logging, security validations, and build triggers.
Note: Other AI assistants don't have hooks (though Kiro does!), I can almost guarantee they're coming soon for everyone else.
✅ TIP 8: GITHUB CLI INTEGRATION
Set up the GitHub CLI to enable Claude to interact with GitHub for issues, pull requests, and repository management.
# Install GitHub CLI
# Visit: https://github.com/cli/cli#installation
# Authenticate
gh auth login
# Verify setup
gh repo listCustom GitHub Commands
Use the /fix-github-issue command for automated fixes:
/fix-github-issue 123This will:
- Fetch issue details
- Analyze the problem
- Search relevant code
- Implement the fix
- Run tests
- Create a PR
Note: GitHub CLI works with any AI coding assistant - just install it and the AI can use gh commands to interact with your repositories.
✅ TIP 9: SAFE YOLO MODE WITH DEV CONTAINERS
Allow Claude Code to perform any action while maintaining safety through containerization. This enables rapid development without destructive behavior on your host machine.
Prerequisites:
- Install Docker
- VS Code (or compatible editors)
Security Features:
- Network isolation with whitelist
- No access to host filesystem
- Restricted outbound connections
- Safe experimentation environment
Setup Process:
- Open in VS Code and press
F1 - Select "Dev Containers: Reopen in Container"
- Wait for container build
- Open terminal (
Ctrl+J) - Authenticate Claude Code in container
- Run in YOLO mode:bash
claude --dangerously-skip-permissions
Why Use Dev Containers?
- Test dangerous operations safely
- Experiment with system changes
- Rapid prototyping
- Consistent development environment
- No fear of breaking your system
✅ TIP 10: PARALLEL DEVELOPMENT WITH GIT WORKTREES
Use Git worktrees to enable multiple Claude instances working on independent tasks simultaneously, or automate parallel implementations of the same feature.
Manual Worktree Setup
# Create worktrees for different features
git worktree add ../project-auth feature/auth
git worktree add ../project-api feature/api
# Launch Claude in each worktree
cd ../project-auth && claude # Terminal 1
cd ../project-api && claude # Terminal 2Automated Parallel Agents
AI coding assistants are non-deterministic. Running multiple attempts increases success probability and provides implementation options.
Setup parallel worktrees:
/prep-parallel user-system 3Execute parallel implementations:
- Create a plan file (
plan.md) - Run parallel execution:
/execute-parallel user-system plan.md 3Select the best implementation:
# Review results
cat trees/user-system-*/RESULTS.md
# Test each implementation
cd trees/user-system-1 && npm test
# Merge the best
git checkout main
git merge user-system-2Benefits
- No Conflicts: Each instance works in isolation
- Multiple Approaches: Compare different implementations
- Quality Gates: Only consider implementations where tests pass
- Easy Integration: Merge the best solution
🎯 Quick Command Reference
| Command | Purpose |
|---|---|
/init |
Generate initial CLAUDE.md |
/permissions |
Manage tool permissions |
/clear |
Clear context between tasks |
/agents |
Create and manage subagents |
/primer |
Analyze repository structure |
ESC |
Interrupt Claude |
Shift+Tab |
Enter planning mode |
/generate-prp INITIAL.md |
Create implementation blueprint |
/execute-prp PRPs/feature.md |
Implement from blueprint |
/prep-parallel [feature] [count] |
Setup parallel worktrees |
/execute-parallel [feature] [plan] [count] |
Run parallel implementations |
/fix-github-issue [number] |
Auto-fix GitHub issues |
/prep-parallel [feature] [count] |
Setup parallel worktrees |
/execute-parallel [feature] [plan] [count] |
Run parallel implementations |
📚 Additional Resources
🚀 Next Steps
- Start Simple: Set up CLAUDE.md and basic permissions
- Add Slash Commands: Create custom commands for your workflow
- Install MCP Servers: Add Serena for enhanced coding capabilities
- Implement Subagents: Add specialists for your tech stack
- Configure Hooks: Automate repetitive tasks
- Try Parallel Development: Experiment with multiple approaches
Remember: Claude Code is most powerful when you provide clear context, specific examples, and comprehensive validation. Happy coding! 🎉
File: use-cases/template-generator/README.md
Template Generator - Meta-Framework for Context Engineering
This template generator creates complete context engineering template packages for any technology domain. It's a meta-template that generates specialized templates for frameworks like Pydantic AI, Supabase, CrewAI, etc.
🚀 Quick Start
# 1. Define your template requirements in detail
# Edit PRPs/INITIAL.md with specific technology and requirements
# 2. Generate comprehensive template PRP
/generate-template-prp PRPs/INITIAL.md
# 3. Execute the PRP to create complete template package
/execute-template-prp PRPs/template-{technology-name}.md📚 What This Creates
This meta-template generates complete context engineering template packages with:
Generated Template Structure
use-cases/{technology-name}/
├── CLAUDE.md # Technology-specific global rules
├── .claude/commands/
│ ├── generate-{tech}-prp.md # Domain PRP generation
│ └── execute-{tech}-prp.md # Domain PRP execution
├── PRPs/
│ ├── templates/
│ │ └── prp_{tech}_base.md # Technology-specific base PRP
│ ├── ai_docs/ # Domain documentation
│ └── INITIAL.md # Example feature request
├── examples/ # Technology-specific examples
└── README.md # Usage guideTemplate Features
Technology Specialization:
- Framework-specific global rules and patterns
- Technology-appropriate validation loops
- Domain-specific research methodologies
- Framework-specialized documentation references
Web Research Integration:
- Extensive web search requirements for technology research
- Official documentation gathering and analysis
- Real-world pattern identification and extraction
- Best practices and gotcha documentation
Context Engineering Adaptation:
- PRP framework adapted for specific technologies
- Domain-appropriate success criteria
- Technology-specific implementation blueprints
- Framework-specialized validation gates
🔍 Research-Driven Approach
This meta-template emphasizes extensive web research as the foundation for creating high-quality templates:
- Technology Deep Dive - Comprehensive research of official docs, patterns, and best practices
- Pattern Extraction - Identification of real-world implementation patterns
- Context Integration - Adaptation of context engineering principles for the technology
- Validation Design - Creation of technology-appropriate testing and validation loops
📋 Usage Process
1. Define Requirements (PRPs/INITIAL.md)
Be extremely specific about:
- Target technology/framework
- Core features to support
- Examples to include
- Documentation to research
- Development patterns
- Security considerations
- Common gotchas
- Validation requirements
2. Generate Template PRP
/generate-template-prp PRPs/INITIAL.mdThis will:
- Conduct extensive web research on your specified technology
- Analyze official documentation and best practices
- Create comprehensive implementation blueprint
- Design technology-specific validation loops
3. Execute Template Generation
/execute-template-prp PRPs/template-{technology-name}.mdThis will:
- Create complete template package directory structure
- Generate technology-specific CLAUDE.md with global rules
- Create specialized PRP commands for the technology
- Develop domain-specific base PRP template
- Include working examples and comprehensive documentation
🎯 Template Quality Standards
Generated templates include:
Comprehensive Research Foundation:
- Extensive web research on target technology
- Official documentation analysis and integration
- Real-world pattern identification
- Best practices and gotcha documentation
Technology Specialization:
- Framework-specific patterns and conventions
- Domain-appropriate architectural guidance
- Technology-specific validation and testing approaches
- Integration patterns for common use cases
Context Engineering Integration:
- Proper adaptation of PRP framework principles
- Technology-appropriate success criteria
- Domain-specific research methodologies
- Specialized validation loops and quality gates
🔧 Key Features
Web Research Emphasis
- Web search is your best friend throughout the process
- Comprehensive technology documentation analysis
- Real-world implementation pattern identification
- Community best practices research and integration
Template Package Completeness
- Complete directory structure with all required files
- Technology-specific global rules and patterns
- Specialized PRP generation and execution commands
- Domain-appropriate base PRP templates
- Working examples and comprehensive documentation
Quality Validation
- Multiple validation levels for template structure and content
- Technology-specific testing and validation approaches
- Integration testing with base context engineering framework
- Usability validation for immediate developer productivity
📚 Examples of Templates You Can Generate
- Pydantic AI Agents - AI agent development with tool integration
- Supabase Applications - Full-stack apps with real-time features
- CrewAI Multi-Agents - Complex multi-agent system development
- FastAPI Services - High-performance API development
- React Applications - Modern frontend development patterns
- Any Technology - The system adapts to any framework or library
🚫 Anti-Patterns Avoided
- ❌ Generic templates without technology specialization
- ❌ Shallow research leading to incomplete patterns
- ❌ Missing validation loops and quality gates
- ❌ Ignoring framework-specific best practices
- ❌ Incomplete documentation and examples
🔄 Continuous Improvement
Templates generated with this system:
- Are based on comprehensive, current research
- Include real-world patterns and best practices
- Provide immediate developer productivity
- Can be updated as technologies evolve
- Maintain consistency with context engineering principles
🎓 Philosophy
This meta-template embodies the principle that context engineering can be applied to any technology domain through:
- Deep Research - Understanding the technology thoroughly
- Pattern Extraction - Identifying reusable implementation patterns
- Context Integration - Adapting context engineering principles
- Quality Validation - Ensuring templates work immediately and effectively
The result is a systematic approach to creating high-quality, immediately usable context engineering templates for any technology domain.
File: use-cases/pydantic-ai/README.md
Pydantic AI Context Engineering Template
A comprehensive template for building production-grade AI agents using Pydantic AI with context engineering best practices, tools integration, structured outputs, and comprehensive testing patterns.
🚀 Quick Start - Copy Template
Get started in 2 minutes:
# Clone the context engineering repository
git clone https://github.com/coleam00/Context-Engineering-Intro.git
cd Context-Engineering-Intro/use-cases/pydantic-ai
# 1. Copy this template to your new project
python copy_template.py /path/to/my-agent-project
# 2. Navigate to your project
cd /path/to/my-agent-project
# 3. Start building with the PRP workflow
# Fill out PRPs/INITIAL.md with the agent you want to create
# 4. Generate the PRP based on your detailed requirements (validate the PRP after generating!)
/generate-pydantic-ai-prp PRPs/INITIAL.md
# 5. Execute the PRP to create your Pydantic AI agent
/execute-pydantic-ai-prp PRPs/generated_prp.mdIf you are not using Claude Code, you can simply tell your AI coding assistant to use the generate-pydantic-ai-prp and execute-pydantic-ai-prp slash commands in .claude/commands as prompts.
📖 What is This Template?
This template provides everything you need to build sophisticated Pydantic AI agents using proven context engineering workflows. It combines:
- Pydantic AI Best Practices: Type-safe agents with tools, structured outputs, and dependency injection
- Context Engineering Workflows: Proven PRP (Product Requirements Prompts) methodology
- Working Examples: Complete agent implementations you can learn from and extend
🎯 PRP Framework Workflow
This template uses a 3-step context engineering workflow for building AI agents:
1. **Define Requirements** (`PRPs/INITIAL.md`)
Start by clearly defining what your agent needs to do:
# Customer Support Agent - Initial Requirements
## Overview
Build an intelligent customer support agent that can handle inquiries,
access customer data, and escalate issues appropriately.
## Core Requirements
- Multi-turn conversations with context and memory
- Customer authentication and account access
- Account balance and transaction queries
- Payment processing and refund handling
...2. **Generate Implementation Plan**
/generate-pydantic-ai-prp PRPs/INITIAL.mdThis creates a comprehensive 'Product Requirements Prompts' document that includes:
- Pydantic AI technology research and best practices
- Agent architecture design with tools and dependencies
- Implementation roadmap with validation loops
- Security patterns and production considerations
3. **Execute Implementation**
/execute-pydantic-ai-prp PRPs/your_agent.mdThis implements the complete agent based on the PRP, including:
- Agent creation with proper model provider configuration
- Tool integration with error handling and validation
- Structured output models with Pydantic validation
- Comprehensive testing with TestModel and FunctionModel
📂 Template Structure
pydantic-ai/
├── CLAUDE.md # Pydantic AI global development rules
├── copy_template.py # Template deployment script
├── .claude/commands/
│ ├── generate-pydantic-ai-prp.md # PRP generation for agents
│ └── execute-pydantic-ai-prp.md # PRP execution for agents
├── PRPs/
│ ├── templates/
│ │ └── prp_pydantic_ai_base.md # Base PRP template for agents
│ └── INITIAL.md # Example agent requirements
├── examples/
│ ├── basic_chat_agent/ # Simple conversational agent
│ │ ├── agent.py # Agent with memory and context
│ │ └── README.md # Usage guide
│ ├── tool_enabled_agent/ # Agent with external tools
│ │ ├── agent.py # Web search + calculator tools
│ │ └── requirements.txt # Dependencies
│ └── testing_examples/ # Comprehensive testing patterns
│ ├── test_agent_patterns.py # TestModel, FunctionModel examples
│ └── pytest.ini # Test configuration
└── README.md # This file🤖 Agent Examples Included
1. Main Agent Reference (`examples/main_agent_reference/`)
The canonical reference implementation showing proper Pydantic AI patterns:
- Environment-based configuration with
settings.pyandproviders.py - Clean separation of concerns between email and research agents
- Proper file structure to separate prompts, tools, agents, and Pydantic models
- Tool integration with external APIs (Gmail, Brave Search)
Key Files:
settings.py: Environment configuration with pydantic-settingsproviders.py: Model provider abstraction withget_llm_model()research_agent.py: Multi-tool agent with web search and email integrationemail_agent.py: Specialized agent for Gmail draft creation
2. Basic Chat Agent (`examples/basic_chat_agent/`)
A simple conversational agent demonstrating core patterns:
- Environment-based model configuration (follows main_agent_reference)
- String output by default (no
result_typeunless needed) - System prompts (static and dynamic)
- Conversation memory with dependency injection
Key Features:
- Simple string responses (not structured output)
- Settings-based configuration pattern
- Conversation context tracking
- Clean, minimal implementation
3. Tool-Enabled Agent (`examples/tool_enabled_agent/`)
An agent with tool integration capabilities:
- Environment-based configuration (follows main_agent_reference)
- String output by default (no unnecessary structure)
- Web search and calculation tools
- Error handling and retry mechanisms
Key Features:
@agent.tooldecorator patterns- RunContext for dependency injection
- Tool error handling and recovery
- Simple string responses from tools
4. Structured Output Agent (`examples/structured_output_agent/`)
NEW: Shows when to use result_type for data validation:
- Environment-based configuration (follows main_agent_reference)
- Structured output with Pydantic validation (when specifically needed)
- Data analysis with statistical tools
- Professional report generation
Key Features:
- Demonstrates proper use of
result_type - Pydantic validation for business reports
- Data analysis tools with numerical statistics
- Clear documentation on when to use structured vs string output
5. Testing Examples (`examples/testing_examples/`)
Comprehensive testing patterns for Pydantic AI agents:
- TestModel for rapid development validation
- FunctionModel for custom behavior testing
- Agent.override() for test isolation
- Pytest fixtures and async testing
Key Features:
- Unit testing without API costs
- Mock dependency injection
- Tool validation and error scenario testing
- Integration testing patterns
📚 Additional Resources
- Official Pydantic AI Documentation: https://ai.pydantic.dev/
- Context Engineering Methodology: See main repository README
🆘 Support & Contributing
- Issues: Report problems with the template or examples
- Improvements: Contribute additional examples or patterns
- Questions: Ask about Pydantic AI integration or context engineering
This template is part of the larger Context Engineering framework. See the main repository for more context engineering templates and methodologies.
Ready to build production-grade AI agents? Start with python copy_template.py my-agent-project and follow the PRP workflow! 🚀
File: use-cases/mcp-server/PRPs/README.md
Product Requirement Prompt (PRP) Concept
"Over-specifying what to build while under-specifying the context, and how to build it, is why so many AI-driven coding attempts stall at 80%. A Product Requirement Prompt (PRP) fixes that by fusing the disciplined scope of a classic Product Requirements Document (PRD) with the “context-is-king” mindset of modern prompt engineering."
What is a PRP?
Product Requirement Prompt (PRP)
A PRP is a structured prompt that supplies an AI coding agent with everything it needs to deliver a vertical slice of working software—no more, no less.
How it differs from a PRD
A traditional PRD clarifies what the product must do and why customers need it, but deliberately avoids how it will be built.
A PRP keeps the goal and justification sections of a PRD yet adds three AI-critical layers:
Context
- Precise file paths and content, library versions and library context, code snippets examples. LLMs generate higher-quality code when given direct, in-prompt references instead of broad descriptions. Usage of a ai_docs/ directory to pipe in library and other docs.
Implementation Details and Strategy
- In contrast of a traditional PRD, a PRP explicitly states how the product will be built. This includes the use of API endpoints, test runners, or agent patterns (ReAct, Plan-and-Execute) to use. Usage of typehints, dependencies, architectural patterns and other tools to ensure the code is built correctly.
Validation Gates
- Deterministic checks such as pytest, ruff, or static type passes “Shift-left” quality controls catch defects early and are cheaper than late re-work.
Example: Each new funtion should be individaully tested, Validation gate = all tests pass.
PRP Layer Why It Exists
- The PRP folder is used to prepare and pipe PRPs to the agentic coder.
Why context is non-negotiable
Large-language-model outputs are bounded by their context window; irrelevant or missing context literally squeezes out useful tokens
The industry mantra “Garbage In → Garbage Out” applies doubly to prompt engineering and especially in agentic engineering: sloppy input yields brittle code
In short
A PRP is PRD + curated codebase intelligence + agent/runbook—the minimum viable packet an AI needs to plausibly ship production-ready code on the first pass.
The PRP can be small and focusing on a single task or large and covering multiple tasks.
The true power of PRP is in the ability to chain tasks together in a PRP to build, self-validate and ship complex features.
File: use-cases/mcp-server/README.md
MCP Server Builder - Context Engineering Use Case
This use case demonstrates how to use Context Engineering and the PRP (Product Requirements Prompt) process to build production-ready Model Context Protocol (MCP) servers. It provides a proven template and workflow for creating MCP servers with GitHub OAuth authentication, database integration, and Cloudflare Workers deployment.
A PRP is PRD + curated codebase intelligence + agent/runbook—the minimum viable packet an AI needs to plausibly ship production-ready code on the first pass.
🚀 Quick Start
Prerequisites
- Node.js and npm installed
- Cloudflare account (free tier works)
- GitHub account for OAuth
- PostgreSQL database (local or hosted)
Step 1: Setup Your Project
# Clone the context engineering repository
git clone https://github.com/coleam00/Context-Engineering-Intro.git
cd Context-Engineering-Intro/use-cases/mcp-server
# Copy template to your new project directory
python copy_template.py my-mcp-server-project
# Navigate to your new project
cd my-mcp-server-project
# Install dependencies
npm install
# Install Wrangler CLI globally
npm install wrangler
# Authenticate with Cloudflare
wrangler loginWhat copy_template.py does:
- Copies all template files except build artifacts (respects .gitignore)
- Renames README.md to README_TEMPLATE.md (so you can create your own README)
- Includes all source code, examples, tests, and configuration files
- Preserves the complete context engineering setup
🎯 What You'll Learn
This use case teaches you how to:
- Use the PRP process to systematically build complex MCP servers
- Leverage specialized context engineering for MCP development
- Follow proven patterns from a production-ready MCP server template
- Implement secure authentication with GitHub OAuth and role-based access
- Deploy to Cloudflare Workers with monitoring and error handling
📋 How It Works - The PRP Process for MCP Servers
Step 1 is the Quick Start setup above - clone repo, copy template, install dependencies, setup Wrangler
Step 2: Define Your MCP Server
Edit PRPs/INITIAL.md to describe your specific MCP server requirements:
## FEATURE:
We want to create a weather MCP server that provides real-time weather data
with caching and rate limiting.
## ADDITIONAL FEATURES:
- Integration with OpenWeatherMap API
- Redis caching for performance
- Rate limiting per user
- Historical weather data access
- Location search and autocomplete
## OTHER CONSIDERATIONS:
- API key management for external services
- Proper error handling for API failures
- Coordinate validation for location queriesStep 3: Generate Your PRP
Use the specialized MCP PRP command to create a comprehensive implementation plan:
/prp-mcp-create INITIAL.mdWhat this does:
- Reads your feature request
- Researches the existing MCP codebase patterns
- Studies authentication and database integration patterns
- Creates a comprehensive PRP in
PRPs/your-server-name.md - Includes all context, validation loops, and step-by-step tasks
It's important after your PRP is generated to validate everything! With the PRP framework, you are meant to be a part of the process to ensure the quality of all context! An execution is only as good as your PRP. Use /prp-mcp-create as a solid starting point.
Step 4: Execute Your PRP
Use the specialized MCP execution command to build your server:
/prp-mcp-execute PRPs/your-server-name.mdWhat this does:
- Loads the complete PRP with all context
- Creates a detailed implementation plan using TodoWrite
- Implements each component following proven patterns
- Runs comprehensive validation (TypeScript, tests, deployment)
- Ensures your MCP server works end-to-end
Step 5: Configure Environment
# Create environment file
cp .dev.vars.example .dev.vars
# Edit .dev.vars with your credentials
# - GitHub OAuth app credentials
# - Database connection string
# - Cookie encryption keyStep 6: Test and Deploy
# Test locally
wrangler dev --config <your wrangler config (.jsonc)>
# Test with MCP Inspector
npx @modelcontextprotocol/inspector@latest
# Connect to: http://localhost:8792/mcp
# Deploy to production
wrangler deploy🏗️ MCP-Specific Context Engineering
This use case includes specialized context engineering components designed specifically for MCP server development:
Specialized Slash Commands
Located in .claude/commands/:
/prp-mcp-create- Generates PRPs specifically for MCP servers/prp-mcp-execute- Executes MCP PRPs with comprehensive validation
These are specialized versions of the generic commands in the root .claude/commands/, but tailored for MCP development patterns.
Specialized PRP Template
The template PRPs/templates/prp_mcp_base.md includes:
- MCP-specific patterns for tool registration and authentication
- Cloudflare Workers configuration for deployment
- GitHub OAuth integration patterns
- Database security and SQL injection protection
- Comprehensive validation loops from TypeScript to production
AI Documentation
The PRPs/ai_docs/ folder contains:
mcp_patterns.md- Core MCP development patterns and security practicesclaude_api_usage.md- How to integrate with Anthropic's API for LLM-powered features
🔧 Template Architecture
This template provides a complete, production-ready MCP server with:
Core Components
src/
├── index.ts # Main authenticated MCP server
├── index_sentry.ts # Version with Sentry monitoring
├── simple-math.ts # Basic MCP example (no auth)
├── github-handler.ts # Complete GitHub OAuth implementation
├── database.ts # PostgreSQL with security patterns
├── utils.ts # OAuth helpers and utilities
├── workers-oauth-utils.ts # HMAC-signed cookie system
└── tools/ # Modular tool registration system
└── register-tools.ts # Central tool registryExample Tools
The examples/ folder shows how to create MCP tools:
database-tools.ts- Example database tools with proper patternsdatabase-tools-sentry.ts- Same tools with Sentry monitoring
Key Features
- 🔐 GitHub OAuth - Complete authentication flow with role-based access
- 🗄️ Database Integration - PostgreSQL with connection pooling and security
- 🛠️ Modular Tools - Clean separation of concerns with central registration
- ☁️ Cloudflare Workers - Global edge deployment with Durable Objects
- 📊 Monitoring - Optional Sentry integration for production
- 🧪 Testing - Comprehensive validation from TypeScript to deployment
🔍 Key Files to Understand
To fully understand this use case, examine these files:
Context Engineering Components
PRPs/templates/prp_mcp_base.md- Specialized MCP PRP template.claude/commands/prp-mcp-create.md- MCP-specific PRP generation.claude/commands/prp-mcp-execute.md- MCP-specific execution
Implementation Patterns
src/index.ts- Complete MCP server with authenticationexamples/database-tools.ts- Tool creation and registration patternssrc/tools/register-tools.ts- Modular tool registration system
Configuration & Deployment
wrangler.jsonc- Cloudflare Workers configuration.dev.vars.example- Environment variable templateCLAUDE.md- Implementation guidelines and patterns
📈 Success Metrics
When you successfully use this process, you'll achieve:
- Fast Implementation - Quickly have an MCP Server with minimal iterations
- Production Ready - Secure authentication, monitoring, and error handling
- Scalable Architecture - Clean separation of concerns and modular design
- Comprehensive Testing - Validation from TypeScript to production deployment
🤝 Contributing
This use case demonstrates the power of Context Engineering for complex software development. To improve it:
- Add new MCP server examples to show different patterns
- Enhance the PRP templates with more comprehensive context
- Improve validation loops for better error detection
- Document edge cases and common pitfalls
The goal is to make MCP server development predictable and successful through comprehensive context engineering.
Ready to build your MCP server? Follow the complete process above: setup your project with the copy template, configure your environment, define your requirements in PRPs/INITIAL.md, then generate and execute your PRP to build your production-ready MCP server.
File: use-cases/build-with-agent-team/README.md
Build with Agent Team
A Claude Code skill for building projects using Agent Teams — Anthropic's multi-agent collaboration feature where multiple Claude instances work in parallel, communicate with each other, and coordinate autonomously. Give it a plan document describing what you want to build, and it spawns a team of specialized agents in tmux split panes to build it together.
Once set up, it's as simple as:
/build-with-agent-team [plan-path] [num-agents]Prerequisites
1. Install tmux
Agent teams use tmux for split-pane visualization so you can see all agents working simultaneously.
macOS:
brew install tmuxLinux (Ubuntu/Debian):
sudo apt update && sudo apt install tmuxLinux (Fedora/RHEL):
sudo dnf install tmuxWindows (WSL required):
Agent teams require WSL (Windows Subsystem for Linux). Native Windows is not supported.
# 1. Install WSL from PowerShell (Admin)
wsl --install
# 2. Restart your computer
# 3. Open WSL and install tmux
sudo apt update && sudo apt install tmuxVerify installation:
tmux -V2. Enable Agent Teams
Agent teams are experimental and disabled by default. Enable by adding to ~/.claude/settings.json:
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}Or export in your shell profile (~/.bashrc or ~/.zshrc):
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1tmux note: Starting a tmux session opens a new shell that does not inherit environment variables from your current terminal. If you enable agent teams via
export, you must run that export inside the tmux session, or add it to your shell profile (~/.bashrc/~/.zshrc) so it loads automatically. Enter tmux first, then set the variable and launch Claude from there. Thesettings.jsonapproach avoids this issue entirely.
Installation
Copy the skill to your personal skills directory:
cp -r build-with-agent-team ~/.claude/skills/Or for project-level use:
cp -r build-with-agent-team .claude/skills/Create Your Plan
Write a markdown document describing what you want to build. This works for:
- Greenfield projects: A new app, API, or system from scratch
- Brownfield features: A new feature in an existing codebase
Your plan should be detailed enough that multiple agents could divide the work. Include:
- What you're building and why
- Tech stack and architecture
- Project structure
- Key components and how they interact
- Data models or API contracts
- Acceptance criteria
See example-plan/session-manager-plan.md for an example.
Usage
/build-with-agent-team [plan-path] [num-agents]Parameters:
| Parameter | Required | Description |
|---|---|---|
plan-path |
Yes | Path to your plan markdown file |
num-agents |
No | Number of agents to spawn. If omitted, determined automatically based on the plan's complexity |
Examples:
# Let the skill determine team size
/build-with-agent-team ./plans/my-project.md
# Specify 3 agents
/build-with-agent-team ./plans/my-project.md 3
# Build a feature in existing codebase
/build-with-agent-team ./docs/new-auth-feature.md 2The skill will:
- Read your plan
- Analyze it to determine agent roles (frontend, backend, database, etc.)
- Spawn agents in tmux split panes
- Coordinate collaboration between agents
- Ensure agents communicate and challenge each other's work
Agent Teams vs Subagents
Claude Code has two ways to parallelize work. Choose based on whether your workers need to communicate:
| Subagents | Agent Teams | |
|---|---|---|
| Context | Runs within main session | Each agent has its own session |
| Communication | Reports back to main agent only | Agents message each other directly |
| Coordination | Main agent manages all work | Shared task list, self-coordination |
| Visibility | Results summarized to main context | Each agent visible in tmux pane |
| Best for | Quick, focused tasks (research, exploration) | Complex builds requiring collaboration |
| Token cost | Lower (results summarized) | Higher (each agent is a separate instance) |
Use subagents when:
- Task is quick and isolated
- You only need the result, not the process
- Cost-sensitive
Use agent teams when:
- Multiple components need to integrate (frontend + backend + database)
- Agents need to agree on interfaces and contracts
- You want to see parallel progress in real-time
- Building something complex enough to warrant coordination overhead
File: use-cases/ai-coding-workflows-foundation/README.md
🚀 AI Coding Workflows
A comprehensive framework for developing effective AI coding workflows, with three phases - Planning, Implementation, and Validation.
🧠 Primary Mental Model
The core philosophy centers around Context Engineering - systematically preparing and organizing information to maximize the effectiveness of AI coding assistants.
📋 Phase 1: Planning
1. 🎨 Vibe Planning
Use the /primer slash command to kickstart your exploration:
- New projects: Research online resources, similar projects, explore architecture and tech stack options
- Existing projects: Analyze and understand the current codebase using the Codebase Analyst sub-agent
- Focus: Unstructured exploration of ideas, concepts, and possibilities
2. 📝 Create INITIAL.md (PRD)
Generate a detailed Product Requirements Document:
- New projects: High-level MVP with supporting documentation references
- Existing projects: Focused, detailed requirements with integration points
3. ⚙️ Context Engineering Components
Prepare these essential elements using slash commands:
- RAG (Retrieval-Augmented Generation)
- Task Management
- Memory Systems
- Prompt Engineering
🛠️ Supporting Tools:
- Archon
- PRP Framework
- Web Search
- GitHub Spec Kit
📊 Plan of Attack
Use the /create-plan slash command to generate a structured implementation strategy based on your INITIAL.md and context engineering setup.
⚡ Phase 2: Implementation
🎯 Execute Task by Task
- Use the
/execute-planslash command to systematically work through your plan of attack - Follow the structured plan created during planning
- Leverage the context engineering foundation
🔍 Trust but Verify
Monitor the AI assistant to ensure it:
- Uses MCP servers correctly
- Reads/edits appropriate files
- Leverages task management properly
- Produces clear "thinking" tokens showing understanding
✅ Phase 3: Validation
📊 Code Review Process
AI Assistant Validation:
- Performs automated code review using the Validator sub-agent
- Runs unit tests
- Runs integration tests
Human Validation:
- Strategic oversight
- Manual testing
🔧 Key Components
🌐 Global Rules
- Subagents coordination (Codebase Analyst & Validator)
- Slash commands integration (
/primer,/create-plan,/execute-plan) - Consistent workflows across phases
🎯 Slash Commands Reference
/primer: Initialize vibe planning phase with exploration prompts/create-plan: Generate structured plan of attack from PRD/execute-plan: Systematically implement the created plan
🤖 Sub-Agents
- Codebase Analyst: Specializes in understanding and analyzing existing codebases
- Validator: Focuses on systematic code review and quality assurance
🏆 Success Factors
- Structured approach: Each phase builds on the previous
- Context preparation: Thorough setup enables better AI performance
- Iterative refinement: Trust but verify at each step
- Tool integration: Leverage specialized tools for specific tasks
This framework transforms ad-hoc AI interactions into a systematic, repeatable process that consistently produces high-quality code and documentation. 🎉
File: use-cases/agent-factory-with-subagents/agents/rag_agent/README.md
🔍 Semantic Search Agent
An intelligent knowledge base search system powered by Pydantic AI and PostgreSQL with PGVector. This agent provides both semantic and hybrid search capabilities with automatic strategy selection and result summarization.
Features
- Semantic Search: Pure vector similarity search using embeddings
- Hybrid Search: Combined semantic and keyword matching for precise results
- Intelligent Strategy Selection: Agent automatically chooses the best search approach
- Result Summarization: Coherent insights generated from search results
- Interactive CLI: Rich command-line interface with real-time streaming
- Multi-Provider Support: Works with any OpenAI-compatible API (OpenAI, Gemini, Ollama, etc.)
Prerequisites
- Python 3.10+
- PostgreSQL with PGVector extension
- LLM API key (OpenAI, Gemini, Ollama, Groq, or any OpenAI-compatible provider)
- Existing database with documents and chunks (schema provided)
Installation
- Clone or copy the agent directory:
cd agents/rag_agent- Install dependencies:
pip install -r requirements.txt- Set up PostgreSQL with PGVector:
# SIMPLEST: Run the SQL in your SQL editor if you are using a platform like Supabase/Postgres
# Or run the schema with psql
psql -d your_database -f sql/schema.sql- Configure environment variables:
cp .env.example .env
# Edit .env with your credentials- Ingest documents into the database:
# This step is required before running the agent
# It will process documents and generate embeddings
python -m ingestion.ingest --documents documents/Configuration
Required Environment Variables
DATABASE_URL: PostgreSQL connection string with PGVectorLLM_PROVIDER: Provider name (openai, anthropic, ollama, etc.)LLM_API_KEY: Your LLM provider API keyLLM_MODEL: Model to use (e.g., gpt-4.1-mini, gemini-2.5-flash)LLM_BASE_URL: API base URL (default: https://api.openai.com/v1)EMBEDDING_MODEL: Embedding model to use (e.g., text-embedding-3-small, text-embedding-3-large)
Usage
Command Line Interface
Run the interactive CLI:
python -m cliThe CLI provides:
- Real-time streaming responses
- Tool execution visibility
- Session persistence
- User preference management
Available Commands
help- Show available commandsinfo- Display system configurationclear- Clear the screenset <key>=<value>- Set preferences (e.g.,set text_weight=0.5)exit/quit- Exit the application
Search Strategies
The agent intelligently selects between two search strategies:
Semantic Search
Best for conceptual queries and finding related content:
- "concepts similar to machine learning"
- "ideas about artificial intelligence"
- "related to neural networks"
Hybrid Search
Best for specific facts and technical terms:
- "OpenAI GPT-4 specifications"
- "NASDAQ:NVDA stock price"
- "specific quote from Sam Altman"
The agent automatically chooses the appropriate strategy based on your query, or you can explicitly request a specific search type in your prompt.
Database Setup
Schema Overview
- documents: Stores full documents with metadata
- chunks: Stores document chunks with embeddings
- match_chunks(): Function for semantic search
- hybrid_search(): Function for combined search
Development
Running Tests
pytest tests/Code Formatting
black .
ruff check .Project Structure
semantic_search_agent/
├── agent.py # Main agent implementation
├── cli.py # Command-line interface
├── dependencies.py # Agent dependencies
├── providers.py # Model providers
├── prompts.py # System prompts
├── settings.py # Configuration
├── tools.py # Search tools
├── ingestion/ # Document ingestion pipeline
├── sql/ # Database schema
└── documents/ # Sample documentsFile: use-cases/agent-factory-with-subagents/README.md
🏭 AI Agent Factory with Claude Code Subagents
A powerful yet simple orchestration framework that leverages Claude Code's subagent capabilities to autonomously build AI agents using Pydantic AI. This system transforms even basic requirements into fully-functional, tested, and documented AI agents through a coordinated workflow of specialized subagents. This can achieve in minutes what traditionally took hours or days of development.
Full Example: For a complete, runnable AI agent built with this framework, see the Hybrid Search RAG Agent which includes full setup instructions and documentation.
🚦 Getting Started
- Request an agent: Open Claude Code in this directory and ask for an AI Agent (see examples below, your prompt can be simple)
- Answer clarifications: Provide 2-3 quick answers about your needs
- Watch the magic: Subagents work in parallel to build your agent in a new folder in
agents/ - Receive your agent: Complete with tests, docs, and setup instructions
🎯 Why Subagents?
Claude Code subagents have been all the rage, and for good reason. With subagents we get:
**Parallel Execution & Scalability**
- Run many specialized agents simultaneously, dramatically reducing development time
- Each subagent operates independently with its own context window
- Orchestrate complex workflows without context pollution or token limitations
**Specialized System Prompts**
- Each subagent has a focused, task-specific prompt optimized for its role
- Prevents prompt dilution and maintains specialized expertise across tasks
- Enables deep domain knowledge without compromising general capabilities
**Modular Architecture**
- Cleanly separated concerns with independent configuration and tools
- Reusable components that can be versioned and shared across projects
- Easy to extend, modify, or replace individual subagents without affecting others
🏗️ Subagent Workflow Architecture
┌─────────────────┐
│ User Request │
└────────┬────────┘
▼
┌─────────────────────┐
│ Phase 0: Clarify │
└────────┬────────────┘
▼
┌─────────────────────┐
│ Phase 1: Planner │
└────────┬────────────┘
▼
┌─────────────────────────────────────┐
│ Phase 2: Parallel Development │
│ ┌─────────────┬─────────────┬──────┴───────┐
│ │ Prompt │ Tool │ Dependency │
│ │ Engineer │ Integrator │ Manager │
│ └─────────────┴─────────────┴──────────────┘
└────────┬────────────────────────────┘
▼
┌─────────────────────┐
│ Phase 3: Implement │
└────────┬────────────┘
▼
┌─────────────────────┐
│ Phase 4: Validator │
└────────┬────────────┘
▼
┌─────────────────────┐
│ Phase 5: Delivery │
└─────────────────────┘Workflow Phases for the AI Agent Factory
- Phase 0: Clarification - Main agent asks targeted questions to understand requirements
- Phase 1: Requirements Documentation - Planner subagent creates comprehensive specifications
- Phase 2: Parallel Component Development - Three specialized subagents work simultaneously:
- Prompt Engineer: Designs optimal system prompts
- Tool Integrator: Plans tool implementations and API integrations
- Dependency Manager: Configures environment and dependencies
- Phase 3: Implementation - Main agent builds the complete agent using specifications
- Phase 4: Validation - Validator subagent creates tests and verifies functionality
- Phase 5: Delivery - Documentation and final packaging
📁 Project Structure
.
├── CLAUDE.md # Central orchestration rules and workflow
├── agents/ # Generated AI agents
│ ├── rag_agent/ # Example: Complete RAG agent implementation
│ └── your_agent_here/ # Whatever agent you create with the factory will go here
├── examples/ # Pydantic AI patterns and references
│ ├── main_agent_reference/ # Reference implementation patterns
│ └── rag_pipeline/ # RAG infrastructure components
│ CLAUDE.md # The global rules that instruct Claude Code on the AI Agent Factory workflow
└── README.md # This file🤖 The Subagents
**pydantic-ai-planner**
Creates minimal, focused requirements documents (INITIAL.md) with MVP mindset. Analyzes user needs and produces clear specifications for agent development.
**pydantic-ai-prompt-engineer**
Designs concise system prompts (100-300 words) that define agent behavior. Specializes in creating clear, effective prompts for Pydantic AI agents.
**pydantic-ai-tool-integrator**
Plans tool specifications focusing on 2-3 essential functions. Defines tool parameters, error handling, and integration patterns.
**pydantic-ai-dependency-manager**
Configures minimal dependencies and environment variables. Sets up model providers, database connections, and agent initialization.
**pydantic-ai-validator**
Creates comprehensive test suites using TestModel and FunctionModel. Validates requirements, tests functionality, and ensures production readiness.
🎨 CLAUDE.md - The Orchestration Engine
The CLAUDE.md file is the heart of the system, containing:
- Workflow triggers: Patterns that activate the agent factory
- Phase definitions: Detailed instructions for each development phase
- Subagent prompts: Specialized instructions for each subagent
- Quality gates: Validation criteria for each phase
- Integration rules: How components work together
Key features:
- Automatic workflow recognition from user requests
- Parallel subagent invocation for optimal performance
- Archon integration for project management (optional)
- Comprehensive error handling and recovery
🚀 Example Prompts
Simple Agents
"Build an AI agent that can search the web"
"Create an agent for summarizing documents"
"I need an assistant that can query databases"Complex Agents
"Build a customer support agent that integrates with Slack and searches our knowledge base"
"Create a data analysis agent that can query PostgreSQL and generate visualizations"
"Implement a content generation agent with brand voice customization and SEO optimization"Domain-Specific Agents
"Build a financial analysis agent that can process earnings reports"
"Create a code review agent that follows our team's style guide"
"Implement a research agent that can search academic papers and summarize findings"🔗 Optional Archon Integration
When Archon is available through MCP, the system provides enhanced project management:
- Automatic project creation with task tracking
- Status updates as each phase progresses
- RAG-powered research during implementation
- Persistent project history for iteration and improvement
The Archon integration is optional—the system works perfectly without it, using local TodoWrite for task tracking.
💡 Key Benefits
**Speed**
- Complete agent in 10-15 minutes vs hours of manual development
- Parallel processing reduces sequential bottlenecks
- Automated testing and validation included
**Quality**
- Consistent architecture following best practices
- Comprehensive testing with 80%+ coverage
- Production-ready with error handling and logging
**Flexibility**
- Works with any LLM provider (OpenAI, Anthropic, Gemini, Ollama)
- Supports various databases (PostgreSQL, SQLite, Redis)
- Extensible for custom requirements
**Maintainability**
- Clean separation of concerns
- Well-documented code and APIs
- Reusable components and patterns
📚 Pydantic AI Integration
All agents are built using Pydantic AI, providing:
- Type Safety: Full type hints and runtime validation
- Structured Outputs: Reliable, schema-validated responses
- Dependency Injection: Clean separation of concerns
- Testing Support: TestModel and FunctionModel for comprehensive testing
- Multi-Provider: Support for OpenAI, Anthropic, Gemini, and more
🛠️ Components Explained
Planning Documents
Each agent includes four planning documents:
INITIAL.md- Requirements and specificationsprompts.md- System prompt designtools.md- Tool specificationsdependencies.md- Configuration and dependencies
Implementation Files
agent.py- Main agent logictools.py- Tool implementationssettings.py- Environment configurationproviders.py- LLM providersdependencies.py- Dependency injectioncli.py- Command-line interface
Testing & Validation
- Comprehensive test suite with pytest
- TestModel for development testing
- FunctionModel for behavior validation
- Integration tests for end-to-end verification
The system handles everything else from requirements analysis to implementation, testing, and documentation.
🔮 Future Enhancements
- Additional specialized subagents for specific domains
- Enhanced pattern library for common use cases
- Automated deployment pipeline generation
- Cross-agent communication protocols
- Real-time collaboration features