|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpLlm\LlmChain\Bridge\HuggingFace; |
| 6 | + |
| 7 | +use PhpLlm\LlmChain\Model\Model as BaseModel; |
| 8 | +use PhpLlm\LlmChain\Platform\ModelClient as PlatformModelClient; |
| 9 | +use Symfony\Component\HttpClient\EventSourceHttpClient; |
| 10 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 11 | +use Symfony\Contracts\HttpClient\ResponseInterface; |
| 12 | +use Webmozart\Assert\Assert; |
| 13 | + |
| 14 | +final readonly class ModelClient implements PlatformModelClient |
| 15 | +{ |
| 16 | + private EventSourceHttpClient $httpClient; |
| 17 | + |
| 18 | + public function __construct( |
| 19 | + HttpClientInterface $httpClient, |
| 20 | + private string $provider, |
| 21 | + #[\SensitiveParameter] |
| 22 | + private string $apiKey, |
| 23 | + ) { |
| 24 | + $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient); |
| 25 | + } |
| 26 | + |
| 27 | + public function supports(BaseModel $model, object|array|string $input): bool |
| 28 | + { |
| 29 | + return $model instanceof Model; |
| 30 | + } |
| 31 | + |
| 32 | + public function request(BaseModel $model, object|array|string $input, array $options = []): ResponseInterface |
| 33 | + { |
| 34 | + Assert::isInstanceOf($model, Model::class); |
| 35 | + $url = sprintf('https://router.huggingface.co/%s/models/%s', $this->provider, $model->getName()); |
| 36 | + |
| 37 | + return $this->httpClient->request('POST', $url, [ |
| 38 | + 'auth_bearer' => $this->apiKey, |
| 39 | + 'headers' => ['Content-Type' => 'application/json'], |
| 40 | + 'json' => $this->getPayload($input, $options), |
| 41 | + ]); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @param array<mixed>|string|object $input |
| 46 | + * @param array<string, mixed> $options |
| 47 | + * |
| 48 | + * @return array<string, mixed> |
| 49 | + */ |
| 50 | + public function getPayload(object|array|string $input, array $options = []): array |
| 51 | + { |
| 52 | + $task = $options['task'] ?? null; |
| 53 | + |
| 54 | + if (Task::TEXT_CLASSIFICATION === $task) { |
| 55 | + return [ |
| 56 | + 'inputs' => $input, |
| 57 | + ]; |
| 58 | + } |
| 59 | + |
| 60 | + throw new \InvalidArgumentException('Unsupported task: '.$task); |
| 61 | + } |
| 62 | +} |
0 commit comments