|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpLlm\LlmChain\Bridge\OpenRouter; |
| 6 | + |
| 7 | +use PhpLlm\LlmChain\Exception\RuntimeException; |
| 8 | +use PhpLlm\LlmChain\Model\Message\MessageBagInterface; |
| 9 | +use PhpLlm\LlmChain\Model\Model; |
| 10 | +use PhpLlm\LlmChain\Model\Response\ResponseInterface as LlmResponse; |
| 11 | +use PhpLlm\LlmChain\Model\Response\TextResponse; |
| 12 | +use PhpLlm\LlmChain\Platform\ModelClient; |
| 13 | +use PhpLlm\LlmChain\Platform\ResponseConverter; |
| 14 | +use Symfony\Component\HttpClient\EventSourceHttpClient; |
| 15 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 16 | +use Symfony\Contracts\HttpClient\ResponseInterface; |
| 17 | +use Webmozart\Assert\Assert; |
| 18 | + |
| 19 | +final readonly class Client implements ModelClient, ResponseConverter |
| 20 | +{ |
| 21 | + private EventSourceHttpClient $httpClient; |
| 22 | + |
| 23 | + public function __construct( |
| 24 | + HttpClientInterface $httpClient, |
| 25 | + #[\SensitiveParameter] private string $apiKey, |
| 26 | + ) { |
| 27 | + $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient); |
| 28 | + Assert::stringNotEmpty($apiKey, 'The API key must not be empty.'); |
| 29 | + Assert::startsWith($apiKey, 'sk-', 'The API key must start with "sk-".'); |
| 30 | + } |
| 31 | + |
| 32 | + public function supports(Model $model, array|string|object $input): bool |
| 33 | + { |
| 34 | + return $input instanceof MessageBagInterface; |
| 35 | + } |
| 36 | + |
| 37 | + public function request(Model $model, object|array|string $input, array $options = []): ResponseInterface |
| 38 | + { |
| 39 | + return $this->httpClient->request('POST', 'https://openrouter.ai/api/v1/chat/completions', [ |
| 40 | + 'auth_bearer' => $this->apiKey, |
| 41 | + 'json' => array_merge($options, [ |
| 42 | + 'model' => $model->getVersion(), |
| 43 | + 'messages' => $input, |
| 44 | + ]), |
| 45 | + ]); |
| 46 | + } |
| 47 | + |
| 48 | + public function convert(ResponseInterface $response, array $options = []): LlmResponse |
| 49 | + { |
| 50 | + $data = $response->toArray(); |
| 51 | + |
| 52 | + if (!isset($data['choices'][0]['message'])) { |
| 53 | + throw new RuntimeException('Response does not contain message'); |
| 54 | + } |
| 55 | + |
| 56 | + if (!isset($data['choices'][0]['message']['content'])) { |
| 57 | + throw new RuntimeException('Message does not contain content'); |
| 58 | + } |
| 59 | + |
| 60 | + return new TextResponse($data['choices'][0]['message']['content']); |
| 61 | + } |
| 62 | +} |
0 commit comments