-
-
Notifications
You must be signed in to change notification settings - Fork 52
[Platform] Standardise token usage #311
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
Open
junaidbinfarooq
wants to merge
1
commit into
symfony:main
Choose a base branch
from
junaidbinfarooq:feat/standardize-token-usage
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+502
−196
Open
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,48 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* 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\Mistral\Mistral; | ||
use Symfony\AI\Platform\Bridge\Mistral\PlatformFactory; | ||
use Symfony\AI\Platform\Bridge\Mistral\TokenUsageExtractor; | ||
use Symfony\AI\Platform\Message\Message; | ||
use Symfony\AI\Platform\Message\MessageBag; | ||
use Symfony\AI\Platform\Result\TokenUsage\TokenUsageOutputProcessor; | ||
|
||
require_once dirname(__DIR__).'/bootstrap.php'; | ||
|
||
$platform = PlatformFactory::create(env('MISTRAL_API_KEY'), http_client()); | ||
$model = new Mistral(Mistral::MISTRAL_SMALL, [ | ||
'temperature' => 0.5, // default options for the model | ||
]); | ||
$agent = new Agent( | ||
$platform, | ||
$model, | ||
outputProcessors: [new TokenUsageOutputProcessor(new TokenUsageExtractor())], | ||
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, [ | ||
'max_tokens' => 500, | ||
]); | ||
|
||
if (null === $tokenUsage = $result->getTokenUsage()) { | ||
throw new RuntimeException('Token usage is not available.'); | ||
} | ||
|
||
echo 'Utilized Tokens: '.$tokenUsage->total.\PHP_EOL; | ||
echo '-- Prompt Tokens: '.$tokenUsage->prompt.\PHP_EOL; | ||
echo '-- Completion Tokens: '.$tokenUsage->completion.\PHP_EOL; |
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
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
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
48 changes: 48 additions & 0 deletions
48
src/ai-bundle/src/DependencyInjection/Compiler/RegisterTokenUsageExtractorPass.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,48 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\AI\AiBundle\DependencyInjection\Compiler; | ||
|
||
use Symfony\AI\Platform\Exception\RuntimeException; | ||
use Symfony\AI\Platform\Result\TokenUsage\Attribute\AsTokenUsageExtractor; | ||
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; | ||
use Symfony\Component\DependencyInjection\ContainerBuilder; | ||
|
||
/** | ||
* @author Junaid Farooq <[email protected]> | ||
*/ | ||
class RegisterTokenUsageExtractorPass implements CompilerPassInterface | ||
{ | ||
public function process(ContainerBuilder $container): void | ||
{ | ||
foreach ($container->findTaggedServiceIds('ai.platform.token_usage_extractor') as $serviceId => $tags) { | ||
$serviceDefinition = $container->getDefinition($serviceId); | ||
$serviceClass = $serviceDefinition->getClass(); | ||
|
||
if (!class_exists($serviceClass)) { | ||
continue; | ||
} | ||
|
||
$reflectionClass = new \ReflectionClass($serviceClass); | ||
$attributes = $reflectionClass->getAttributes(AsTokenUsageExtractor::class); | ||
|
||
if (0 === \count($attributes)) { | ||
throw new RuntimeException(\sprintf('Service "%s" is tagged as "ai.platform.token_usage_extractor" but does not have the "%s" attribute.', $serviceId, AsTokenUsageExtractor::class)); | ||
} | ||
|
||
foreach ($attributes as $attribute) { | ||
$platform = $attribute->newInstance()->platform; | ||
$alias = \sprintf('ai.platform.token_usage_extractor.%s', $platform); | ||
$container->setAlias($alias, $serviceId); | ||
} | ||
} | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
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,60 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\AI\Platform\Bridge\Mistral; | ||
|
||
use Symfony\AI\Agent\Output; | ||
use Symfony\AI\Platform\Result\StreamResult; | ||
use Symfony\AI\Platform\Result\TokenUsage\Attribute\AsTokenUsageExtractor; | ||
use Symfony\AI\Platform\Result\TokenUsage\TokenUsage; | ||
use Symfony\AI\Platform\Result\TokenUsage\TokenUsageExtractorInterface; | ||
use Symfony\Contracts\HttpClient\ResponseInterface; | ||
|
||
/** | ||
* @author Junaid Farooq <[email protected]> | ||
*/ | ||
#[AsTokenUsageExtractor(platform: 'mistral')] | ||
class TokenUsageExtractor implements TokenUsageExtractorInterface | ||
{ | ||
public function extractTokenUsage(Output $output): ?TokenUsage | ||
{ | ||
if ($output->result instanceof StreamResult) { | ||
return null; | ||
} | ||
|
||
$rawResponse = $output->result->getRawResult()?->getObject(); | ||
|
||
if (!$rawResponse instanceof ResponseInterface) { | ||
return null; | ||
} | ||
|
||
$remainingTokensMinute = $rawResponse->getHeaders(false)['x-ratelimit-limit-tokens-minute'][0] ?? null; | ||
$remainingTokensMonth = $rawResponse->getHeaders(false)['x-ratelimit-limit-tokens-month'][0] ?? null; | ||
|
||
$tokenUsage = new TokenUsage( | ||
remainingTokensMinute: null !== $remainingTokensMinute ? (int) $remainingTokensMinute : null, | ||
remainingTokensMonth: null !== $remainingTokensMonth ? (int) $remainingTokensMonth : null, | ||
); | ||
|
||
$data = $rawResponse->toArray(false); | ||
$usage = $data['usage'] ?? null; | ||
|
||
if (null === $usage) { | ||
return $tokenUsage; | ||
} | ||
|
||
$tokenUsage->prompt = $usage['prompt_tokens'] ?? null; | ||
$tokenUsage->completion = $usage['completion_tokens'] ?? null; | ||
$tokenUsage->total = $usage['total_tokens'] ?? null; | ||
|
||
return $tokenUsage; | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can this happen?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, if you mean
null === $tokenUsage
, when token_usage is marked false in the config, as far as I can see.