Skip to content

Commit bee0151

Browse files
committed
[OpenAI] Add Agent-as-Tool example
1 parent 64eef5e commit bee0151

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

examples/openai/agent-as-tool.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
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\InputProcessor\SystemPromptInputProcessor;
14+
use Symfony\AI\Agent\Toolbox\AgentProcessor;
15+
use Symfony\AI\Agent\Toolbox\Tool\Agent as AgentTool;
16+
use Symfony\AI\Agent\Toolbox\ToolFactory\ChainFactory;
17+
use Symfony\AI\Agent\Toolbox\ToolFactory\MemoryToolFactory;
18+
use Symfony\AI\Agent\Toolbox\ToolFactory\ReflectionToolFactory;
19+
use Symfony\AI\Agent\Toolbox\Toolbox;
20+
use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory;
21+
use Symfony\AI\Platform\Message\Message;
22+
use Symfony\AI\Platform\Message\MessageBag;
23+
24+
require_once dirname(__DIR__).'/bootstrap.php';
25+
26+
$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client());
27+
28+
// Create a specialized agent for mathematical calculations
29+
$mathSystemPrompt = new SystemPromptInputProcessor('You are a mathematical calculator. When given a math problem, solve it and return only the numerical result with a brief explanation.');
30+
$mathAgent = new Agent($platform, 'gpt-4o', [$mathSystemPrompt], logger: logger());
31+
32+
// Wrap the math agent as a tool
33+
$mathTool = new AgentTool($mathAgent);
34+
35+
// Use MemoryToolFactory to register the tool with metadata
36+
$memoryFactory = new MemoryToolFactory();
37+
$memoryFactory->addTool(
38+
$mathTool,
39+
'calculate',
40+
'Performs mathematical calculations. Use this when you need to solve math problems or do arithmetic.',
41+
);
42+
43+
// Combine with ReflectionToolFactory using ChainFactory
44+
$chainFactory = new ChainFactory([
45+
$memoryFactory,
46+
new ReflectionToolFactory(),
47+
]);
48+
49+
// Create the main agent with the math agent as a tool
50+
$toolbox = new Toolbox([$mathTool], toolFactory: $chainFactory, logger: logger());
51+
$processor = new AgentProcessor($toolbox);
52+
$agent = new Agent($platform, 'gpt-4o-mini', [$processor], [$processor], logger: logger());
53+
54+
// Ask a question that requires mathematical calculation
55+
$messages = new MessageBag(Message::ofUser('I have 15 apples and I want to share them equally among 4 friends. How many apples does each friend get and how many are left over?'));
56+
$result = $agent->call($messages);
57+
58+
echo $result->getContent().\PHP_EOL;

0 commit comments

Comments
 (0)