Skip to content

[Platform][RFC] OpenAI Responses API #149

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions examples/openai/responses-stream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\Platform\Bridge\OpenAI\GPT;
use Symfony\AI\Platform\Bridge\OpenAI\PlatformFactory;
use Symfony\AI\Platform\Bridge\OpenAI\Responses;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\Dotenv\Dotenv;

require_once dirname(__DIR__).'/vendor/autoload.php';
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');

if (!isset($_SERVER['OPENAI_API_KEY'])) {
echo 'Please set the OPENAI_API_KEY environment variable.'.\PHP_EOL;
exit(1);
}

$platform = PlatformFactory::create($_SERVER['OPENAI_API_KEY']);
$model = new Responses(Responses::GPT_4O_MINI);

$agent = new Agent($platform, $model);
$messages = new MessageBag(
Message::forSystem('You are a thoughtful philosopher.'),
Message::ofUser('What is the purpose of an ant?'),
);
$response = $agent->call($messages, [
'stream' => true, // enable streaming of response text
]);

foreach ($response->getContent() as $word) {
echo $word;
}
echo \PHP_EOL;
61 changes: 61 additions & 0 deletions examples/openai/responses-structured-output-clock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\StructuredOutput\Responses\ResponsesAgentProcessor;
use Symfony\AI\Platform\Bridge\OpenAI\PlatformFactory;
use Symfony\AI\Platform\Bridge\OpenAI\Responses;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\Dotenv\Dotenv;

require_once dirname(__DIR__).'/vendor/autoload.php';
(new Dotenv())->loadEnv(dirname(__DIR__) . '/.env');

if (!isset($_SERVER['OPENAI_API_KEY'])) {
echo 'Please set the OPENAI_API_KEY environment variable.' . \PHP_EOL;
exit(1);
}

$platform = PlatformFactory::create($_SERVER['OPENAI_API_KEY']);
$model = new Responses(Responses::GPT_4O_MINI);

$structuredOutputProcessor = new ResponsesAgentProcessor();

$agent = new Agent($platform, $model, [$structuredOutputProcessor], [$structuredOutputProcessor]);
$messages = new MessageBag(
Message::ofUser('What date and time is it?'),
);
$response = $agent->call($messages, [
'text' => [
'format' => [
'type' => 'json_schema',
'name' => 'clock',
'schema' => [
'type' => 'object',
'properties' => [
'date' => [
'type' => 'string',
'description' => 'The current date in the format YYYY-MM-DD.',
],
'time' => [
'type' => 'string',
'description' => 'The current time in the format HH:MM:SS.',
],
],
'required' => ['date', 'time'],
'additionalProperties' => false,
],
],
],
]);

dump($response->getContent());
43 changes: 43 additions & 0 deletions examples/openai/responses-structured-output-math.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\StructuredOutput\Responses\ResponsesAgentProcessor;
use Symfony\AI\Fixtures\StructuredOutput\MathReasoning;
use Symfony\AI\Platform\Bridge\OpenAI\PlatformFactory;
use Symfony\AI\Platform\Bridge\OpenAI\Responses;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\Dotenv\Dotenv;

require_once dirname(__DIR__).'/vendor/autoload.php';
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');

if (!isset($_SERVER['OPENAI_API_KEY'])) {
echo 'Please set the OPENAI_API_KEY environment variable.'.\PHP_EOL;
exit(1);
}

$platform = PlatformFactory::create($_SERVER['OPENAI_API_KEY']);
$model = new Responses(Responses::GPT_4O_MINI);

$processor = new ResponsesAgentProcessor();

$agent = new Agent($platform, $model, [$processor], [$processor]);
$messages = new MessageBag(
Message::forSystem('You are a helpful math tutor. Guide the user through the solution step by step.'),
Message::ofUser('how can I solve 8x + 7 = -23'),
);
$response = $agent->call($messages, [
'output_structure' => MathReasoning::class,
]);

dump($response->getContent());
45 changes: 45 additions & 0 deletions examples/openai/responses-toolcall-stream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\Platform\Bridge\OpenAI\PlatformFactory;
use Symfony\AI\Platform\Bridge\OpenAI\Responses;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\Dotenv\Dotenv;

require_once dirname(__DIR__).'/vendor/autoload.php';
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');

if (!isset($_SERVER['OPENAI_API_KEY'])) {
echo 'Please set the OPENAI_API_KEY environment variable.'.\PHP_EOL;
exit(1);
}

$platform = PlatformFactory::create($_SERVER['OPENAI_API_KEY']);
$model = new Responses(Responses::GPT_4O_MINI);

