Repository navigation
Expand file tree
/
Copy pathproduction_agent.php
More file actions
189 lines (162 loc) · 6.89 KB
/
Copy pathproduction_agent.php
File metadata and controls
189 lines (162 loc) · 6.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env php
<?php
/**
* Production Agent Example
*
* Demonstrates production-ready patterns including error handling,
* retry logic, logging, and monitoring.
*/
require_once __DIR__ . '/../vendor/autoload.php';
use ClaudeAgents\Agent;
use ClaudeAgents\Config\AgentConfig;
use ClaudeAgents\Config\RetryConfig;
use ClaudeAgents\Support\RetryHandler;
use ClaudeAgents\Support\TokenTracker;
use ClaudeAgents\Tools\Tool;
use ClaudePhp\ClaudePhp;
use Psr\Log\AbstractLogger;
// Simple console logger for demonstration
class ConsoleLogger extends AbstractLogger
{
public function log($level, string|\Stringable $message, array $context = []): void
{
$timestamp = date('H:i:s');
$contextStr = !empty($context) ? ' ' . json_encode($context) : '';
echo "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
}
}
// Load environment
$dotenv = __DIR__ . '/../.env';
if (file_exists($dotenv)) {
$lines = file($dotenv, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) continue;
if (strpos($line, '=') === false) continue;
[$name, $value] = explode('=', $line, 2);
$_ENV[trim($name)] = trim($value);
}
}
$apiKey = $_ENV['ANTHROPIC_API_KEY'] ?? throw new RuntimeException('ANTHROPIC_API_KEY not set');
$client = new ClaudePhp(apiKey: $apiKey);
echo "╔════════════════════════════════════════════════════════════════════════════╗\n";
echo "║ Production Agent Example ║\n";
echo "╚════════════════════════════════════════════════════════════════════════════╝\n\n";
// Create logger and token tracker
$logger = new ConsoleLogger();
$tokenTracker = new TokenTracker();
// Production configuration
$config = AgentConfig::fromArray([
'model' => 'claude-sonnet-4-5',
'max_tokens' => 4096,
'max_iterations' => 10,
'timeout' => 30.0,
'retry' => [
'max_attempts' => 3,
'delay_ms' => 1000,
'multiplier' => 2.0,
],
]);
// Create tools with proper error handling
$calculator = Tool::create('calculate')
->description('Perform mathematical calculations safely')
->stringParam('expression', 'Math expression (supports +, -, *, /, parentheses)')
->handler(function (array $input): string {
$expr = $input['expression'];
// Input validation
if (empty($expr)) {
return "Error: Empty expression";
}
if (!preg_match('/^[0-9+\-*\/().\s]+$/', $expr)) {
return "Error: Invalid characters in expression";
}
// Prevent division by zero
if (preg_match('/\/\s*0(?![0-9.])/', $expr)) {
return "Error: Division by zero";
}
try {
$result = eval("return {$expr};");
return (string) $result;
} catch (Throwable $e) {
return "Error: Calculation failed - " . $e->getMessage();
}
});
$weatherTool = Tool::create('get_weather')
->description('Get current weather for a location (simulated)')
->stringParam('city', 'City name')
->handler(function (array $input): string {
// Simulate occasional failures for retry demonstration
if (random_int(1, 10) === 1) {
throw new RuntimeException("Weather service temporarily unavailable");
}
$conditions = ['sunny', 'cloudy', 'rainy', 'partly cloudy'];
return json_encode([
'city' => $input['city'],
'temperature' => random_int(50, 85) . '°F',
'conditions' => $conditions[array_rand($conditions)],
]);
});
// Create the agent with production settings
$agent = Agent::create($client)
->withConfig($config)
->withTools([$calculator, $weatherTool])
->withLogger($logger)
->withSystemPrompt('You are a helpful assistant. Use tools when needed and handle errors gracefully.')
->onIteration(function (int $iteration, $response, $context) use ($tokenTracker) {
// Track tokens
if (isset($response->usage)) {
$tokenTracker->record(
$response->usage->input_tokens ?? 0,
$response->usage->output_tokens ?? 0
);
}
})
->onToolExecution(function (string $tool, array $input, $result) use ($logger) {
$status = $result->isError() ? '❌' : '✅';
$logger->info("{$status} Tool executed: {$tool}", [
'input' => $input,
'error' => $result->isError(),
]);
})
->onError(function (Throwable $e, int $attempt) use ($logger) {
$logger->error("Agent error on attempt {$attempt}", [
'message' => $e->getMessage(),
]);
});
// Run multiple tasks
$tasks = [
"What is 25 * 17 + 100?",
"What's the weather in Tokyo and New York?",
];
foreach ($tasks as $i => $task) {
echo "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "Task " . ($i + 1) . ": {$task}\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n";
$startTime = microtime(true);
$result = $agent->run($task);
$duration = round(microtime(true) - $startTime, 2);
if ($result->isSuccess()) {
echo "\n✅ Success:\n{$result->getAnswer()}\n";
} else {
echo "\n❌ Failed: {$result->getError()}\n";
}
echo "\n📊 Task Stats:\n";
echo " • Duration: {$duration}s\n";
echo " • Iterations: {$result->getIterations()}\n";
$usage = $result->getTokenUsage();
echo " • Tokens: {$usage['total']} ({$usage['input']} in, {$usage['output']} out)\n";
}
// Final summary
echo "\n" . str_repeat("═", 80) . "\n";
echo "Session Summary\n";
echo str_repeat("═", 80) . "\n\n";
$summary = $tokenTracker->getSummary();
echo "📈 Token Usage:\n";
echo " • Total requests: {$summary['request_count']}\n";
echo " • Total tokens: {$summary['total_tokens']}\n";
echo " • Input tokens: {$summary['input_tokens']}\n";
echo " • Output tokens: {$summary['output_tokens']}\n";
echo " • Average per request: {$summary['average_per_request']}\n";
$estimatedCost = $tokenTracker->estimateCost();
echo "\n💰 Estimated Cost: $" . number_format($estimatedCost, 4) . "\n";
echo "\n" . str_repeat("═", 80) . "\n";
echo "Production agent example completed!\n";