Skip to content
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
39 changes: 39 additions & 0 deletions examples/openai/connector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?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\Platform\Bridge\OpenAI\Connector;
use Symfony\AI\Platform\Bridge\OpenAI\GPT;
use Symfony\AI\Platform\ConnectorPlatform;
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);
}

$connector = new Connector($_SERVER['OPENAI_API_KEY']);
$model = new GPT(GPT::GPT_4O_MINI, [
'temperature' => 0.5, // default options for the model
]);

$platform = new ConnectorPlatform($connector);

$result = $platform->call($model, new MessageBag(
Message::forSystem('You are a pirate and you write funny.'),
Message::ofUser('What is the Symfony framework?'),
));

echo $result->asText().\PHP_EOL;
95 changes: 95 additions & 0 deletions src/platform/src/Bridge/OpenAi/Connector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

namespace Symfony\AI\Platform\Bridge\OpenAi;

use Symfony\AI\Platform\Bridge\OpenAi\Contract\OpenAiContract;
use Symfony\AI\Platform\Connector\HttpResult;
use Symfony\AI\Platform\Connector\ResultInterface;
use Symfony\AI\Platform\Contract;
use Symfony\AI\Platform\Exception\InvalidArgumentException;
use Symfony\AI\Platform\Model;
use Symfony\AI\Platform\Connector\HttpConnector;
use Symfony\AI\Platform\Result\ResultInterface as ConverterResult;
use Symfony\AI\Platform\Result\StreamResult;
use Symfony\Component\HttpClient\EventSourceHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final class Connector extends HttpConnector
{
const BASE_URL = 'https://api.openai.com/v1';

public function __construct(
#[\SensitiveParameter] private readonly string $apiKey,
private readonly ?string $region = null,
private readonly ?HttpClientInterface $httpClient = null,
) {
}

public function supports(Model $model): bool
{
return $model instanceof Gpt
|| $model instanceof DallE
|| $model instanceof Embeddings
|| $model instanceof Whisper;
}

public function getContract(): Contract
{
return OpenAiContract::create();
}

protected function initHttpClient(): EventSourceHttpClient
{
$httpClient = $this->httpClient instanceof EventSourceHttpClient
? $this->httpClient : new EventSourceHttpClient($this->httpClient);

return $httpClient->withOptions(['auth_bearer' => $this->apiKey]);
}

protected function getEndpoint(Model $model): string
{
$baseUrl = match ($this->region) {
null => 'https://api.openai.com',
PlatformFactory::REGION_EU => 'https://eu.api.openai.com',
PlatformFactory::REGION_US => 'https://us.api.openai.com',
default => throw new InvalidArgumentException(\sprintf('Invalid region "%s". Valid options are: "%s", "%s", or null.', $this->region, PlatformFactory::REGION_EU, PlatformFactory::REGION_US)),
};

return match (get_class($model)) {
Gpt::class => $baseUrl.'/chat/completions',
DallE::class => $baseUrl.'/images/generations',
Embeddings::class => $baseUrl.'/embeddings',
Whisper::class => $baseUrl.'/audio/transcriptions',
default => throw new InvalidArgumentException('Unsupported model type.'),
};
}

public function isError(ResultInterface $result): bool
{
return false;
}

public function handleStream(Model $model, HttpResult|ResultInterface $result, array $options): StreamResult
{
return match (get_class($model)) {
Gpt::class => (new Gpt\ResultConverter())->convert($result->getRawObject(), $options),
default => throw new InvalidArgumentException('Unsupported model type for streaming.'),
};
}

public function handleError(Model $model, ResultInterface $result): never
{
// TODO: Implement handleError() method.
}

public function handleResult(Model $model, HttpResult|ResultInterface $result, array $options): ConverterResult
{
return match (get_class($model)) {
Gpt::class => (new Gpt\ResultConverter())->convert($result->getRawObject(), $options),
DallE::class => (new DallEModelClient())->convert($result->getRawObject(), $options),
Embeddings::class => (new EmbeddingsResponseConverter())->convert($result->getRawObject(), $options),
Whisper::class => (new WhisperResponseConverter())->convert($result->getRawObject(), $options),
default => throw new InvalidArgumentException('Unsupported model type for streaming.'),
};
}
}
35 changes: 35 additions & 0 deletions src/platform/src/Connector/ConnectorInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Symfony\AI\Platform\Connector;

use Symfony\AI\Platform\Contract;
use Symfony\AI\Platform\Model;
use Symfony\AI\Platform\Result\StreamResult;
use Symfony\AI\Platform\Result\ResultInterface as ConverterResult;

/**
* @author Christopher Hertel <[email protected]>
*/
interface ConnectorInterface
{
public function getContract(): Contract;

/**
* @param array<int|string, mixed>|string $payload
* @param array<string, mixed> $options
*
* @return array<string, mixed>
*/
public function call(Model $model, array|string $payload, array $options): ResultPromise;

public function isError(ResultInterface $result): bool;

public function handleStream(Model $model, ResultInterface $result, array $options): StreamResult;

/**
* @throws ConnectorException
*/
public function handleError(Model $model, ResultInterface $result): never;

public function handleResult(Model $model, ResultInterface $result, array $options): ConverterResult;
}
31 changes: 31 additions & 0 deletions src/platform/src/Connector/HttpConnector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Symfony\AI\Platform\Connector;

