|
4 | 4 |
|
5 | 5 | namespace PhpLlm\LlmChain\Chain\Toolbox; |
6 | 6 |
|
| 7 | +use Symfony\Component\Serializer\Encoder\EncoderInterface; |
| 8 | +use Symfony\Component\Serializer\Encoder\JsonEncoder; |
| 9 | +use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; |
| 10 | +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
| 11 | +use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
| 12 | +use Symfony\Component\Serializer\Serializer; |
| 13 | + |
7 | 14 | /** |
8 | 15 | * @author Christopher Hertel <[email protected]> |
9 | 16 | */ |
10 | 17 | final readonly class ToolResultConverter |
11 | 18 | { |
12 | | - /** |
13 | | - * @param \JsonSerializable|\Stringable|array<int|string, mixed>|float|string|null $result |
14 | | - */ |
15 | | - public function convert(\JsonSerializable|\Stringable|array|float|string|\DateTimeInterface|null $result): ?string |
| 19 | + public function __construct( |
| 20 | + private NormalizerInterface&EncoderInterface $serializer = new Serializer([new DateTimeNormalizer(), new ObjectNormalizer()], [new JsonEncoder()]), |
| 21 | + ) { |
| 22 | + } |
| 23 | + |
| 24 | + public function convert(mixed $result): ?string |
16 | 25 | { |
17 | | - if (null === $result) { |
18 | | - return null; |
| 26 | + if (null === $result || \is_string($result)) { |
| 27 | + return $result; |
19 | 28 | } |
20 | 29 |
|
21 | 30 | if ($result instanceof \JsonSerializable || \is_array($result)) { |
22 | 31 | return json_encode($result, flags: \JSON_THROW_ON_ERROR); |
23 | 32 | } |
24 | 33 |
|
25 | | - if (\is_float($result) || $result instanceof \Stringable) { |
| 34 | + if ($result instanceof \Stringable) { |
26 | 35 | return (string) $result; |
27 | 36 | } |
28 | 37 |
|
29 | | - if ($result instanceof \DateTimeInterface) { |
30 | | - return $result->format(\DATE_ATOM); |
| 38 | + $normalized = $this->serializer->normalize($result, 'json'); |
| 39 | + |
| 40 | + if (\is_scalar($normalized)) { |
| 41 | + return (string) $normalized; |
31 | 42 | } |
32 | 43 |
|
33 | | - return $result; |
| 44 | + return $this->serializer->encode($normalized, 'json'); |
34 | 45 | } |
35 | 46 | } |
0 commit comments