|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\AI\Platform\Bridge\Cerebras; |
| 13 | + |
| 14 | +use Symfony\AI\Platform\Exception\RuntimeException; |
| 15 | +use Symfony\AI\Platform\Model as BaseModel; |
| 16 | +use Symfony\AI\Platform\Result\RawHttpResult; |
| 17 | +use Symfony\AI\Platform\Result\RawResultInterface; |
| 18 | +use Symfony\AI\Platform\Result\ResultInterface; |
| 19 | +use Symfony\AI\Platform\Result\StreamResult; |
| 20 | +use Symfony\AI\Platform\Result\TextResult; |
| 21 | +use Symfony\AI\Platform\ResultConverterInterface; |
| 22 | +use Symfony\Component\HttpClient\Chunk\ServerSentEvent; |
| 23 | +use Symfony\Component\HttpClient\EventSourceHttpClient; |
| 24 | +use Symfony\Component\HttpClient\Exception\JsonException; |
| 25 | +use Symfony\Contracts\HttpClient\ResponseInterface as HttpResponse; |
| 26 | + |
| 27 | +/** |
| 28 | + * @author Junaid Farooq <[email protected]> |
| 29 | + */ |
| 30 | +final readonly class ResultConverter implements ResultConverterInterface |
| 31 | +{ |
| 32 | + public function supports(BaseModel $model): bool |
| 33 | + { |
| 34 | + return $model instanceof Model; |
| 35 | + } |
| 36 | + |
| 37 | + public function convert(RawHttpResult|RawResultInterface $result, array $options = []): ResultInterface |
| 38 | + { |
| 39 | + if ($options['stream'] ?? false) { |
| 40 | + return new StreamResult($this->convertStream($result->getObject())); |
| 41 | + } |
| 42 | + |
| 43 | + $data = $result->getData(); |
| 44 | + |
| 45 | + if (!isset($data['choices'][0]['message']['content'])) { |
| 46 | + if (isset($data['type'], $data['message']) && str_ends_with($data['type'], 'error')) { |
| 47 | + throw new RuntimeException(sprintf('Cerebras API error: %s', $data['message'])); |
| 48 | + } |
| 49 | + |
| 50 | + throw new RuntimeException('Response does not contain output.'); |
| 51 | + } |
| 52 | + |
| 53 | + return new TextResult($data['choices'][0]['message']['content']); |
| 54 | + } |
| 55 | + |
| 56 | + private function convertStream(HttpResponse $result): \Generator |
| 57 | + { |
| 58 | + foreach ((new EventSourceHttpClient())->stream($result) as $chunk) { |
| 59 | + if (!$chunk instanceof ServerSentEvent || '[DONE]' === $chunk->getData()) { |
| 60 | + continue; |
| 61 | + } |
| 62 | + |
| 63 | + try { |
| 64 | + $data = $chunk->getArrayData(); |
| 65 | + } catch (JsonException) { |
| 66 | + continue; |
| 67 | + } |
| 68 | + |
| 69 | + if (!isset($data['choices'][0]['delta']['content'])) { |
| 70 | + continue; |
| 71 | + } |
| 72 | + |
| 73 | + yield $data['choices'][0]['delta']['content']; |
| 74 | + } |
| 75 | + } |
| 76 | +} |
| 77 | + |
0 commit comments