-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcode_generation_example.php
More file actions
145 lines (122 loc) Β· 4.26 KB
/
Copy pathcode_generation_example.php
File metadata and controls
145 lines (122 loc) Β· 4.26 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
<?php
declare(strict_types=1);
require_once __DIR__ . '/load-env.php';
use ClaudeAgents\Agents\CodeGenerationAgent;
use ClaudeAgents\Validation\ValidationCoordinator;
use ClaudeAgents\Validation\Validators\PHPSyntaxValidator;
use ClaudeAgents\Validation\Validators\LLMReviewValidator;
use ClaudePhp\ClaudePhp;
/**
* Example: Basic code generation with validation.
*
* Demonstrates:
* - Creating a CodeGenerationAgent
* - Setting up validators
* - Generating PHP code from natural language
* - Automatic validation and retry on failure
*/
$apiKey = getenv('ANTHROPIC_API_KEY');
if (! $apiKey) {
echo "Error: ANTHROPIC_API_KEY environment variable not set\n";
exit(1);
}
$client = new ClaudePhp(apiKey: $apiKey);
// Setup validation coordinator with multiple validators
$validator = new ValidationCoordinator();
$validator->addValidator(new PHPSyntaxValidator());
$validator->addValidator(new LLMReviewValidator($client));
// Create code generation agent
$agent = new CodeGenerationAgent($client, [
'max_validation_retries' => 3,
'validation_coordinator' => $validator,
'max_tokens' => 4096,
]);
// Setup callbacks for progress monitoring
$agent->onUpdate(function (string $type, array $data) {
$timestamp = date('H:i:s');
match ($type) {
'code.generating' => printf("[%s] π Generating code...\n", $timestamp),
'code.generated' => printf(
"[%s] β
Generated %d lines (%d bytes)\n",
$timestamp,
$data['line_count'],
$data['code_length']
),
'validation.started' => printf("[%s] π Validating (attempt %d)...\n", $timestamp, $data['attempt'] + 1),
'validation.passed' => printf("[%s] β
Validation passed!\n", $timestamp),
'validation.failed' => printf(
"[%s] β Validation failed: %s\n",
$timestamp,
implode(', ', array_slice($data['errors'], 0, 2))
),
'retry.attempt' => printf(
"[%s] π Retry attempt %d/%d\n",
$timestamp,
$data['attempt'],
$data['max_attempts']
),
'component.completed' => printf(
"[%s] π Component generated successfully after %d attempt(s)\n",
$timestamp,
$data['attempts']
),
default => null,
};
});
echo "=== Code Generation Example ===\n\n";
// Example 1: Generate a simple class
echo "Example 1: Generating a UserRepository class\n";
echo str_repeat('-', 50) . "\n\n";
try {
$description = <<<DESC
Create a UserRepository class with the following:
- Namespace: App\Repository
- Methods: findById(int \$id), findAll(), save(User \$user), delete(int \$id)
- Use dependency injection for PDO
- Include proper type hints and docblocks
DESC;
$result = $agent->generateComponent($description);
if ($result->isValid()) {
echo "\nGenerated code:\n";
echo str_repeat('=', 50) . "\n";
echo $result->getCode();
echo str_repeat('=', 50) . "\n";
// Optionally save to file
$outputPath = '/tmp/UserRepository.php';
if ($result->saveToFile($outputPath)) {
echo "\nβ
Code saved to: {$outputPath}\n";
}
} else {
echo "\nβ Code generation failed validation:\n";
foreach ($result->getValidation()->getErrors() as $error) {
echo " - {$error}\n";
}
}
} catch (\Throwable $e) {
echo "\nβ Error: {$e->getMessage()}\n";
}
echo "\n\n";
// Example 2: Generate an interface
echo "Example 2: Generating a CacheInterface\n";
echo str_repeat('-', 50) . "\n\n";
try {
$description = <<<DESC
Create a CacheInterface with methods:
- get(string \$key): mixed
- set(string \$key, mixed \$value, int \$ttl = 3600): bool
- delete(string \$key): bool
- has(string \$key): bool
- clear(): bool
Include PSR-6 compatible docblocks
DESC;
$result = $agent->generateComponent($description);
echo "\n" . $result->getSummary() . "\n";
if ($result->isValid()) {
echo "\nβ
Code generation successful!\n";
echo "Lines: " . substr_count($result->getCode(), "\n") . "\n";
echo "Validation: " . $result->getValidation()->getSummary() . "\n";
}
} catch (\Throwable $e) {
echo "\nβ Error: {$e->getMessage()}\n";
}
echo "\n=== Example Complete ===\n";