Skip to content
This repository was archived by the owner on Jul 16, 2025. It is now read-only.

feat: allow JsonSerializable objects in contract #377

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Platform/Contract.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use PhpLlm\LlmChain\Platform\Contract\Normalizer\ToolNormalizer;
use PhpLlm\LlmChain\Platform\Tool\Tool;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Serializer;

Expand Down Expand Up @@ -53,6 +54,9 @@ public static function create(NormalizerInterface ...$normalizer): self
// Response
$normalizer[] = new ToolCallNormalizer();

// JsonSerializable objects as extension point to library interfaces
$normalizer[] = new JsonSerializableNormalizer();

return new self(
new Serializer($normalizer),
);
Expand Down
34 changes: 34 additions & 0 deletions tests/Platform/ContractTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
use PhpLlm\LlmChain\Platform\Message\Content\ImageUrl;
use PhpLlm\LlmChain\Platform\Message\Message;
use PhpLlm\LlmChain\Platform\Message\MessageBag;
use PhpLlm\LlmChain\Platform\Message\MessageInterface;
use PhpLlm\LlmChain\Platform\Message\Role;
use PhpLlm\LlmChain\Platform\Message\SystemMessage;
use PhpLlm\LlmChain\Platform\Message\UserMessage;
use PhpLlm\LlmChain\Platform\Model;
Expand All @@ -33,6 +35,7 @@
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Uid\Uuid;

#[Large]
#[CoversClass(Contract::class)]
Expand Down Expand Up @@ -191,6 +194,37 @@ public static function providePayloadTestCases(): iterable
'model' => 'gpt-4o',
],
];

$customSerializableMessage = new class implements MessageInterface, \JsonSerializable {
public function getRole(): Role
{
return Role::User;
}

public function getId(): Uuid
{
return Uuid::v7();
}

public function jsonSerialize(): array
{
return [
'role' => 'user',
'content' => 'This is a custom serializable message.',
];
}
};

yield 'MessageBag with custom message from GPT' => [
'model' => new GPT(),
'input' => new MessageBag($customSerializableMessage),
'expected' => [
'messages' => [
['role' => 'user', 'content' => 'This is a custom serializable message.'],
],
'model' => 'gpt-4o',
],
];
}

#[Test]
Expand Down