This directory contains 16 comprehensive examples demonstrating various features and patterns of the Claude PHP Agent framework. Each example is production-ready and demonstrates best practices.
Most examples also show live progress reporting via callbacks, including the unified Agent::onUpdate() progress stream for iteration updates, tool execution results, and streaming deltas.
What it demonstrates:
- Creating a simple agent with a single tool
- Tool definition and handler implementation
- Input validation and error handling
- Monitoring tool calls and token usage
Key Features:
- ✅ Calculator tool with safe expression evaluation
- ✅ System prompts
- ✅ Token usage tracking
- ✅ Tool call monitoring
Usage:
php examples/basic_agent.phpOutput:
- Solves:
(25 * 17) + (100 / 4) - Shows iterations, tokens used, and tool calls
What it demonstrates:
- Agent with multiple tools
- Tool selection reasoning
- Different tool types (math, string, datetime, random)
- Callback monitoring
Key Features:
- ✅ 4 different tools (calculator, string ops, datetime, random)
- ✅ Intelligent tool selection
- ✅ Real-time tool execution logging
- ✅ Multiple task execution
Usage:
php examples/multi_tool_agent.phpTasks Demonstrated:
- Mathematical calculations
- String manipulation
- Date/time operations
- Random number generation
- Multi-tool workflows
What it demonstrates:
- Generate-Reflect-Refine pattern
- Iterative quality improvement
- Quality scoring and thresholds
- Multiple refinement rounds
Key Features:
- ✅ Self-reflection and critique
- ✅ Quality scoring (1-10)
- ✅ Configurable quality thresholds
- ✅ Refinement history tracking
Usage:
php examples/reflection_agent.phpExamples:
- Code generation with quality checks
- Writing improvement with iterative refinement
What it demonstrates:
- Master-worker pattern
- Specialized worker agents
- Task decomposition and delegation
- Coordinated execution
Key Features:
- ✅ Master coordinator agent
- ✅ Specialized workers (math, writing, research)
- ✅ Task delegation
- ✅ Result aggregation
Usage:
php examples/hierarchical_agent.phpWorkers:
- Math Agent: Numerical calculations
- Writing Agent: Content creation
- Research Agent: Information synthesis
What it demonstrates:
- Zero-shot CoT reasoning
- Few-shot CoT with examples
- Step-by-step problem solving
- Mathematical reasoning
Key Features:
- ✅ Zero-shot CoT trigger
- ✅ Few-shot examples
- ✅ Explicit reasoning steps
- ✅ Math problem solving
Usage:
php examples/cot_example.phpExamples:
- Multi-step mathematical calculations
- Discount and pricing problems
What it demonstrates:
- Tree-based exploration
- Best-first search strategy
- Multiple solution paths
- Complex problem solving
Key Features:
- ✅ Branching factor configuration
- ✅ Depth limiting
- ✅ Path tracking
- ✅ Node evaluation
Usage:
php examples/tot_example.phpExample:
- Solving: "Use 3, 5, 7, 11 to make 24"
What it demonstrates:
- Retrieval-Augmented Generation
- Document management
- Knowledge base queries
- Source tracking
Key Features:
- ✅ Document ingestion
- ✅ Semantic retrieval
- ✅ Context-aware responses
- ✅ Source attribution
Usage:
php examples/rag_example.phpDocuments:
- PHP Basics
- Object-Oriented Programming
- Claude API documentation
What it demonstrates:
- Goal-oriented behavior
- State persistence across sessions
- Progress tracking
- Multi-session execution
Key Features:
- ✅ Goal definition
- ✅ State file persistence
- ✅ Session management
- ✅ Progress percentage
- ✅ Action history
Usage:
# Basic autonomous agent
php examples/autonomous_example.php
# Advanced autonomous agent with detailed examples
php examples/advanced_autonomous_agent.php
# Local test (no API key required)
php examples/autonomous_agent_local_test.phpState Management:
- Session tracking
- Conversation history
- Action history persistence
- Goal tracking and subgoals
- State recovery across sessions
Additional Examples:
advanced_autonomous_agent.php- Multi-session execution, state persistence demoautonomous_agent_local_test.php- Unit-test style examples without API calls
What it demonstrates:
- Real-time token streaming
- StreamingLoop integration
- Console output handlers
- Progressive responses
Key Features:
- ✅ Real-time streaming
- ✅ Console handler
- ✅ Tool execution with streaming
- ✅ Token-by-token output
Usage:
php examples/streaming_example.phpWhat it demonstrates:
- Multiple concurrent stream handlers
- Stream statistics and performance monitoring
- File logging and PSR-3 logging integration
- Custom callback handlers
- Error handling in streams
- Progress tracking
Key Features:
- ✅ Console, File, and Callback handlers simultaneously
- ✅ Real-time performance metrics (bytes/sec, chunks/sec)
- ✅ Iteration and tool execution callbacks
- ✅ Timestamped file logging
- ✅ Stream statistics (duration, throughput, chunk count)
Usage:
php examples/streaming_advanced.php
# Show detailed log file
php examples/streaming_advanced.php --show-logOutput:
- Real-time console output with emoji indicators
- Detailed log file with timestamps and event types
- Performance statistics (speed, duration, chunks)
- Token usage tracking per iteration
What it demonstrates:
- Multi-agent debates
- Pro/Con pattern
- Round table discussions
- Agreement scoring
- Synthesis generation
Key Features:
- ✅ Pro/Con debates
- ✅ Round table format
- ✅ Multiple perspectives
- ✅ Agreement metrics
- ✅ Debate synthesis
Usage:
php examples/debate_example.phpTopics:
- Remote work policies
- Technology stack selection
What it demonstrates:
- Production best practices
- Error handling and retry logic
- Logging and monitoring
- Token tracking and cost estimation
- Configuration management
Key Features:
- ✅ Custom logger integration
- ✅ Retry configuration
- ✅ Timeout handling
- ✅ Token cost estimation
- ✅ Input validation
- ✅ Error recovery
- ✅ Session summaries
Usage:
php examples/production_agent.phpProduction Features:
- PSR-3 logging
- Retry with exponential backoff
- Token usage tracking
- Cost estimation
- Error callbacks
What it demonstrates:
- AMPHP-powered concurrent execution
- Batch processing with concurrency limits
- Parallel tool execution
- Promise-based async workflows
- Performance gains from parallelism
Key Features:
- ✅ Concurrent batch processing
- ✅ Parallel tool executor
- ✅ Promise-based async API
- ✅ Batched execution with concurrency limits
- ✅ Real-time performance comparison
Usage:
php examples/amphp_async_example.phpExamples Covered:
- Batch processing multiple agent tasks concurrently
- Parallel tool execution (weather, time, calculator)
- Promise-based async workflows
- Batched tool execution with concurrency limits
- Async batch processing with promises
What it demonstrates:
- Intelligent alert processing and notification
- LLM-enhanced alert messages
- Multi-channel notifications
- Metric-based threshold alerting
- Alert history tracking
Key Features:
- ✅ Multi-channel routing (console, log file)
- ✅ LLM-enhanced alert messages
- ✅ Alert severity levels
- ✅ Metric integration
- ✅ Context-aware notifications
Usage:
php examples/alert_agent.phpExamples:
- Basic informational alerts
- Metric-based threshold alerts
- Critical alerts with metrics
- Natural language alert processing
What it demonstrates:
- Production alert system patterns
- Multiple notification channels (email, webhook, Slack)
- Custom message templates
- Alert aggregation and deduplication
- Conditional channel routing
Key Features:
- ✅ Multi-channel setup (email, webhook, Slack, PagerDuty)
- ✅ Custom templates per severity
- ✅ Alert aggregation
- ✅ Deduplication logic
- ✅ Conditional routing based on severity
- ✅ Alert statistics and reporting
Usage:
php examples/advanced_alert_agent.phpScenarios Covered:
- System monitoring (CPU, memory, disk)
- Application performance monitoring
- Error rate tracking with aggregation
- Natural language alert processing
What it demonstrates:
- Context window monitoring and management
- Automatic context compaction
- Token estimation and tracking
- Message history manipulation
- Custom compaction strategies
Key Features:
- ✅ Token counting for messages and tools
- ✅ Automatic context compaction
- ✅ Usage percentage monitoring
- ✅ Context editor utilities
- ✅ Custom compaction strategies
- ✅ Agent integration
Usage:
php examples/context_management.phpExamples Covered:
- Token estimation for text and messages
- Context editor utilities
- Keeping recent messages
- Context manager with automatic compaction
- Agent with context management enabled
- Custom compaction strategies
What it demonstrates:
- Complex chain workflows
- All chain types (Sequential, Parallel, Router, Transform, LLM)
- Chain composition patterns
- Error handling in chains
- Conditional execution
Key Features:
- ✅ 10+ composition examples
- ✅ Sequential pipelines
- ✅ Parallel execution
- ✅ Conditional routing
- ✅ Data transformation
- ✅ Nested compositions
- ✅ Chain callbacks
- ✅ Error recovery
Usage:
php examples/chain-composition-demo.phpExamples Covered:
- Simple LLM Chain
- Sequential Chain (multi-step pipeline)
- Parallel Chain (concurrent analysis)
- Router Chain (conditional routing)
- Transform Chain (data transformation)
- Complex nested composition
- Chain as Tool for agents
- Callbacks for monitoring
- Conditional sequential execution
- Error handling and recovery
-
API Key Setup: Create a
.envfile in the project root:ANTHROPIC_API_KEY=your_api_key_here
-
Dependencies:
composer install
# Basic examples
php examples/basic_agent.php
php examples/multi_tool_agent.php
# Advanced patterns
php examples/reflection_agent.php
php examples/hierarchical_agent.php
php examples/cot_example.php
php examples/tot_example.php
# Specialized
php examples/rag_example.php
php examples/autonomous_example.php
php examples/streaming_example.php
php examples/streaming_advanced.php
php examples/debate_example.php
# Async & Performance
php examples/amphp_async_example.php
# Alerts & Monitoring
php examples/alert_agent.php
php examples/advanced_alert_agent.php
# Production & Management
php examples/production_agent.php
php examples/context_management.php
php examples/chain-composition-demo.phpfor f in examples/*.php; do
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Running: $f"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
php "$f"
echo ""
donebasic_agent.php- Start heremulti_tool_agent.php- Multiple tools
cot_example.php- Chain of Thoughttot_example.php- Tree of Thoughtsreflection_agent.php- Self-reflection
hierarchical_agent.php- Master-workerdebate_example.php- Multi-agent collaborationautonomous_example.php- Goal-oriented
rag_example.php- Knowledge retrievalstreaming_example.php- Real-time outputstreaming_advanced.php- Advanced streaming with multiple handlerschain-composition-demo.php- Workflows
alert_agent.php- Intelligent alertingadvanced_alert_agent.php- Production alert system
amphp_async_example.php- Concurrent execution
production_agent.php- Best practicescontext_management.php- Context window management
- Tool definition with parameters
- Handler implementation
- Input validation
- Error handling
- Tool selection reasoning
- Model selection
- Token limits
- Iteration limits
- System prompts
- Timeout configuration
- Iteration callbacks
- Tool execution callbacks
- Error callbacks
- Token tracking
- Performance monitoring
- Retry logic
- Exponential backoff
- Graceful degradation
- Error recovery
- Logging
- In-memory state
- File persistence
- Session tracking
- Goal progress
- History management
- Sequential execution
- Parallel processing
- Conditional routing
- Data transformation
- Error propagation
All examples include:
- ✅ Valid PHP syntax
- ✅ Error handling
- ✅ Proper documentation
- ✅ Clear output formatting
- ✅ Token usage reporting
To validate all examples:
cd examples
for f in *.php; do
echo "Validating $f..."
php -l "$f"
done$myTool = Tool::create('my_tool')
->description('What the tool does')
->stringParam('input', 'Description')
->handler(function (array $input): string {
// Your logic here
return "result";
});
$agent->withTool($myTool);use ClaudeAgents\Agent;
use ClaudeAgents\Config\AgentConfig;
$config = AgentConfig::fromArray([
'model' => 'claude-sonnet-4-5',
'max_tokens' => 4096,
'max_iterations' => 10,
]);
$agent = Agent::create($client)
->withConfig($config)
->withSystemPrompt('Your custom prompt')
->onIteration(function($iter, $response, $context) {
// Monitor execution
});-
Missing API Key:
Error: ANTHROPIC_API_KEY not setSolution: Create
.envfile with your API key -
Timeout Errors: Increase timeout in config:
'timeout' => 60.0
-
Token Limits: Adjust max_tokens:
'max_tokens' => 8192
- Always validate tool inputs (see
production_agent.php) - Use appropriate error handling (see all examples)
- Track token usage (see
production_agent.php) - Log important events (see
production_agent.php) - Set reasonable iteration limits (see all examples)
- Use system prompts effectively (see all examples)
- Monitor tool execution (see
multi_tool_agent.php) - Persist state when needed (see
autonomous_example.php) - Use callbacks for observability (see
production_agent.php) - Compose chains for complex workflows (see
chain-composition-demo.php)
From the examples:
- Token Efficiency: Track and optimize token usage
- Iteration Limits: Set appropriate max_iterations
- Timeout Configuration: Balance responsiveness and completion
- Tool Selection: Design tools for specific purposes
- Caching: Use conversation memory appropriately
- Parallel Execution: Use ParallelChain for independent tasks
- Retry Logic: Configure retries for production reliability
- README.md - Project overview
- FEATURES.md - Complete feature list
- Test Coverage - Testing documentation
To add a new example:
- Create
my_example.phpin/examples - Include comprehensive comments
- Add error handling
- Test thoroughly
- Update this documentation
- Submit a pull request
All 16 examples are production-ready and demonstrate real-world usage patterns.