use Symfony\AI\Platform\Contract;
use Symfony\AI\Platform\Model;
use Symfony\Component\HttpClient\EventSourceHttpClient;

/**
* @author Christopher Hertel <[email protected]>
*/
abstract class HttpConnector implements ConnectorInterface
{
public function getContract(): Contract
{
return Contract::create();
}

public function call(Model $model, array|string $payload, array $options): ResultPromise
{
$response = $this->initHttpClient()->request('POST', $this->getEndpoint($model), [
'json' => $payload,
]);

return new ResultPromise(new HttpResult($response), $options);
}

abstract protected function initHttpClient(): EventSourceHttpClient;

abstract protected function getEndpoint(Model $model): string;
}
26 changes: 26 additions & 0 deletions src/platform/src/Connector/HttpResult.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Symfony\AI\Platform\Connector;

use Symfony\Contracts\HttpClient\ResponseInterface as HttpResponseInterface;

/**
* @author Christopher Hertel <[email protected]
*/
final readonly class HttpResult implements ResultInterface
{
public function __construct(
private HttpResponseInterface $response,
) {
}

public function getRawData(): array
{
return $this->response->toArray(false);
}

public function getRawObject(): HttpResponseInterface
{
return $this->response;
}
}
23 changes: 23 additions & 0 deletions src/platform/src/Connector/ResultInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Symfony\AI\Platform\Connector;

/**
* @author Christopher Hertel <[email protected]>
*/
interface ResultInterface
{
/**
* Returns an array representation of the raw result data.
*
* @return array<string, mixed>
*/
public function getRawData(): array;

/**
* Returns the raw result object.
*
* @return object
*/
public function getRawObject(): object;
}
141 changes: 141 additions & 0 deletions src/platform/src/Connector/ResultPromise.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<?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\Platform\Connector;

use Symfony\AI\Platform\Exception\RuntimeException;
use Symfony\AI\Platform\Exception\UnexpectedResultTypeException;
use Symfony\AI\Platform\Result\BinaryResult;
use Symfony\AI\Platform\Result\ObjectResult;
use Symfony\AI\Platform\Result\ResultInterface as ConverterResult;
use Symfony\AI\Platform\Result\StreamResult;
use Symfony\AI\Platform\Result\TextResult;
use Symfony\AI\Platform\Result\ToolCall;
use Symfony\AI\Platform\Result\ToolCallResult;
use Symfony\AI\Platform\Result\VectorResult;
use Symfony\AI\Platform\Vector\Vector;

/**
* @author Christopher Hertel <[email protected]>
*/
final class ResultPromise
{
private \Closure $resultConverter;
private bool $isConverted = false;
private ConverterResult $convertedResult;

/**
* @param array<string, mixed> $options
*/
public function __construct(
private readonly ResultInterface $result,
private readonly array $options = [],
) {
}

public function registerConverter(\Closure $resultConverter): void
{
if (isset($this->resultConverter)) {
throw new RuntimeException('A result converter has already been registered for this promise.');
}

$this->resultConverter = $resultConverter;
}

public function getResult(): ConverterResult
{
return $this->await();
}

public function getRawResponse(): ResultInterface
{
return $this->result;
}

public function await(): ConverterResult
{
if (!$this->isConverted) {
if (!isset($this->resultConverter)) {
throw new RuntimeException('No result converter registered to handle the raw result.');
}

$this->convertedResult = ($this->resultConverter)($this->result, $this->options);

if (null === $this->convertedResult->getRawResponse()) {
// Fallback to set the raw response when it was not handled by the response converter itself
$this->convertedResult->setRawResponse($this->result);
}

$this->isConverted = true;
}

return $this->convertedResult;
}

public function asText(): string
{
return $this->as(TextResult::class)->getContent();
}

public function asObject(): object
{
return $this->as(ObjectResult::class)->getContent();
}

public function asBinary(): string
{
return $this->as(BinaryResult::class)->getContent();
}

public function asBase64(): string
{
$response = $this->as(BinaryResult::class);

\assert($response instanceof BinaryResult);

return $response->toDataUri();
}

/**
* @return Vector[]
*/
public function asVectors(): array
{
return $this->as(VectorResult::class)->getContent();
}

public function asStream(): \Generator
{
yield from $this->as(StreamResult::class)->getContent();
}

/**
* @return ToolCall[]
*/
public function asToolCalls(): array
{
return $this->as(ToolCallResult::class)->getContent();
}

/**
* @param class-string $type
*/
private function as(string $type): ConverterResult
{
$response = $this->getResult();

if (!$response instanceof $type) {
throw new UnexpectedResultTypeException($type, $response::class);
}

return $response;
}
}
Loading
Loading