-
-
Notifications
You must be signed in to change notification settings - Fork 102
[Platform] Rework platform by introducing Connectors #646
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
chr-hertel
wants to merge
1
commit into
main
Choose a base branch
from
refactor-platform-connector
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.'), | ||
}; | ||
} | ||
} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
chr-hertel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
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; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.