PHP code example of claude-php / agent

1. Go to this page and download the library: Download claude-php/agent library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

claude-php / agent example snippets




use ClaudeAgents\Agent;
use ClaudeAgents\Tools\Tool;
use ClaudePhp\ClaudePhp;

$client = new ClaudePhp(apiKey: getenv('ANTHROPIC_API_KEY'));

// Create a simple calculator tool
$calculator = Tool::create('calculate')
    ->description('Perform mathematical calculations')
    ->parameter('expression', 'string', 'Math expression to evaluate')
    ->7 + 100?');

echo $result->getAnswer();

use ClaudeAgents\Services\ServiceManager;
use ClaudeAgents\Services\ServiceType;

// Get the streaming executor
$executor = ServiceManager::getInstance()->get(ServiceType::FLOW_EXECUTOR);

// Stream execution with real-time events
foreach ($executor->executeWithStreaming($agent, "Calculate 15 * 23") as $event) {
    match ($event['type']) {
        'token' => print($event['data']['token']),              // Token-by-token streaming
        'progress' => printf("%.1f%%\n", $event['data']['progress_percent']), // Progress updates
        'tool_start' => print("šŸ”§ {$event['data']['tool']}\n"), // Tool execution
        'end' => print("āœ… Done!\n"),
        default => null
    };
}

use ClaudeAgents\Services\ServiceManager;
use ClaudeAgents\Services\ServiceType;

// Get the service
$errorService = ServiceManager::getInstance()->get(ServiceType::ERROR_HANDLING);

try {
    $result = $agent->run('Your task');
} catch (\Throwable $e) {
    // Convert to user-friendly message
    echo $errorService->convertToUserFriendly($e);
    // Output: "Rate limit exceeded. Please wait before retrying."
    
    // Get detailed error info for logging
    $details = $errorService->getErrorDetails($e);
    $logger->error('Agent failed', $details);
}

use ClaudeAgents\Templates\TemplateManager;

// Search templates
$templates = TemplateManager::search(
    query: 'chatbot',
    tags: ['conversation'],
    fields: ['name', 'description']
);

// Instantiate from template
$agent = TemplateManager::instantiate('rag-agent', [
    'api_key' => getenv('ANTHROPIC_API_KEY'),
    'model' => 'claude-sonnet-4-5'
]);

// Run the agent
$result = $agent->run('What is RAG?');

use ClaudeAgents\Progress\AgentUpdate;

$agent = Agent::create($client)
    ->onUpdate(function (AgentUpdate $update): void {
        // Send to WebSocket/SSE, update CLI spinner, etc.
    });

use ClaudeAgents\Loops\ReactLoop;

$agent = Agent::create()
    ->withLoopStrategy(new ReactLoop())
    ->withTools([$searchTool, $calculatorTool])
    ->maxIterations(10);

use ClaudeAgents\Loops\PlanExecuteLoop;

$loop = new PlanExecuteLoop(allowReplan: true);
$loop->onPlanCreated(function ($steps) {
    echo "Plan: " . count($steps) . " steps\n";
});

$agent = Agent::create()
    ->withLoopStrategy($loop)
    ->withTools($tools);

use ClaudeAgents\Loops\ReflectionLoop;

$loop = new ReflectionLoop(
    maxRefinements: 3,
    qualityThreshold: 8
);

$agent = Agent::create()
    ->withLoopStrategy($loop);

use ClaudeAgents\Tools\Tool;

// Fluent API for tool creation
$weatherTool = Tool::create('get_weather')
    ->description('Get current weather for a location')
    ->parameter('city', 'string', 'City name')
    ->parameter('units', 'string', 'Temperature units (celsius/fahrenheit)', false)
    ->

use ClaudeAgents\Agents\ReactAgent;

$agent = new ReactAgent($client, [
    'tools' => [$tool1, $tool2],
    'max_iterations' => 10,
    'system' => 'You are a helpful assistant.',
]);

$result = $agent->run('Complete this task...');

use ClaudeAgents\Agents\HierarchicalAgent;
use ClaudeAgents\Agents\WorkerAgent;

$master = new HierarchicalAgent($client);

$master->registerWorker('researcher', new WorkerAgent($client, [
    'specialty' => 'research and information gathering',
]));

$master->registerWorker('writer', new WorkerAgent($client, [
    'specialty' => 'writing and content creation',
]));

$result = $master->run('Research PHP 8 features and write a summary');

use ClaudeAgents\Agents\ReflectionAgent;

$agent = new ReflectionAgent($client, [
    'max_refinements' => 3,
    'quality_threshold' => 8,
]);

$result = $agent->run('Write a function to validate email addresses');
// Agent will generate, reflect, and refine until quality threshold is met

use ClaudeAgents\Memory\Memory;
use ClaudeAgents\Memory\FileMemory;

// In-memory state
$memory = new Memory();
$memory->set('user_preference', 'dark_mode');

// Persistent file-based memory
$memory = new FileMemory('/path/to/state.json');

$agent = Agent::create()
    ->withMemory($memory)
    ->run('Remember my preferences...');

use ClaudeAgents\Agent;
use ClaudeAgents\Tools\ToolResult;
use Psr\Log\LoggerInterface;

$agent = Agent::create($client)
    ->withLogger($psrLogger)
    ->withRetry(maxAttempts: 3, delayMs: 1000) // ms
    ->onError(function (Throwable $e, int $attempt) {
        // Handle errors
    })
    ->onToolExecution(function (string $tool, array $input, ToolResult $result) {
        // Monitor tool usage
    })
    ->onUpdate(function (\ClaudeAgents\Progress\AgentUpdate $update) {
        // Unified progress updates (iterations, tools, streaming deltas, start/end)
    });

