Skip to content

Commit 9c6844a

Browse files
committed
Add OpenAI example demonstrating streaming with sources
This example shows how to use the Agent with OpenAI platform to stream responses while collecting source metadata from tools like Tavily. This demonstrates the fix for issue #833 where sources metadata was unavailable during streaming. The example uses: - Agent with streaming enabled - Tavily tool for web search (provides sources) - Clock tool for current time - Source metadata display after streaming completes
1 parent 1e69969 commit 9c6844a

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
use Symfony\AI\Agent\Agent;
13+
use Symfony\AI\Agent\Toolbox\AgentProcessor;
14+
use Symfony\AI\Agent\Toolbox\Tool\Clock;
15+
use Symfony\AI\Agent\Toolbox\Tool\Tavily;
16+
use Symfony\AI\Agent\Toolbox\Toolbox;
17+
use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory;
18+
use Symfony\AI\Platform\Message\Message;
19+
use Symfony\AI\Platform\Message\MessageBag;
20+
use Symfony\Component\Clock\Clock as SymfonyClock;
21+
22+
require_once dirname(__DIR__).'/bootstrap.php';
23+
24+
$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client());
25+
26+
$clock = new Clock(new SymfonyClock());
27+
$tavily = new Tavily(http_client(), env('TAVILY_API_KEY'));
28+
$toolbox = new Toolbox([$clock, $tavily], logger: logger());
29+
$processor = new AgentProcessor($toolbox, includeSources: true);
30+
$agent = new Agent($platform, 'gpt-4o', [$processor], [$processor]);
31+
32+
$prompt = <<<PROMPT
33+
Summarize the latest game of the Dallas Cowboys. When and where was it? Who was the opponent, what was the result,
34+
and how was the game and the weather in the city. Use tools for the research and only answer based on information
35+
given in the context - don't make up information.
36+
PROMPT;
37+
38+
$result = $agent->call(new MessageBag(Message::ofUser($prompt)), ['stream' => true]);
39+
40+
foreach ($result->getContent() as $chunk) {
41+
echo $chunk->getContent();
42+
}
43+
44+
echo \PHP_EOL.\PHP_EOL;
45+
46+
echo 'Used sources:'.\PHP_EOL;
47+
foreach ($result->getMetadata()->get('sources', []) as $source) {
48+
echo sprintf(' - %s (%s)', $source->getName(), $source->getReference()).\PHP_EOL;
49+
}
50+
echo \PHP_EOL;

0 commit comments

Comments
 (0)