-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstreaming_example.php
More file actions
74 lines (58 loc) · 2.04 KB
/
Copy pathstreaming_example.php
File metadata and controls
74 lines (58 loc) · 2.04 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
#!/usr/bin/env php
<?php
/**
* Streaming Example
*
* Demonstrates real-time token streaming from Claude API.
* Shows how to use StreamingLoop and handlers for progressive output.
*/
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use ClaudeAgents\Agent;
use ClaudeAgents\Config\AgentConfig;
use ClaudeAgents\Progress\AgentUpdate;
use ClaudeAgents\Streaming\StreamingLoop;
use ClaudeAgents\Streaming\Handlers\ConsoleHandler;
use ClaudeAgents\Tools\Tool;
use ClaudePhp\ClaudePhp;
// Initialize Claude client
$client = new ClaudePhp(apiKey: getenv('ANTHROPIC_API_KEY'));
echo "=== Streaming Agent Example ===\n\n";
// Create a simple calculator tool
$calculator = Tool::create('calculator')
->description('Performs basic arithmetic operations')
->stringParam('expression', 'Math expression to evaluate')
->handler(function($input) {
$expr = $input['expression'] ?? '0';
// Safe evaluation (normally use a proper math library)
return @eval('return ' . $expr . ';');
});
// Create agent with streaming
$config = new AgentConfig([
'model' => 'claude-sonnet-4-5',
'max_iterations' => 5,
'max_tokens' => 1024,
]);
$agent = Agent::create($client)
->withConfig($config)
->withTool($calculator)
->maxIterations(3);
// Optional: unified progress updates (includes streaming deltas)
$agent->onUpdate(function (AgentUpdate $update): void {
if ($update->getType() === 'llm.stream') {
// Each event contains the streamed chunk metadata.
// $event = $update->getData()['event'] ?? [];
}
});
// Add streaming loop
$streamingLoop = new StreamingLoop();
$streamingLoop->addHandler(new ConsoleHandler(newline: true));
$agent->withLoopStrategy($streamingLoop);
echo "Running agent with streaming...\n";
echo "Task: Calculate the sum of 25 + 17 + 8\n\n";
echo "Output:\n";
echo "---\n";
$result = $agent->run('Calculate the sum of 25 + 17 + 8');
echo "---\n\n";
echo "Final Answer: " . $result->getAnswer() . "\n";
echo "Success: " . ($result->isSuccess() ? 'Yes' : 'No') . "\n";