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\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\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
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.