$agent = new Agent($platform, $model);
$messages = new MessageBag(Message::ofUser('What was a positive news story from today?'));
$response = $agent->call($messages, [
'stream' => true, // enable streaming of response text
'tools' => [
[
'type' => 'web_search_preview',
],
],
]);

foreach ($response->getContent() as $word) {
echo $word;
}

echo \PHP_EOL;
41 changes: 41 additions & 0 deletions examples/openai/responses.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\Platform\Bridge\OpenAI\PlatformFactory;
use Symfony\AI\Platform\Bridge\OpenAI\Responses;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Component\Dotenv\Dotenv;

require_once dirname(__DIR__).'/vendor/autoload.php';
(new Dotenv())->loadEnv(dirname(__DIR__) . '/.env');

if (!isset($_SERVER['OPENAI_API_KEY'])) {
echo 'Please set the OPENAI_API_KEY environment variable.' . \PHP_EOL;
exit(1);
}

$platform = PlatformFactory::create($_SERVER['OPENAI_API_KEY']);
$model = new Responses(Responses::GPT_4O_MINI, [
'temperature' => 0.5, // default options for the model
]);

$agent = new Agent($platform, $model);
$messages = new MessageBag(
Message::forSystem('You are a pirate and you write funny.'),
Message::ofUser('What is the Symfony framework?'),
);
$response = $agent->call($messages, [
'max_output_tokens' => 500, // specific options just for this call
]);

echo $response->getContent().\PHP_EOL;
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\AI\Agent\StructuredOutput\Responses;

use Symfony\AI\Agent\Exception\InvalidArgumentException;
use Symfony\AI\Agent\Exception\MissingModelSupportException;
use Symfony\AI\Agent\Input;
use Symfony\AI\Agent\InputProcessorInterface;
use Symfony\AI\Agent\Output;
use Symfony\AI\Agent\OutputProcessorInterface;
use Symfony\AI\Platform\Capability;
use Symfony\AI\Platform\Response\ObjectResponse;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;

/**
* @author Christopher Hertel <[email protected]>
*/
final class ResponsesAgentProcessor implements InputProcessorInterface, OutputProcessorInterface
{
private string $outputStructure;

public function __construct(
private readonly ResponsesResponseFormatFactoryInterface $responseFormatFactory = new ResponsesResponseFormatFactory(),
private ?SerializerInterface $serializer = null,
)
{
if (null === $this->serializer) {
$propertyInfo = new PropertyInfoExtractor([], [new PhpDocExtractor()]);
$normalizers = [new ObjectNormalizer(propertyTypeExtractor: $propertyInfo), new ArrayDenormalizer()];
$this->serializer = new Serializer($normalizers, [new JsonEncoder()]);
}
}

public function processInput(Input $input): void
{
$options = $input->getOptions();

if (!isset($options['output_structure'])) {
return;
}

if (!$input->model->supports(Capability::OUTPUT_STRUCTURED)) {
throw MissingModelSupportException::forStructuredOutput($input->model::class);
}

if (true === ($options['stream'] ?? false)) {
throw new InvalidArgumentException('Streamed responses are not supported for structured output');
}

$options['text'] = $this->responseFormatFactory->create($options['output_structure']);

$this->outputStructure = $options['output_structure'];
unset($options['output_structure']);

$input->setOptions($options);
}

public function processOutput(Output $output): void
{
$options = $output->options;

if ($output->response instanceof ObjectResponse) {
return;
}

if (!isset($options['text']['format'])) {
return;
}

if (!isset($this->outputStructure)) {
$output->response = new ObjectResponse(json_decode($output->response->getContent(), true));

return;
}

$output->response = new ObjectResponse(
$this->serializer->deserialize($output->response->getContent(), $this->outputStructure, 'json')
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\AI\Agent\StructuredOutput\Responses;

use Symfony\AI\Platform\Contract\JsonSchema\Factory;
use function Symfony\Component\String\u;

/**
* @author Christopher Hertel <[email protected]>
*/
final readonly class ResponsesResponseFormatFactory implements ResponsesResponseFormatFactoryInterface
{
public function __construct(
private Factory $schemaFactory = new Factory(),
) {
}

public function create(string $responseClass): array
{
return [
'format' => [
'type' => 'json_schema',
'name' => u($responseClass)->afterLast('\\')->toString(),
'strict' => true,
'schema' => $this->schemaFactory->buildProperties($responseClass),
],
];
}
}
Loading
Loading