Skip to content

refactor: switch from JsonSerializable to normalizer #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"mongodb/mongodb": "^1.21",
"php-cs-fixer/shim": "^3.70",
"phpstan/phpstan": "^2.0",
"phpstan/phpstan-symfony": "^2.0",
"phpstan/phpstan-webmozart-assert": "^2.0",
"phpunit/phpunit": "^11.5",
"probots-io/pinecone-php": "^1.0",
Expand Down
1 change: 1 addition & 0 deletions phpstan.dist.neon
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
includes:
- vendor/phpstan/phpstan-webmozart-assert/extension.neon
- vendor/phpstan/phpstan-symfony/extension.neon

parameters:
level: 6
Expand Down
56 changes: 56 additions & 0 deletions src/Bridge/Anthropic/Contract/AssistantMessageNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

namespace PhpLlm\LlmChain\Bridge\Anthropic\Contract;

use PhpLlm\LlmChain\Model\Message\AssistantMessage;
use PhpLlm\LlmChain\Model\Response\ToolCall;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class AssistantMessageNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;

public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AssistantMessage && $data->hasToolCalls();
}

public function getSupportedTypes(?string $format): array
{
return [
AssistantMessage::class => true,
];
}

/**
* @param AssistantMessage $data
*
* @return array{
* role: 'assistant',
* content: list<array{
* type: 'tool_use',
* id: string,
* name: string,
* input: array<string, mixed>
* }>
* }
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
return [
'role' => 'assistant',
'content' => array_map(static function (ToolCall $toolCall) {
return [
'type' => 'tool_use',
'id' => $toolCall->id,
'name' => $toolCall->name,
'input' => empty($toolCall->arguments) ? new \stdClass() : $toolCall->arguments,
];
}, $data->toolCalls),
];
}
}
49 changes: 49 additions & 0 deletions src/Bridge/Anthropic/Contract/ImageNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace PhpLlm\LlmChain\Bridge\Anthropic\Contract;

use PhpLlm\LlmChain\Model\Message\Content\Image;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

use function Symfony\Component\String\u;

final class ImageNormalizer implements NormalizerInterface
{
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof Image;
}

public function getSupportedTypes(?string $format): array
{
return [
Image::class => true,
];
}

/**
* @param Image $data
*
* @return array{
* type: 'image',
* source: array{
* type: 'base64',
* media_type: string,
* data: string
* }
* }
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
return [
'type' => 'image',
'source' => [
'type' => 'base64',
'media_type' => u($data->getFormat())->replace('jpg', 'jpeg')->toString(),
'data' => $data->asBase64(),
],
];
}
}
55 changes: 55 additions & 0 deletions src/Bridge/Anthropic/Contract/MessageBagNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace PhpLlm\LlmChain\Bridge\Anthropic\Contract;

use PhpLlm\LlmChain\Model\Message\MessageBagInterface;
use PhpLlm\LlmChain\Model\Model;
use PhpLlm\LlmChain\Platform\Contract;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class MessageBagNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;

public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof MessageBagInterface;
}

public function getSupportedTypes(?string $format): array
{
return [
MessageBagInterface::class => true,
];
}

/**
* @param MessageBagInterface $data
*
* @return array{
* messages: array<string, mixed>,
* model?: string,
* system?: string,
* }
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
$array = [
'messages' => $this->normalizer->normalize($data->withoutSystemMessage()->getMessages(), $format, $context),
];

if (null !== $system = $data->getSystemMessage()) {
$array['system'] = $system->content;
}

if (isset($context[Contract::CONTEXT_MODEL]) && $context[Contract::CONTEXT_MODEL] instanceof Model) {
$array['model'] = $context[Contract::CONTEXT_MODEL]->getName();
}

return $array;
}
}
53 changes: 53 additions & 0 deletions src/Bridge/Anthropic/Contract/ToolCallMessageNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace PhpLlm\LlmChain\Bridge\Anthropic\Contract;

use PhpLlm\LlmChain\Model\Message\ToolCallMessage;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class ToolCallMessageNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;

public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof ToolCallMessage;
}

public function getSupportedTypes(?string $format): array
{
return [
ToolCallMessage::class => true,
];
}

/**
* @param ToolCallMessage $data
*
* @return array{
* role: 'user',
* content: list<array{
* type: 'tool_result',
* tool_use_id: string,
* content: string,
* }>
* }
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
return [
'role' => 'user',
'content' => [
[
'type' => 'tool_result',
'tool_use_id' => $data->toolCall->id,
'content' => $data->content,
],
],
];
}
}
79 changes: 4 additions & 75 deletions src/Bridge/Anthropic/ModelHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,6 @@

use PhpLlm\LlmChain\Chain\Toolbox\Metadata;
use PhpLlm\LlmChain\Exception\RuntimeException;
use PhpLlm\LlmChain\Model\Message\AssistantMessage;
use PhpLlm\LlmChain\Model\Message\Content\Content;
use PhpLlm\LlmChain\Model\Message\Content\Image;
use PhpLlm\LlmChain\Model\Message\MessageBagInterface;
use PhpLlm\LlmChain\Model\Message\MessageInterface;
use PhpLlm\LlmChain\Model\Message\ToolCallMessage;
use PhpLlm\LlmChain\Model\Message\UserMessage;
use PhpLlm\LlmChain\Model\Model;
use PhpLlm\LlmChain\Model\Response\ResponseInterface as LlmResponse;
use PhpLlm\LlmChain\Model\Response\StreamResponse;
Expand All @@ -26,9 +19,6 @@
use Symfony\Component\HttpClient\Exception\JsonException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Webmozart\Assert\Assert;

use function Symfony\Component\String\u;

final readonly class ModelHandler implements ModelClient, ResponseConverter
{
Expand All @@ -42,15 +32,13 @@ public function __construct(
$this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);
}

public function supports(Model $model, array|string|object $input): bool
public function supports(Model $model): bool
{
return $model instanceof Claude && $input instanceof MessageBagInterface;
return $model instanceof Claude;
}

public function request(Model $model, object|array|string $input, array $options = []): ResponseInterface
public function request(Model $model, array|string $payload, array $options = []): ResponseInterface
{
Assert::isInstanceOf($input, MessageBagInterface::class);

if (isset($options['tools'])) {
$tools = $options['tools'];
$options['tools'] = [];
Expand All @@ -66,71 +54,12 @@ public function request(Model $model, object|array|string $input, array $options
$options['tool_choice'] = ['type' => 'auto'];
}

$body = [
'model' => $model->getName(),
'messages' => $input->withoutSystemMessage()->jsonSerialize(),
];

$body['messages'] = array_map(static function (MessageInterface $message) {
if ($message instanceof ToolCallMessage) {
return [
'role' => 'user',
'content' => [
[
'type' => 'tool_result',
'tool_use_id' => $message->toolCall->id,
'content' => $message->content,
],
],
];
}
if ($message instanceof AssistantMessage && $message->hasToolCalls()) {
return [
'role' => 'assistant',
'content' => array_map(static function (ToolCall $toolCall) {
return [
'type' => 'tool_use',
'id' => $toolCall->id,
'name' => $toolCall->name,
'input' => empty($toolCall->arguments) ? new \stdClass() : $toolCall->arguments,
];
}, $message->toolCalls),
];
}
if ($message instanceof UserMessage && $message->hasImageContent()) {
// make sure images are encoded for Bedrock invocation
return [
'role' => 'user',
'content' => array_map(static function (Content $content) {
if ($content instanceof Image) {
return [
'type' => 'image',
'source' => [
'type' => 'base64',
'media_type' => u($content->getFormat())->replace('jpg', 'jpeg')->toString(),
'data' => $content->asBase64(),
],
];
}

return $content;
}, $message->content),
];
}

return $message;
}, $body['messages']);

if ($system = $input->getSystemMessage()) {
$body['system'] = $system->content;
}

return $this->httpClient->request('POST', 'https://api.anthropic.com/v1/messages', [
'headers' => [
'x-api-key' => $this->apiKey,
'anthropic-version' => $this->version,
],
'json' => array_merge($options, $body),
'json' => array_merge($options, $payload),
]);
}

Expand Down
10 changes: 9 additions & 1 deletion src/Bridge/Anthropic/PlatformFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@

namespace PhpLlm\LlmChain\Bridge\Anthropic;

use PhpLlm\LlmChain\Bridge\Anthropic\Contract\AssistantMessageNormalizer;
use PhpLlm\LlmChain\Bridge\Anthropic\Contract\MessageBagNormalizer;
use PhpLlm\LlmChain\Bridge\Anthropic\Contract\ToolCallMessageNormalizer;
use PhpLlm\LlmChain\Platform;
use PhpLlm\LlmChain\Platform\Contract;
use Symfony\Component\HttpClient\EventSourceHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;

Expand All @@ -19,6 +23,10 @@ public static function create(
$httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);
$responseHandler = new ModelHandler($httpClient, $apiKey, $version);

return new Platform([$responseHandler], [$responseHandler]);
return new Platform([$responseHandler], [$responseHandler], Contract::create(
new AssistantMessageNormalizer(),
new MessageBagNormalizer(),
new ToolCallMessageNormalizer())
);
}
}
Loading
Loading