|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpLlm\LlmChain\Bridge\TransformersPHP; |
| 6 | + |
| 7 | +use Codewithkyrian\Transformers\Pipelines\Task; |
| 8 | +use PhpLlm\LlmChain\Model\Model as BaseModel; |
| 9 | +use PhpLlm\LlmChain\Model\Response\ResponseInterface as LlmResponse; |
| 10 | +use PhpLlm\LlmChain\Model\Response\StructuredResponse; |
| 11 | +use PhpLlm\LlmChain\Model\Response\TextResponse; |
| 12 | +use PhpLlm\LlmChain\Platform\ModelClient; |
| 13 | +use PhpLlm\LlmChain\Platform\ResponseConverter; |
| 14 | +use Symfony\Contracts\HttpClient\ResponseInterface; |
| 15 | + |
| 16 | +use function Codewithkyrian\Transformers\Pipelines\pipeline; |
| 17 | + |
| 18 | +final readonly class Handler implements ModelClient, ResponseConverter |
| 19 | +{ |
| 20 | + public function supports(BaseModel $model, object|array|string $input): bool |
| 21 | + { |
| 22 | + return $model instanceof Model; |
| 23 | + } |
| 24 | + |
| 25 | + public function request(BaseModel $model, object|array|string $input, array $options = []): ResponseInterface |
| 26 | + { |
| 27 | + if (!isset($options['task'])) { |
| 28 | + throw new \InvalidArgumentException('The task option is required.'); |
| 29 | + } |
| 30 | + |
| 31 | + $pipeline = pipeline( |
| 32 | + $options['task'], |
| 33 | + $model->getName(), |
| 34 | + $options['quantized'] ?? true, |
| 35 | + $options['config'] ?? null, |
| 36 | + $options['cacheDir'] ?? null, |
| 37 | + $options['revision'] ?? 'main', |
| 38 | + $options['modelFilename'] ?? null, |
| 39 | + ); |
| 40 | + |
| 41 | + return new PipelineResponse($pipeline, $input); |
| 42 | + } |
| 43 | + |
| 44 | + public function convert(ResponseInterface $response, array $options = []): LlmResponse |
| 45 | + { |
| 46 | + if (!$response instanceof PipelineResponse) { |
| 47 | + throw new \InvalidArgumentException('The response is not a valid TransformersPHP response.'); |
| 48 | + } |
| 49 | + |
| 50 | + $task = $options['task']; |
| 51 | + $data = $response->toArray(); |
| 52 | + |
| 53 | + return match ($task) { |
| 54 | + Task::Text2TextGeneration => new TextResponse($data[0]['generated_text']), |
| 55 | + default => new StructuredResponse($response->toArray()), |
| 56 | + }; |
| 57 | + } |
| 58 | +} |
0 commit comments