Skip to content
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

Add possibility to react to content filter violation #192

Merged
merged 4 commits into from
Jan 13, 2025
Merged
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
14 changes: 13 additions & 1 deletion src/Bridge/OpenAI/GPT/ResponseConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace PhpLlm\LlmChain\Bridge\OpenAI\GPT;

use PhpLlm\LlmChain\Bridge\OpenAI\GPT;
use PhpLlm\LlmChain\Exception\ContentFilterException;
use PhpLlm\LlmChain\Exception\RuntimeException;
use PhpLlm\LlmChain\Model\Model;
use PhpLlm\LlmChain\Model\Response\Choice;
Expand All @@ -18,6 +19,7 @@
use Symfony\Component\HttpClient\Chunk\ServerSentEvent;
use Symfony\Component\HttpClient\EventSourceHttpClient;
use Symfony\Component\HttpClient\Exception\JsonException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\ResponseInterface as HttpResponse;

final class ResponseConverter implements PlatformResponseConverter
Expand All @@ -33,7 +35,17 @@ public function convert(HttpResponse $response, array $options = []): LlmRespons
return $this->convertStream($response);
}

$data = $response->toArray();
try {
$data = $response->toArray();
} catch (ClientExceptionInterface $e) {
$data = $response->toArray(throw: false);

if (isset($data['error']['code']) && 'content_filter' === $data['error']['code']) {
throw new ContentFilterException(message: $data['error']['message'], previous: $e);
}

throw $e;
}

if (!isset($data['choices'])) {
throw new RuntimeException('Response does not contain choices');
Expand Down
9 changes: 9 additions & 0 deletions src/Exception/ContentFilterException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace PhpLlm\LlmChain\Exception;

class ContentFilterException extends InvalidArgumentException
{
}
Loading