|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpLlm\LlmChain\Bridge\OpenAI\Whisper; |
| 6 | + |
| 7 | +use PhpLlm\LlmChain\Bridge\OpenAI\Whisper; |
| 8 | +use PhpLlm\LlmChain\Model\Model; |
| 9 | +use PhpLlm\LlmChain\Model\Response\ResponseInterface as LlmResponse; |
| 10 | +use PhpLlm\LlmChain\Model\Response\TextResponse; |
| 11 | +use PhpLlm\LlmChain\Platform\ModelClient as PlatformResponseFactory; |
| 12 | +use PhpLlm\LlmChain\Platform\ResponseConverter as PlatformResponseConverter; |
| 13 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 14 | +use Symfony\Contracts\HttpClient\ResponseInterface; |
| 15 | +use Webmozart\Assert\Assert; |
| 16 | + |
| 17 | +final readonly class ModelClient implements PlatformResponseFactory, PlatformResponseConverter |
| 18 | +{ |
| 19 | + public function __construct( |
| 20 | + private HttpClientInterface $httpClient, |
| 21 | + #[\SensitiveParameter] |
| 22 | + private string $apiKey, |
| 23 | + ) { |
| 24 | + Assert::stringNotEmpty($apiKey, 'The API key must not be empty.'); |
| 25 | + } |
| 26 | + |
| 27 | + public function supports(Model $model, object|array|string $input): bool |
| 28 | + { |
| 29 | + return $model instanceof Whisper && $input instanceof File; |
| 30 | + } |
| 31 | + |
| 32 | + public function request(Model $model, object|array|string $input, array $options = []): ResponseInterface |
| 33 | + { |
| 34 | + assert($input instanceof File); |
| 35 | + |
| 36 | + return $this->httpClient->request('POST', 'https://api.openai.com/v1/audio/transcriptions', [ |
| 37 | + 'auth_bearer' => $this->apiKey, |
| 38 | + 'headers' => ['Content-Type' => 'multipart/form-data'], |
| 39 | + 'body' => array_merge($options, $model->getOptions(), [ |
| 40 | + 'model' => $model->getVersion(), |
| 41 | + 'file' => fopen($input->path, 'r'), |
| 42 | + ]), |
| 43 | + ]); |
| 44 | + } |
| 45 | + |
| 46 | + public function convert(ResponseInterface $response, array $options = []): LlmResponse |
| 47 | + { |
| 48 | + $data = $response->toArray(); |
| 49 | + |
| 50 | + return new TextResponse($data['text']); |
| 51 | + } |
| 52 | +} |
0 commit comments