PHP code example of tourze / anthropic-token-usage-bundle

1. Go to this page and download the library: Download tourze/anthropic-token-usage-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tourze / anthropic-token-usage-bundle example snippets


return [
    // ...
    Tourze\AnthropicTokenUsageBundle\AnthropicTokenUsageBundle::class => ['all' => true],
];



use Tourze\AnthropicTokenUsageBundle\Service\UsageCollector;
use Tourze\AnthropicTokenUsageBundle\ValueObject\AnthropicUsageData;

class AnthropicService
{
    public function __construct(
        private UsageCollector $usageCollector
    ) {}

    public function processAnthropicRequest(array $response, ?AccessKey $accessKey = null, ?UserInterface $user = null)
    {
        // Create usage data from API response
        $usageData = new AnthropicUsageData(
            inputTokens: $response['usage']['input_tokens'] ?? 0,
            outputTokens: $response['usage']['output_tokens'] ?? 0,
            cacheCreationInputTokens: $response['usage']['cache_creation_input_tokens'] ?? 0,
            cacheReadInputTokens: $response['usage']['cache_read_input_tokens'] ?? 0
        );

        // Collect usage with metadata
        $this->usageCollector->collectUsage(
            $usageData,
            $accessKey,
            $user,
            [
                'model' => $response['model'],
                'request_id' => $response['id'],
                'feature' => 'chat_completion',
                'endpoint' => '/api/v1/messages'
            ]
        );
    }
}



use Tourze\AnthropicTokenUsageBundle\ValueObject\UsageCollectionBatch;
use Tourze\AnthropicTokenUsageBundle\ValueObject\UsageCollectionItem;

$batch = new UsageCollectionBatch([
    new UsageCollectionItem($usageData1, $accessKey1, $user1, $metadata1),
    new UsageCollectionItem($usageData2, $accessKey2, $user2, $metadata2),
    // ... more items
]);

$result = $this->usageCollector->collectBatchUsage($batch);

echo "Processed {$result->totalItems} items\n";
echo "Success: {$result->successCount}, Failures: {$result->failureCount}\n";



use Tourze\AnthropicTokenUsageBundle\Service\UsageQueryService;
use Tourze\AnthropicTokenUsageBundle\ValueObject\UsageQueryFilter;
use Tourze\AnthropicTokenUsageBundle\ValueObject\UsageStatisticsPeriod;

class UsageAnalyticsService
{
    public function __construct(
        private UsageQueryService $queryService
    ) {}

    public function getMonthlyUsageStats(string $accessKeyId): array
    {
        $filter = new UsageQueryFilter(
            dimensionType: UsageStatistics::DIMENSION_ACCESS_KEY,
            dimensionId: $accessKeyId,
            periodType: UsageStatistics::PERIOD_MONTH,
            startDate: new DateTimeImmutable('-6 months'),
            endDate: new DateTimeImmutable()
        );

        return $this->queryService->getUsageStatistics($filter);
    }

    public function getTopConsumers(int $limit = 10): array
    {
        return $this->queryService->getTopConsumers(
            dimensionType: UsageStatistics::DIMENSION_ACCESS_KEY,
            periodType: UsageStatistics::PERIOD_DAY,
            limit: $limit
        );
    }
}



use Tourze\AnthropicTokenUsageBundle\Service\UsageAggregateService;

// Trigger manual aggregation
$this->aggregateService->aggregateAccessKeyUsage(
    new DateTimeImmutable('-1 day'),
    new DateTimeImmutable()
);

$this->aggregateService->aggregateUserUsage(
    new DateTimeImmutable('-1 day'),
    new DateTimeImmutable()
);

$usageData = new AnthropicUsageData(
    inputTokens: 1000,
    outputTokens: 500,
    cacheCreationInputTokens: 100,
    cacheReadInputTokens: 50
);

echo $usageData->getTotalTokens(); // 1650

$result = $queryService->getUsageStatistics($filter);

foreach ($result->items as $stat) {
    echo sprintf(
        "Period: %s to %s\nTokens: %d\nRequests: %d\n",
        $stat->periodStart->format('Y-m-d H:i'),
        $stat->periodEnd->format('Y-m-d H:i'),
        $stat->getTotalTokens(),
        $stat->totalRequests
    );
}

// Log channels
'monolog.channels' => [
    'anthropic_token_usage' => [
        'type' => 'stream',
        'path' => '%kernel.logs_dir%/anthropic_usage.log',
        'level' => 'info'
    ]
]
bash
php vendor/bin/phpunit packages/anthropic-token-usage-bundle/tests