-
-
Notifications
You must be signed in to change notification settings - Fork 102
[Platform][Anthropic] Add TokenOutputProcessor
#554
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
Merged
welcoMattic
merged 1 commit into
symfony:main
from
nictou-weglot:anthropicOutputProcessor
Sep 12, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
use Symfony\AI\Agent\Agent; | ||
use Symfony\AI\Platform\Bridge\Anthropic\Claude; | ||
use Symfony\AI\Platform\Bridge\Anthropic\PlatformFactory; | ||
use Symfony\AI\Platform\Bridge\Anthropic\TokenOutputProcessor; | ||
use Symfony\AI\Platform\Message\Message; | ||
use Symfony\AI\Platform\Message\MessageBag; | ||
|
||
require_once dirname(__DIR__).'/bootstrap.php'; | ||
|
||
$platform = PlatformFactory::create(env('ANTHROPIC_API_KEY'), http_client()); | ||
$model = new Claude(Claude::SONNET_37); | ||
|
||
$agent = new Agent($platform, $model, outputProcessors: [new TokenOutputProcessor()], logger: logger()); | ||
$messages = new MessageBag( | ||
Message::forSystem('You are a pirate and you write funny.'), | ||
Message::ofUser('What is the Symfony framework?'), | ||
); | ||
$result = $agent->call($messages); | ||
|
||
print_token_usage($result->getMetadata()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
src/platform/src/Bridge/Anthropic/TokenOutputProcessor.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\AI\Platform\Bridge\Anthropic; | ||
|
||
use Symfony\AI\Agent\Output; | ||
use Symfony\AI\Agent\OutputProcessorInterface; | ||
use Symfony\AI\Platform\Metadata\TokenUsage; | ||
use Symfony\AI\Platform\Result\StreamResult; | ||
use Symfony\Contracts\HttpClient\ResponseInterface; | ||
|
||
final class TokenOutputProcessor implements OutputProcessorInterface | ||
{ | ||
public function processOutput(Output $output): void | ||
{ | ||
if ($output->result instanceof StreamResult) { | ||
// Streams have to be handled manually as the tokens are part of the streamed chunks | ||
return; | ||
} | ||
|
||
$rawResponse = $output->result->getRawResult()?->getObject(); | ||
if (!$rawResponse instanceof ResponseInterface) { | ||
return; | ||
} | ||
|
||
$metadata = $output->result->getMetadata(); | ||
|
||
$tokenUsage = new TokenUsage(); | ||
|
||
$content = $rawResponse->toArray(false); | ||
if (!\array_key_exists('usage', $content)) { | ||
$metadata->add('token_usage', $tokenUsage); | ||
|
||
return; | ||
} | ||
|
||
$usage = $content['usage']; | ||
|
||
$tokenUsage->promptTokens = $usage['input_tokens'] ?? null; | ||
$tokenUsage->completionTokens = $usage['output_tokens'] ?? null; | ||
$tokenUsage->toolTokens = $usage['server_tool_use']['web_search_requests'] ?? null; | ||
|
||
$cachedTokens = null; | ||
if (\array_key_exists('cache_creation_input_tokens', $usage) || \array_key_exists('cache_read_input_tokens', $usage)) { | ||
$cachedTokens = ($usage['cache_creation_input_tokens'] ?? 0) + ($usage['cache_read_input_tokens'] ?? 0); | ||
} | ||
$tokenUsage->cachedTokens = $cachedTokens; | ||
|
||
$metadata->add('token_usage', $tokenUsage); | ||
} | ||
} |
163 changes: 163 additions & 0 deletions
163
src/platform/tests/Bridge/Anthropic/TokenOutputProcessorTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Bridge\Anthropic; | ||
|
||
use PHPUnit\Framework\Attributes\CoversClass; | ||
use PHPUnit\Framework\Attributes\Small; | ||
use PHPUnit\Framework\Attributes\UsesClass; | ||
use PHPUnit\Framework\TestCase; | ||
use Symfony\AI\Agent\Output; | ||
use Symfony\AI\Platform\Bridge\Anthropic\TokenOutputProcessor; | ||
use Symfony\AI\Platform\Message\MessageBag; | ||
use Symfony\AI\Platform\Metadata\Metadata; | ||
use Symfony\AI\Platform\Metadata\TokenUsage; | ||
use Symfony\AI\Platform\Model; | ||
use Symfony\AI\Platform\Result\RawHttpResult; | ||
use Symfony\AI\Platform\Result\ResultInterface; | ||
use Symfony\AI\Platform\Result\StreamResult; | ||
use Symfony\AI\Platform\Result\TextResult; | ||
use Symfony\Contracts\HttpClient\ResponseInterface; | ||
|
||
#[CoversClass(TokenOutputProcessor::class)] | ||
#[UsesClass(Output::class)] | ||
#[UsesClass(TextResult::class)] | ||
#[UsesClass(StreamResult::class)] | ||
#[UsesClass(Metadata::class)] | ||
#[UsesClass(TokenUsage::class)] | ||
#[Small] | ||
final class TokenOutputProcessorTest extends TestCase | ||
{ | ||
public function testItHandlesStreamResponsesWithoutProcessing() | ||
{ | ||
$processor = new TokenOutputProcessor(); | ||
$streamResult = new StreamResult((static function () { yield 'test'; })()); | ||
$output = $this->createOutput($streamResult); | ||
|
||
$processor->processOutput($output); | ||
|
||
$metadata = $output->result->getMetadata(); | ||
$this->assertCount(0, $metadata); | ||
} | ||
|
||
public function testItDoesNothingWithoutRawResponse() | ||
{ | ||
$processor = new TokenOutputProcessor(); | ||
$textResult = new TextResult('test'); | ||
$output = $this->createOutput($textResult); | ||
|
||
$processor->processOutput($output); | ||
|
||
$metadata = $output->result->getMetadata(); | ||
$this->assertCount(0, $metadata); | ||
} | ||
|
||
public function testItAddsRemainingTokensToMetadata() | ||
{ | ||
$processor = new TokenOutputProcessor(); | ||
$textResult = new TextResult('test'); | ||
|
||
$textResult->setRawResult($this->createRawResult()); | ||
|
||
$output = $this->createOutput($textResult); | ||
|
||
$processor->processOutput($output); | ||
|
||
$metadata = $output->result->getMetadata(); | ||
$tokenUsage = $metadata->get('token_usage'); | ||
|
||
$this->assertCount(1, $metadata); | ||
$this->assertInstanceOf(TokenUsage::class, $tokenUsage); | ||
$this->assertNull($tokenUsage->remainingTokens); | ||
} | ||
|
||
public function testItAddsUsageTokensToMetadata() | ||
{ | ||
$processor = new TokenOutputProcessor(); | ||
$textResult = new TextResult('test'); | ||
|
||
$rawResult = $this->createRawResult([ | ||
'usage' => [ | ||
'input_tokens' => 10, | ||
'output_tokens' => 20, | ||
'server_tool_use' => [ | ||
'web_search_requests' => 30, | ||
], | ||
'cache_creation_input_tokens' => 40, | ||
'cache_read_input_tokens' => 50, | ||
], | ||
]); | ||
|
||
$textResult->setRawResult($rawResult); | ||
|
||
$output = $this->createOutput($textResult); | ||
|
||
$processor->processOutput($output); | ||
|
||
$metadata = $output->result->getMetadata(); | ||
$tokenUsage = $metadata->get('token_usage'); | ||
|
||
$this->assertInstanceOf(TokenUsage::class, $tokenUsage); | ||
$this->assertSame(10, $tokenUsage->promptTokens); | ||
$this->assertSame(30, $tokenUsage->toolTokens); | ||
$this->assertSame(20, $tokenUsage->completionTokens); | ||
$this->assertNull($tokenUsage->remainingTokens); | ||
$this->assertNull($tokenUsage->thinkingTokens); | ||
$this->assertSame(90, $tokenUsage->cachedTokens); | ||
$this->assertNull($tokenUsage->totalTokens); | ||
} | ||
|
||
public function testItHandlesMissingUsageFields() | ||
{ | ||
$processor = new TokenOutputProcessor(); | ||
$textResult = new TextResult('test'); | ||
|
||
$rawResult = $this->createRawResult([ | ||
'usage' => [ | ||
// Missing some fields | ||
'input_tokens' => 10, | ||
], | ||
]); | ||
|
||
$textResult->setRawResult($rawResult); | ||
|
||
$output = $this->createOutput($textResult); | ||
|
||
$processor->processOutput($output); | ||
|
||
$metadata = $output->result->getMetadata(); | ||
$tokenUsage = $metadata->get('token_usage'); | ||
|
||
$this->assertInstanceOf(TokenUsage::class, $tokenUsage); | ||
$this->assertSame(10, $tokenUsage->promptTokens); | ||
$this->assertNull($tokenUsage->remainingTokens); | ||
$this->assertNull($tokenUsage->completionTokens); | ||
$this->assertNull($tokenUsage->totalTokens); | ||
} | ||
|
||
private function createRawResult(array $data = []): RawHttpResult | ||
{ | ||
$rawResponse = $this->createStub(ResponseInterface::class); | ||
$rawResponse->method('toArray')->willReturn($data); | ||
|
||
return new RawHttpResult($rawResponse); | ||
} | ||
|
||
private function createOutput(ResultInterface $result): Output | ||
{ | ||
return new Output( | ||
$this->createStub(Model::class), | ||
$result, | ||
new MessageBag(), | ||
[], | ||
); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.