From 948c5041c64079299c3a8a6be2f19d51d69d99c7 Mon Sep 17 00:00:00 2001 From: Oskar Stark Date: Fri, 14 Nov 2025 09:01:23 +0100 Subject: [PATCH] Add OpenAI example demonstrating streaming with sources --- examples/openai/agent-stream-sources.php | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 examples/openai/agent-stream-sources.php diff --git a/examples/openai/agent-stream-sources.php b/examples/openai/agent-stream-sources.php new file mode 100644 index 000000000..187243a7c --- /dev/null +++ b/examples/openai/agent-stream-sources.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\AI\Agent\Agent; +use Symfony\AI\Agent\Toolbox\AgentProcessor; +use Symfony\AI\Agent\Toolbox\Tool\Clock; +use Symfony\AI\Agent\Toolbox\Tool\Tavily; +use Symfony\AI\Agent\Toolbox\Toolbox; +use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory; +use Symfony\AI\Platform\Message\Message; +use Symfony\AI\Platform\Message\MessageBag; +use Symfony\Component\Clock\Clock as SymfonyClock; + +require_once dirname(__DIR__).'/bootstrap.php'; + +$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client()); + +$clock = new Clock(new SymfonyClock()); +$tavily = new Tavily(http_client(), env('TAVILY_API_KEY')); +$toolbox = new Toolbox([$clock, $tavily], logger: logger()); +$processor = new AgentProcessor($toolbox, includeSources: true); +$agent = new Agent($platform, 'gpt-4o', [$processor], [$processor]); + +$prompt = <<call(new MessageBag(Message::ofUser($prompt)), ['stream' => true]); + +foreach ($result->getContent() as $word) { + echo $word; +} +echo \PHP_EOL; + +echo 'Used sources:'.\PHP_EOL; +foreach ($result->getMetadata()->get('sources', []) as $source) { + echo sprintf(' - %s (%s)', $source->getName(), $source->getReference()).\PHP_EOL; +} +echo \PHP_EOL;