Skip to content
This repository was archived by the owner on Jul 16, 2025. It is now read-only.
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
9 changes: 5 additions & 4 deletions src/Bridge/Anthropic/ModelHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,16 +121,17 @@ public function convert(ResponseInterface $response, array $options = []): LlmRe
throw new RuntimeException('Response does not contain any content');
}

if (!isset($data['content'][0]['text'])) {
throw new RuntimeException('Response content does not contain any text');
}

$toolCalls = [];
foreach ($data['content'] as $content) {
if ('tool_use' === $content['type']) {
$toolCalls[] = new ToolCall($content['id'], $content['name'], $content['input']);
}
}

if (!isset($data['content'][0]['text']) && 0 === count($toolCalls)) {
throw new RuntimeException('Response content does not contain any text nor tool calls.');
}

if (!empty($toolCalls)) {
return new ToolCallResponse(...$toolCalls);
}
Expand Down
39 changes: 39 additions & 0 deletions tests/Bridge/Anthropic/ModelHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace PhpLlm\LlmChain\Tests\Bridge\Anthropic;

use PhpLlm\LlmChain\Bridge\Anthropic\ModelHandler;
use PhpLlm\LlmChain\Model\Response\ToolCallResponse;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;

#[CoversClass(ModelHandler::class)]
final class ModelHandlerTest extends TestCase
{
public function testConvertThrowsExceptionWhenContentIsToolUseAndLacksText(): void
{
$httpClient = new MockHttpClient(new JsonMockResponse([
'content' => [
[
'type' => 'tool_use',
'id' => 'toolu_01UM4PcTjC1UDiorSXVHSVFM',
'name' => 'xxx_tool',
'input' => ['action' => 'get_data'],
],
],
]));
$httpResponse = $httpClient->request('POST', 'https://api.anthropic.com/v1/messages');
$handler = new ModelHandler($httpClient, 'test-api-key');

$response = $handler->convert($httpResponse);
self::assertInstanceOf(ToolCallResponse::class, $response);
self::assertCount(1, $response->getContent());
self::assertSame('toolu_01UM4PcTjC1UDiorSXVHSVFM', $response->getContent()[0]->id);
self::assertSame('xxx_tool', $response->getContent()[0]->name);
self::assertSame(['action' => 'get_data'], $response->getContent()[0]->arguments);
}
}