Skip to content
Open
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
8 changes: 2 additions & 6 deletions src/platform/src/Bridge/Anthropic/ResultConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace Symfony\AI\Platform\Bridge\Anthropic;

use Symfony\AI\Platform\Exception\RateLimitExceededException;
use Symfony\AI\Platform\Exception\HttpErrorHandler;
use Symfony\AI\Platform\Exception\RuntimeException;
use Symfony\AI\Platform\Model;
use Symfony\AI\Platform\Result\RawHttpResult;
Expand Down Expand Up @@ -41,11 +41,7 @@ public function convert(RawHttpResult|RawResultInterface $result, array $options
{
$response = $result->getObject();

if (429 === $response->getStatusCode()) {
$retryAfter = $response->getHeaders(false)['retry-after'][0] ?? null;
$retryAfterValue = $retryAfter ? (float) $retryAfter : null;
throw new RateLimitExceededException($retryAfterValue);
}
HttpErrorHandler::handleHttpError($response);

if ($options['stream'] ?? false) {
return new StreamResult($this->convertStream($response));
Expand Down
6 changes: 5 additions & 1 deletion src/platform/src/Bridge/Cerebras/ResultConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\AI\Platform\Bridge\Cerebras;

use Symfony\AI\Platform\Exception\HttpErrorHandler;
use Symfony\AI\Platform\Exception\RuntimeException;
use Symfony\AI\Platform\Model as BaseModel;
use Symfony\AI\Platform\Result\RawHttpResult;
Expand All @@ -36,8 +37,11 @@ public function supports(BaseModel $model): bool

public function convert(RawHttpResult|RawResultInterface $result, array $options = []): ResultInterface
{
$response = $result->getObject();
HttpErrorHandler::handleHttpError($response);

if ($options['stream'] ?? false) {
return new StreamResult($this->convertStream($result->getObject()));
return new StreamResult($this->convertStream($response));
}

$data = $result->getData();
Expand Down
6 changes: 2 additions & 4 deletions src/platform/src/Bridge/Gemini/Gemini/ResultConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace Symfony\AI\Platform\Bridge\Gemini\Gemini;

use Symfony\AI\Platform\Bridge\Gemini\Gemini;
use Symfony\AI\Platform\Exception\RateLimitExceededException;
use Symfony\AI\Platform\Exception\HttpErrorHandler;
use Symfony\AI\Platform\Exception\RuntimeException;
use Symfony\AI\Platform\Model;
use Symfony\AI\Platform\Result\ChoiceResult;
Expand Down Expand Up @@ -45,9 +45,7 @@ public function convert(RawResultInterface|RawHttpResult $result, array $options
{
$response = $result->getObject();

if (429 === $response->getStatusCode()) {
throw new RateLimitExceededException();
}
HttpErrorHandler::handleHttpError($response);

if ($options['stream'] ?? false) {
return new StreamResult($this->convertStream($response));
Expand Down
42 changes: 2 additions & 40 deletions src/platform/src/Bridge/OpenAi/Gpt/ResultConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
namespace Symfony\AI\Platform\Bridge\OpenAi\Gpt;

use Symfony\AI\Platform\Bridge\OpenAi\Gpt;
use Symfony\AI\Platform\Exception\AuthenticationException;
use Symfony\AI\Platform\Exception\ContentFilterException;
use Symfony\AI\Platform\Exception\RateLimitExceededException;
use Symfony\AI\Platform\Exception\HttpErrorHandler;
use Symfony\AI\Platform\Exception\RuntimeException;
use Symfony\AI\Platform\Model;
use Symfony\AI\Platform\Result\ChoiceResult;
Expand Down Expand Up @@ -46,23 +45,7 @@ public function convert(RawResultInterface|RawHttpResult $result, array $options
{
$response = $result->getObject();

if (401 === $response->getStatusCode()) {
$errorMessage = json_decode($response->getContent(false), true)['error']['message'];
throw new AuthenticationException($errorMessage);
}

if (429 === $response->getStatusCode()) {
$headers = $response->getHeaders(false);
$resetTime = null;

if (isset($headers['x-ratelimit-reset-requests'][0])) {
$resetTime = self::parseResetTime($headers['x-ratelimit-reset-requests'][0]);
} elseif (isset($headers['x-ratelimit-reset-tokens'][0])) {
$resetTime = self::parseResetTime($headers['x-ratelimit-reset-tokens'][0]);
}

throw new RateLimitExceededException($resetTime);
}
HttpErrorHandler::handleHttpError($response);

if ($options['stream'] ?? false) {
return new StreamResult($this->convertStream($response));
Expand Down Expand Up @@ -208,25 +191,4 @@ private function convertToolCall(array $toolCall): ToolCall

return new ToolCall($toolCall['id'], $toolCall['function']['name'], $arguments);
}

/**
* Converts OpenAI's reset time format (e.g. "1s", "6m0s", "2m30s") into seconds.
*
* Supported formats:
* - "1s"
* - "6m0s"
* - "2m30s"
*/
private static function parseResetTime(string $resetTime): float
{
$seconds = 0;

if (preg_match('/^(?:(\d+)m)?(?:(\d+)s)?$/', $resetTime, $matches)) {
$minutes = isset($matches[1]) ? (int) $matches[1] : 0;
$secs = isset($matches[2]) ? (int) $matches[2] : 0;
$seconds = ($minutes * 60) + $secs;
}

return (float) $seconds;
}
}
6 changes: 5 additions & 1 deletion src/platform/src/Bridge/Perplexity/ResultConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\AI\Platform\Bridge\Perplexity;

use Symfony\AI\Platform\Exception\HttpErrorHandler;
use Symfony\AI\Platform\Exception\RuntimeException;
use Symfony\AI\Platform\Metadata\Metadata;
use Symfony\AI\Platform\Model;
Expand Down Expand Up @@ -38,8 +39,11 @@ public function supports(Model $model): bool

public function convert(RawResultInterface|RawHttpResult $result, array $options = []): ResultInterface
{
$response = $result->getObject();
HttpErrorHandler::handleHttpError($response);

if ($options['stream'] ?? false) {
return new StreamResult($this->convertStream($result->getObject()));
return new StreamResult($this->convertStream($response));
}

$data = $result->getData();
Expand Down
107 changes: 107 additions & 0 deletions src/platform/src/Exception/HttpErrorHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?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\Exception;

use Symfony\Contracts\HttpClient\ResponseInterface;

/**
* @author Junaid Farooq <[email protected]>
*/
final class HttpErrorHandler
{
public static function handleHttpError(ResponseInterface $response): void
{
$statusCode = $response->getStatusCode();

if ($statusCode >= 200 && $statusCode < 300) {
return;
}

$errorMessage = self::extractErrorMessage($response);

match ($statusCode) {
401 => throw new AuthenticationException($errorMessage),
404 => throw new NotFoundException($errorMessage),
429 => throw new RateLimitExceededException(self::extractRetryAfter($response)),
503 => throw new ServiceUnavailableException($errorMessage),
default => throw new RuntimeException(\sprintf('HTTP %d: %s', $statusCode, $errorMessage)),
};
}

private static function extractErrorMessage(ResponseInterface $response): string
{
$content = $response->getContent(false);

if ('' === $content) {
return \sprintf('HTTP %d error', $response->getStatusCode());
}

$data = json_decode($content, true);

if (!\is_array($data)) {
return $content;
}

if (isset($data['error']['message'])) {
return $data['error']['message'];
}

if (isset($data['error']) && \is_string($data['error'])) {
return $data['error'];
}

return $data['message'] ?? $data['detail'] ?? $content;
}

private static function extractRetryAfter(ResponseInterface $response): ?float
{
$headers = $response->getHeaders(false);

if (isset($headers['retry-after'][0])) {
return (float) $headers['retry-after'][0];
}

if (isset($headers['x-ratelimit-reset-requests'][0])) {
return self::parseResetTime($headers['x-ratelimit-reset-requests'][0]);
}

if (isset($headers['x-ratelimit-reset-tokens'][0])) {
return self::parseResetTime($headers['x-ratelimit-reset-tokens'][0]);
}

return null;
}

private static function parseResetTime(string $resetTime): ?float
{
if (is_numeric($resetTime)) {
return (float) $resetTime;
}

if (preg_match('/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/', $resetTime, $matches)) {
$hours = (int) ($matches[1] ?? 0);
$minutes = (int) ($matches[2] ?? 0);
$seconds = (int) ($matches[3] ?? 0);

return (float) ($hours * 3600 + $minutes * 60 + $seconds);
}

$timestamp = strtotime($resetTime);
if (false === $timestamp) {
return null;
}

$diff = $timestamp - time();

return $diff > 0 ? (float) $diff : null;
}
}
19 changes: 19 additions & 0 deletions src/platform/src/Exception/NotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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\Exception;

/**
* @author Junaid Farooq <[email protected]>
*/
class NotFoundException extends InvalidArgumentException
{
}
19 changes: 19 additions & 0 deletions src/platform/src/Exception/ServiceUnavailableException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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\Exception;

/**
* @author Junaid Farooq <[email protected]>
*/
class ServiceUnavailableException extends RuntimeException
{
}
Loading