use ClaudeAgents\Agents\MakerAgent;

// Based on: "Solving a Million-Step LLM Task with Zero Errors"
// https://arxiv.org/html/2511.09030v1

$maker = new MakerAgent($client, [
    'voting_k' => 3,                    // First-to-ahead-by-3 voting
    'enable_red_flagging' => true,      // Detect unreliable responses
    'max_decomposition_depth' => 10,    // Extreme decomposition
]);

// Can reliably handle tasks requiring millions of steps
$result = $maker->run('Solve this complex multi-step problem...');

// Track detailed execution statistics
$stats = $result->getMetadata()['execution_stats'];
echo "Steps: {$stats['total_steps']}\n";
echo "Votes: {$stats['votes_cast']}\n";
echo "Error Rate: " . $result->getMetadata()['error_rate'] . "\n";

use ClaudeAgents\Agents\AdaptiveAgentService;

// Create service that automatically selects the best agent
$service = new AdaptiveAgentService($client, [
    'max_attempts' => 3,              // Try up to 3 times
    'quality_threshold' => 7.0,       // Require 7/10 quality
    'enable_reframing' => true,       // Reframe on failure
]);

// Register various agents with their profiles
$service->registerAgent('react', $reactAgent, [
    'type' => 'react',
    'complexity_level' => 'medium',
    'quality' => 'standard',
]);

$service->registerAgent('reflection', $reflectionAgent, [
    'type' => 'reflection',
    'complexity_level' => 'medium',
    'quality' => 'high',
]);

// Service automatically:
// 1. Analyzes the task
// 2. Selects the best agent
// 3. Validates the result
// 4. Retries with different agents if needed
$result = $service->run('Your task here');

echo "Agent used: {$result->getMetadata()['final_agent']}\n";
echo "Quality: {$result->getMetadata()['final_quality']}/10\n";

use ClaudeAgents\Config\AgentConfig;

$config = new AgentConfig([
    'model' => 'claude-sonnet-4-5',
    'max_tokens' => 4096,
    'max_iterations' => 10,
    'temperature' => 0.7,
    'timeout' => 30.0,
    'retry' => [
        'max_attempts' => 3,
        'delay_ms' => 1000,
        'multiplier' => 2,
    ],
]);

$agent = Agent::create()->withConfig($config);

use ClaudeAgents\Services\ServiceManager;
use ClaudeAgents\Services\ServiceType;

// Get streaming executor from ServiceManager
$executor = ServiceManager::getInstance()->get(ServiceType::FLOW_EXECUTOR);

// Stream execution with events
foreach ($executor->executeWithStreaming($agent, "Your task") as $event) {
    match ($event['type']) {
        'token' => print($event['data']['token']),
        'progress' => updateProgressBar($event['data']['progress_percent']),
        'tool_start' => logToolExecution($event['data']['tool']),
        'error' => handleError($event['data']['error']),
        'end' => print("\nāœ… Complete!\n"),
        default => null
    };
}

// Set SSE headers
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

// Stream events to browser
foreach ($executor->streamSSE($agent, $task) as $sseData) {
    echo $sseData;
    flush();
}

$eventManager = ServiceManager::getInstance()->get(ServiceType::EVENT_MANAGER);

// Token counter listener
$eventManager->subscribe(function($event) {
    if ($event->isToken()) {
        incrementTokenCount();
    }
});

// Progress logger listener
$eventManager->subscribe(function($event) {
    if ($event->isProgress()) {
        logProgress($event->data['percent']);
    }
});

// Error monitor listener
$eventManager->subscribe(function($event) {
    if ($event->isError()) {
        alertError($event->data['error']);
    }
});

use ClaudeAgents\Async\BatchProcessor;

$processor = BatchProcessor::create($agent);

$processor->addMany([
    'task1' => 'Summarize this document...',
    'task2' => 'Analyze this data...',
    'task3' => 'Generate a report...',
]);

// Execute with concurrency of 5
$results = $processor->run(concurrency: 5);

// Get statistics
$stats = $processor->getStats();
echo "Success rate: " . ($stats['success_rate'] * 100) . "%\n";

use ClaudeAgents\Async\ParallelToolExecutor;

$executor = new ParallelToolExecutor($tools);

$calls = [
    ['tool' => 'get_weather', 'input' => ['city' => 'London']],
    ['tool' => 'get_time', 'input' => ['timezone' => 'UTC']],
    ['tool' => 'calculate', 'input' => ['expression' => '42 * 8']],
];

// All execute in parallel!
$results = $executor->execute($calls);

use ClaudeAgents\Async\Promise;

$promises = $processor->runAsync();

// Do other work...

// Wait for all to complete
$results = Promise::all($promises);

use ClaudeAgents\Parsers\ParserFactory;
use ClaudeAgents\Chains\LLMChain;

$factory = ParserFactory::create();

// JSON with schema validation
$jsonParser = $factory->json([
    'type' => 'object',
    '$jsonParser->parse($text));
bash
composer 
bash
# 1. Set your API key
export ANTHROPIC_API_KEY=your_api_key_here

# 2. Start the MCP server
php bin/mcp-server

# 3. Add to Claude Desktop config
{
  "mcpServers": {
    "claude-php-agent": {
      "command": "php",
      "args": ["/path/to/claude-php-agent/bin/mcp-server"]
    }
  }
}
bash
composer