Repository navigation
Expand file tree
/
Copy pathdesign_patterns_demo.php
More file actions
475 lines (389 loc) Β· 20.5 KB
/
Copy pathdesign_patterns_demo.php
File metadata and controls
475 lines (389 loc) Β· 20.5 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#!/usr/bin/env php
<?php
/**
* Design Patterns Demo
*
* Comprehensive demonstration of all 6 design patterns in the Claude PHP Agent Framework:
* 1. Factory Pattern (AgentFactory) - Consistent agent creation
* 2. Builder Pattern (AgentConfigBuilder) - Fluent configuration
* 3. Observer Pattern (EventDispatcher) - Lifecycle monitoring
* 4. Strategy Pattern (ResponseParserChain) - Response parsing
* 5. Template Pattern (PromptBuilder) - Prompt construction
* 6. Error Handler Pattern - Resilient execution
*
* Run: php examples/design_patterns_demo.php
*/
require_once __DIR__ . '/../vendor/autoload.php';
use ClaudeAgents\Factory\AgentFactory;
use ClaudeAgents\Config\AgentConfigBuilder;
use ClaudeAgents\Events\EventDispatcher;
use ClaudeAgents\Events\{AgentStartedEvent, AgentCompletedEvent, AgentFailedEvent};
use ClaudeAgents\Parsers\ResponseParserChain;
use ClaudeAgents\Parsers\{JsonResponseParser, MarkdownParser};
use ClaudeAgents\Prompts\PromptBuilder;
use ClaudeAgents\Exceptions\ErrorHandler;
use ClaudeAgents\Tools\Tool;
use ClaudePhp\ClaudePhp;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// Load environment variables
$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 "β Design Patterns in Claude PHP Agent Framework β\n";
echo "β Comprehensive Pattern Demonstration β\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// ============================================================================
// Example 1: Factory Pattern
// ============================================================================
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 1: Factory Pattern - Consistent Agent Creation\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Setup logger
$logger = new Logger('patterns_demo');
$logger->pushHandler(new StreamHandler('php://stdout', Logger::INFO));
// Create factory - centralizes agent creation with consistent configuration
$factory = new AgentFactory($client, $logger);
echo "β
Created AgentFactory with client and logger\n\n";
// Create agents using factory - all get consistent configuration
echo "Creating agents with factory:\n";
$agent1 = $factory->create('react', ['name' => 'agent1']);
echo " β Created ReactAgent 'agent1' using generic create()\n";
$agent2 = $factory->createReactAgent(['name' => 'agent2', 'max_iterations' => 5]);
echo " β Created ReactAgent 'agent2' using specific method\n";
// Benefits demonstrated:
echo "\nπ Factory Pattern Benefits:\n";
echo " β’ Consistency: All agents created with same defaults\n";
echo " β’ DRY: No duplication of construction logic\n";
echo " β’ Logger injection: Automatically provided to all agents\n";
echo " β’ Testability: Easy to mock factory in tests\n\n";
// ============================================================================
// Example 2: Builder Pattern
// ============================================================================
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 2: Builder Pattern - Fluent Configuration\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Build complex configuration using fluent API
$config = AgentConfigBuilder::create()
->withModel('claude-sonnet-4-20250514')
->withMaxTokens(2048)
->withMaxIterations(5)
->withSystemPrompt('You are a helpful assistant demonstrating design patterns')
->withTemperature(0.7)
->build();
echo "β
Built agent configuration using Builder pattern\n\n";
echo "Configuration details:\n";
echo " β’ Model: claude-sonnet-4-20250514\n";
echo " β’ Max Tokens: 2048\n";
echo " β’ Max Iterations: 5\n";
echo " β’ Temperature: 0.7\n\n";
echo "π Builder Pattern Benefits:\n";
echo " β’ Type Safety: Typos caught at compile time\n";
echo " β’ Readability: Self-documenting code\n";
echo " β’ IDE Support: Full autocomplete\n";
echo " β’ Flexibility: Easy to add optional parameters\n\n";
// ============================================================================
// Example 3: Observer Pattern (Event System)
// ============================================================================
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 3: Observer Pattern - Event-Driven Monitoring\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Create event dispatcher
$dispatcher = new EventDispatcher();
// Metrics collector
$metrics = [
'total' => 0,
'successful' => 0,
'failed' => 0,
'total_duration' => 0.0,
];
// Subscribe to events
$dispatcher->listen(AgentStartedEvent::class, function($event) {
echo "π Agent '{$event->getAgentName()}' started\n";
echo " Task: {$event->getTask()}\n";
});
$dispatcher->listen(AgentCompletedEvent::class, function($event) use (&$metrics) {
$metrics['total']++;
$metrics['successful']++;
$metrics['total_duration'] += $event->getDuration();
echo "β
Agent '{$event->getAgentName()}' completed\n";
echo " Duration: " . round($event->getDuration(), 2) . "s\n";
echo " Iterations: {$event->getIterations()}\n";
});
$dispatcher->listen(AgentFailedEvent::class, function($event) use (&$metrics) {
$metrics['total']++;
$metrics['failed']++;
echo "β Agent '{$event->getAgentName()}' failed\n";
echo " Error: {$event->getError()}\n";
});
echo "β
Event dispatcher configured with 3 listeners\n\n";
// Simulate events
echo "Simulating agent lifecycle events:\n\n";
$dispatcher->dispatch(new AgentStartedEvent('demo_agent', 'Demonstrate patterns'));
sleep(1);
$dispatcher->dispatch(new AgentCompletedEvent('demo_agent', duration: 1.0, iterations: 3, result: 'Success'));
echo "\nπ Observer Pattern Benefits:\n";
echo " β’ Decoupling: Agents don't know about observers\n";
echo " β’ Extensibility: Add listeners without modifying agents\n";
echo " β’ Multiple Listeners: Many observers per event\n";
echo " β’ Runtime Configuration: Add/remove dynamically\n\n";
echo "π Collected Metrics:\n";
echo " β’ Total runs: {$metrics['total']}\n";
echo " β’ Successful: {$metrics['successful']}\n";
echo " β’ Failed: {$metrics['failed']}\n";
echo " β’ Avg duration: " . round($metrics['total_duration'] / max($metrics['successful'], 1), 2) . "s\n\n";
// ============================================================================
// Example 4: Strategy Pattern (Response Parser Chain)
// ============================================================================
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 4: Strategy Pattern - Flexible Response Parsing\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Create parser chain - tries each parser until one succeeds
$parserChain = new ResponseParserChain([
new JsonResponseParser(),
new MarkdownParser(),
]);
echo "β
Created ResponseParserChain with JSON and Markdown parsers\n\n";
// Test with JSON response
$jsonResponse = '```json
{
"status": "success",
"data": {
"patterns": ["Factory", "Builder", "Observer"]
}
}
```';
echo "Parsing JSON response:\n";
$parsed1 = $parserChain->parse($jsonResponse);
echo " β Parsed successfully using JsonResponseParser\n";
echo " Result: " . json_encode($parsed1, JSON_PRETTY_PRINT) . "\n\n";
// Test with Markdown response
$markdownResponse = '# Results
The framework uses these patterns:
- **Factory**: Consistent creation
- **Builder**: Fluent configuration
- **Observer**: Event monitoring';
echo "Parsing Markdown response:\n";
$parsed2 = $parserChain->parse($markdownResponse);
echo " β Parsed successfully using MarkdownParser\n";
echo " Headings found: " . count($parsed2['headings']) . "\n";
echo " Lists found: " . count($parsed2['lists']) . "\n\n";
echo "π Strategy Pattern Benefits:\n";
echo " β’ Flexibility: Multiple parsing strategies\n";
echo " β’ Automatic: Chain tries parsers until success\n";
echo " β’ Extensible: Add parsers without modifying existing code\n";
echo " β’ Clean: Each parser has single responsibility\n\n";
// ============================================================================
// Example 5: Template Pattern (Prompt Builder)
// ============================================================================
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 5: Template Pattern - Structured Prompt Construction\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Build structured prompt using template pattern
$prompt = PromptBuilder::create()
->addContext(
'You are a software architecture expert explaining design patterns. ' .
'Your goal is to help developers understand when and how to use each pattern.'
)
->addTask('Explain the Factory Pattern in one sentence')
->addExample(
'Input: Explain Builder Pattern',
'Output: The Builder Pattern provides a fluent API for constructing complex objects with many optional parameters.'
)
->addConstraint('Be concise and clear')
->addConstraint('Focus on the core benefit')
->addInstructions('Format your response as a single sentence')
->build();
echo "β
Built structured prompt using PromptBuilder\n\n";
echo "Prompt structure:\n";
echo " β’ Context: Set the role and goal\n";
echo " β’ Task: Define what to do\n";
echo " β’ Example: Show expected format\n";
echo " β’ Constraints: Set requirements\n";
echo " β’ Instructions: Specify output format\n\n";
echo "Generated prompt preview:\n";
echo str_repeat("-", 76) . "\n";
echo substr($prompt, 0, 200) . "...\n";
echo str_repeat("-", 76) . "\n\n";
echo "π Template Pattern Benefits:\n";
echo " β’ Readability: Clear prompt structure\n";
echo " β’ Reusability: Build prompts programmatically\n";
echo " β’ Consistency: Standard prompt format\n";
echo " β’ Maintainability: Easy to modify structure\n\n";
// ============================================================================
// Example 6: Error Handler Pattern
// ============================================================================
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 6: Error Handler Pattern - Resilient Execution\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Create error handler with retry logic
$errorHandler = new ErrorHandler($logger, maxRetries: 3, initialDelayMs: 100);
echo "β
Created ErrorHandler with retry logic\n";
echo " Max retries: 3\n";
echo " Initial delay: 100ms\n";
echo " Backoff: Exponential\n\n";
// Simulate operation that might fail
$attemptCount = 0;
echo "Simulating flaky operation:\n";
try {
$result = $errorHandler->executeWithRetry(
fn: function() use (&$attemptCount) {
$attemptCount++;
echo " Attempt {$attemptCount}...\n";
// Succeed on 3rd attempt
if ($attemptCount < 3) {
throw new RuntimeException("Simulated transient error");
}
return "Operation succeeded!";
},
context: 'Demo operation'
);
echo "\nβ
Operation completed: {$result}\n\n";
} catch (Exception $e) {
echo "\nβ All retries exhausted: {$e->getMessage()}\n\n";
}
echo "π Error Handler Pattern Benefits:\n";
echo " β’ Resilience: Automatic retry on transient failures\n";
echo " β’ Consistency: Same error handling everywhere\n";
echo " β’ Observability: Callbacks for monitoring\n";
echo " β’ Smart: Exponential backoff prevents overwhelming\n\n";
// ============================================================================
// Example 7: All Patterns Together
// ============================================================================
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 7: Combined Patterns - Production-Ready Setup\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
echo "Combining all patterns for production-ready agent:\n\n";
// 1. Factory for agent creation
echo "1. Using Factory for consistent agent creation\n";
$productionFactory = new AgentFactory($client, $logger);
// 2. Builder for configuration
echo "2. Using Builder for type-safe configuration\n";
$productionConfig = AgentConfigBuilder::create()
->withModel('claude-sonnet-4-20250514')
->withMaxTokens(1024)
->withMaxIterations(3)
->withTemperature(0.7)
->toArray();
// 3. Events for monitoring
echo "3. Using Events for decoupled monitoring\n";
$productionDispatcher = new EventDispatcher();
$productionDispatcher->listen(AgentCompletedEvent::class, function($event) {
echo " β Agent completed in " . round($event->getDuration(), 2) . "s\n";
});
// 4. Parser chain for robust parsing
echo "4. Using ParserChain for flexible parsing\n";
$productionParser = new ResponseParserChain([
new JsonResponseParser(),
new MarkdownParser(),
]);
// 5. Prompt builder for structured prompts
echo "5. Using PromptBuilder for clear prompts\n";
$productionPrompt = PromptBuilder::create()
->addContext('You are a helpful assistant')
->addTask('Say hello and list 2 design patterns')
->addConstraint('Be brief')
->build();
// 6. Error handler for resilience
echo "6. Using ErrorHandler for resilient execution\n";
$productionErrorHandler = new ErrorHandler($logger, maxRetries: 2);
echo "\nβ
All patterns configured!\n\n";
echo "This production setup provides:\n";
echo " β’ Consistent agent creation (Factory)\n";
echo " β’ Type-safe configuration (Builder)\n";
echo " β’ Decoupled monitoring (Observer)\n";
echo " β’ Flexible parsing (Strategy)\n";
echo " β’ Structured prompts (Template)\n";
echo " β’ Resilient execution (ErrorHandler)\n\n";
// Create and run agent with all patterns
$calculator = Tool::create('calculate')
->description('Perform mathematical calculations')
->stringParam('expression', 'Math expression to evaluate')
->handler(function (array $input): string {
$expr = $input['expression'];
if (!preg_match('/^[0-9+\-*\/().\s]+$/', $expr)) {
return "Error: Invalid expression";
}
try {
$result = eval("return {$expr};");
return (string) $result;
} catch (Throwable $e) {
return "Error: " . $e->getMessage();
}
});
$fullStackConfig = AgentConfigBuilder::create()
->withModel('claude-sonnet-4-20250514')
->withMaxTokens(512)
->withMaxIterations(3)
->addTool($calculator)
->toArray();
$fullStackAgent = $productionFactory->create('react', $fullStackConfig);
echo "Running agent with full pattern stack:\n\n";
$productionDispatcher->dispatch(new AgentStartedEvent('full_stack_agent', 'Calculate 15 * 23'));
$startTime = microtime(true);
$agentResult = $fullStackAgent->run('What is 15 multiplied by 23? Use the calculate tool.');
$duration = microtime(true) - $startTime;
if ($agentResult->isSuccess()) {
echo "β
Agent execution successful!\n";
echo " Answer: " . substr($agentResult->getAnswer(), 0, 100) . "...\n";
echo " Iterations: {$agentResult->getIterations()}\n";
$productionDispatcher->dispatch(new AgentCompletedEvent(
'full_stack_agent',
duration: $duration,
iterations: $agentResult->getIterations(),
result: $agentResult->getAnswer()
));
} else {
echo "β Agent execution failed\n";
echo " Error: {$agentResult->getError()}\n";
}
// ============================================================================
// Summary
// ============================================================================
echo "\n" . str_repeat("β", 80) . "\n";
echo "π Design Patterns Summary\n";
echo str_repeat("β", 80) . "\n\n";
echo "The Claude PHP Agent Framework uses 6 production-ready design patterns:\n\n";
echo "1. π Factory Pattern (AgentFactory)\n";
echo " β Consistent agent creation with dependency injection\n";
echo " β Use: Always in production code\n\n";
echo "2. βοΈ Builder Pattern (AgentConfigBuilder)\n";
echo " β Type-safe, fluent configuration API\n";
echo " β Use: Complex configurations (>3 parameters)\n\n";
echo "3. π‘ Observer Pattern (EventDispatcher)\n";
echo " β Decoupled lifecycle event monitoring\n";
echo " β Use: Monitoring, logging, analytics\n\n";
echo "4. π Strategy Pattern (ResponseParserChain)\n";
echo " β Pluggable response parsing with fallthrough\n";
echo " β Use: Multiple response formats\n\n";
echo "5. π Template Pattern (PromptBuilder)\n";
echo " β Structured prompt construction\n";
echo " β Use: Complex, multi-section prompts\n\n";
echo "6. π‘οΈ Error Handler Pattern\n";
echo " β Unified error handling with retry\n";
echo " β Use: All external API calls\n\n";
echo str_repeat("β", 80) . "\n\n";
echo "π‘ Key Takeaways:\n\n";
echo " β’ Use Factory for all agent creation in production\n";
echo " β’ Use Builder when configuration has >3 parameters\n";
echo " β’ Use Events for monitoring and observability\n";
echo " β’ Use ParserChain for robust response handling\n";
echo " β’ Use PromptBuilder for complex prompts\n";
echo " β’ Use ErrorHandler for all external calls\n\n";
echo "π Learn More:\n";
echo " β’ Design Patterns Guide: docs/DesignPatterns.md\n";
echo " β’ Best Practices: docs/BestPractices.md\n";
echo " β’ Individual Examples: examples/factory_pattern_example.php, etc.\n\n";
echo str_repeat("β", 80) . "\n";
echo "β¨ Design Patterns Demo Complete!\n";
echo str_repeat("β", 80) . "\n";