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