-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker_agent.php
More file actions
executable file
·278 lines (215 loc) · 10.1 KB
/
worker_agent.php
File metadata and controls
executable file
·278 lines (215 loc) · 10.1 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env php
<?php
/**
* Worker Agent Example
*
* Demonstrates the WorkerAgent class as a specialized agent
* that can be used standalone or as part of hierarchical systems.
*/
require_once __DIR__ . '/../vendor/autoload.php';
use ClaudeAgents\Agents\WorkerAgent;
use ClaudePhp\ClaudePhp;
// 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 "║ Worker Agent Example ║\n";
echo "╚════════════════════════════════════════════════════════════════════════════╝\n\n";
// ============================================================================
// Example 1: Simple Worker - Math Specialist
// ============================================================================
echo "Example 1: Math Specialist Worker\n";
echo str_repeat("─", 80) . "\n";
$mathWorker = new WorkerAgent($client, [
'name' => 'math_expert',
'specialty' => 'mathematical calculations, statistics, and numerical analysis',
'system' => 'You are a mathematics expert. Provide precise calculations and clear explanations of mathematical concepts. Always show your work.',
]);
echo "Worker Name: {$mathWorker->getName()}\n";
echo "Specialty: {$mathWorker->getSpecialty()}\n\n";
$mathTask = "Calculate the average, median, and standard deviation of this dataset: 15, 23, 27, 19, 32, 28, 22, 25, 30, 21";
echo "Task: {$mathTask}\n\n";
echo "Processing...\n\n";
$result = $mathWorker->run($mathTask);
if ($result->isSuccess()) {
echo "✅ Result:\n";
echo str_repeat("─", 80) . "\n";
echo $result->getAnswer() . "\n";
echo str_repeat("─", 80) . "\n\n";
$usage = $result->getTokenUsage();
echo "📊 Stats: {$result->getIterations()} iterations, {$usage['total']} tokens\n";
} else {
echo "❌ Error: {$result->getError()}\n";
}
echo "\n" . str_repeat("═", 80) . "\n\n";
// ============================================================================
// Example 2: Writing Specialist
// ============================================================================
echo "Example 2: Writing Specialist Worker\n";
echo str_repeat("─", 80) . "\n";
$writingWorker = new WorkerAgent($client, [
'name' => 'content_writer',
'specialty' => 'creative writing, content creation, and storytelling',
'system' => 'You are a professional writer. Create engaging, clear, and well-structured content that resonates with readers.',
]);
echo "Worker Name: {$writingWorker->getName()}\n";
echo "Specialty: {$writingWorker->getSpecialty()}\n\n";
$writingTask = "Write a compelling 3-paragraph introduction for a blog post about the benefits of morning exercise routines.";
echo "Task: {$writingTask}\n\n";
echo "Processing...\n\n";
$result = $writingWorker->run($writingTask);
if ($result->isSuccess()) {
echo "✅ Result:\n";
echo str_repeat("─", 80) . "\n";
echo $result->getAnswer() . "\n";
echo str_repeat("─", 80) . "\n\n";
$metadata = $result->getMetadata();
echo "📊 Worker: {$metadata['worker']}\n";
echo "📊 Specialty: {$metadata['specialty']}\n";
$usage = $result->getTokenUsage();
echo "📊 Tokens: {$usage['total']} total ({$usage['input']} in, {$usage['output']} out)\n";
} else {
echo "❌ Error: {$result->getError()}\n";
}
echo "\n" . str_repeat("═", 80) . "\n\n";
// ============================================================================
// Example 3: Code Analysis Specialist
// ============================================================================
echo "Example 3: Code Analysis Specialist Worker\n";
echo str_repeat("─", 80) . "\n";
$codeWorker = new WorkerAgent($client, [
'name' => 'code_reviewer',
'specialty' => 'code review, security analysis, and best practices',
'system' => 'You are a senior software engineer. Review code for bugs, security issues, performance problems, and adherence to best practices. Provide specific, actionable feedback.',
'max_tokens' => 3000,
]);
echo "Worker Name: {$codeWorker->getName()}\n";
echo "Specialty: {$codeWorker->getSpecialty()}\n\n";
$codeToReview = <<<'PHP'
function processUserInput($input) {
$query = "SELECT * FROM users WHERE username = '" . $input . "'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo $row['username'] . ": " . $row['email'] . "<br>";
}
}
PHP;
$codeTask = "Review this PHP function and identify security issues, deprecated functions, and suggest improvements:\n\n{$codeToReview}";
echo "Task: Reviewing PHP code for security issues...\n\n";
echo "Processing...\n\n";
$result = $codeWorker->run($codeTask);
if ($result->isSuccess()) {
echo "✅ Review Results:\n";
echo str_repeat("─", 80) . "\n";
echo $result->getAnswer() . "\n";
echo str_repeat("─", 80) . "\n\n";
$usage = $result->getTokenUsage();
echo "📊 Analysis completed with {$usage['total']} tokens\n";
} else {
echo "❌ Error: {$result->getError()}\n";
}
echo "\n" . str_repeat("═", 80) . "\n\n";
// ============================================================================
// Example 4: Research Specialist
// ============================================================================
echo "Example 4: Research Specialist Worker\n";
echo str_repeat("─", 80) . "\n";
$researchWorker = new WorkerAgent($client, [
'name' => 'researcher',
'specialty' => 'research, fact-finding, and information synthesis',
'system' => 'You are a research specialist. Gather relevant information, synthesize data, and provide well-structured insights. Always explain your reasoning.',
'model' => 'claude-sonnet-4-5',
'max_tokens' => 2048,
]);
echo "Worker Name: {$researchWorker->getName()}\n";
echo "Specialty: {$researchWorker->getSpecialty()}\n\n";
$researchTask = "Explain the key differences between REST and GraphQL APIs, including when to use each approach.";
echo "Task: {$researchTask}\n\n";
echo "Processing...\n\n";
$result = $researchWorker->run($researchTask);
if ($result->isSuccess()) {
echo "✅ Research Findings:\n";
echo str_repeat("─", 80) . "\n";
echo $result->getAnswer() . "\n";
echo str_repeat("─", 80) . "\n\n";
$metadata = $result->getMetadata();
echo "📊 Research by: {$metadata['worker']}\n";
$usage = $result->getTokenUsage();
echo "📊 Tokens used: {$usage['total']}\n";
} else {
echo "❌ Error: {$result->getError()}\n";
}
echo "\n" . str_repeat("═", 80) . "\n\n";
// ============================================================================
// Example 5: Multiple Workers Comparison
// ============================================================================
echo "Example 5: Comparing Different Worker Specialties\n";
echo str_repeat("─", 80) . "\n";
$topic = "the importance of software testing";
$workers = [
new WorkerAgent($client, [
'name' => 'technical_writer',
'specialty' => 'technical documentation and explanation',
'system' => 'You are a technical writer. Explain concepts clearly with proper technical terminology.',
]),
new WorkerAgent($client, [
'name' => 'sales_writer',
'specialty' => 'persuasive writing and marketing',
'system' => 'You are a marketing copywriter. Write persuasive, benefit-focused content.',
]),
new WorkerAgent($client, [
'name' => 'educator',
'specialty' => 'educational content and teaching',
'system' => 'You are an educator. Teach concepts using clear examples and analogies.',
]),
];
$task = "Write a brief paragraph about {$topic}";
echo "Same task given to different specialists:\n";
echo "Task: \"{$task}\"\n\n";
foreach ($workers as $worker) {
echo "Worker: {$worker->getName()} ({$worker->getSpecialty()})\n";
echo str_repeat("─", 80) . "\n";
$result = $worker->run($task);
if ($result->isSuccess()) {
echo $result->getAnswer() . "\n";
$usage = $result->getTokenUsage();
echo "\n💡 Tokens: {$usage['total']}\n";
} else {
echo "❌ Error: {$result->getError()}\n";
}
echo "\n";
}
echo str_repeat("═", 80) . "\n\n";
// ============================================================================
// Summary
// ============================================================================
echo "Summary:\n";
echo str_repeat("─", 80) . "\n";
echo "✅ Demonstrated 5 worker agent examples:\n";
echo " 1. Math Specialist - Precise calculations and analysis\n";
echo " 2. Writing Specialist - Creative content creation\n";
echo " 3. Code Review Specialist - Security and best practices\n";
echo " 4. Research Specialist - Information synthesis\n";
echo " 5. Multiple Specialists - Same task, different approaches\n\n";
echo "Key Features:\n";
echo " • Each worker has a specific specialty and system prompt\n";
echo " • Workers can use different models and token limits\n";
echo " • Same task produces different results based on specialty\n";
echo " • Workers can be used standalone or in hierarchical systems\n\n";
echo "Next Steps:\n";
echo " • Try creating your own specialized workers\n";
echo " • Combine workers in a HierarchicalAgent for complex tasks\n";
echo " • Adjust system prompts to fine-tune behavior\n";
echo " • Monitor token usage for cost optimization\n";
echo "\n" . str_repeat("═", 80) . "\n";
echo "Worker agent examples completed!\n";