adachsoft / model-usage-ledger
Append-only ledger of AI model requests (tokens, cost, correlation) with summaries grouped by correlation keys
v0.1.0
2026-11-28 17:48 UTC
Requires
- php: ^8.3
- ext-bcmath: *
- ext-json: *
Requires (Dev)
- adachsoft/php-code-style: ^0.8.0
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^12.5
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A pure PHP append-only ledger for model request usage, cost, and correlation metadata. Entries are stored as JSON Lines files partitioned by UTC day, and summaries can be grouped by correlation, provider, or model fields.
Features
- Append-only JSON Lines storage for model usage entries, partitioned by UTC day.
- Agent run usage log for completed agent runs with correlation metadata.
- Exact-match queries by correlation identifiers, provider, model, and time range.
- Summaries grouped by any correlation, provider, or model fields, with token totals and per-currency costs.
- Decimal cost handling with BCMath; costs are never summed across currencies.
- Conversation-level usage aggregation over nested agent conversations.
Installation
Install the package with Composer:
composer require adachsoft/model-usage-ledger
Requirements
- PHP 8.3 or newer
ext-bcmathext-json
Integration
The library is framework-agnostic. Integrate it in your application as follows:
- Create a storage implementation (for example
JsonlModelUsageLedgerorJsonlAgentRunUsageLog) pointing to a writable directory. - Call
record()after each model response that contains usage data. - Use
find()with a query DTO to read entries for a time range or correlation key. - Pass the result to
UsageSummaryServiceto build grouped totals.
See the examples directory for complete usage samples.
Example
use AdachSoft\ModelUsageLedger\Dto\ModelUsageEntryDto;
use AdachSoft\ModelUsageLedger\Dto\ModelUsageQueryDto;
use AdachSoft\ModelUsageLedger\Dto\UsageCorrelationDto;
use AdachSoft\ModelUsageLedger\Storage\JsonlModelUsageLedger;
use AdachSoft\ModelUsageLedger\Summary\UsageSummaryService;
$ledger = new JsonlModelUsageLedger(__DIR__ . '/var/usage-ledger');
$ledger->record(new ModelUsageEntryDto(
id: 'request-123',
recordedAt: new DateTimeImmutable(),
providerId: 'openai',
modelId: 'gpt-4.1',
inputTokens: 120,
outputTokens: 40,
costIsComplete: true,
costAmount: '0.0025000000',
currency: 'USD',
costSource: 'provider_reported',
correlation: new UsageCorrelationDto(
conversationId: 'conversation-42',
agentId: 'assistant',
workflowRootRunId: 'workflow-run-7',
stepId: 'summarize',
),
));
$entries = $ledger->find(new ModelUsageQueryDto(
conversationId: 'conversation-42',
from: new DateTimeImmutable('2026-01-01T00:00:00+00:00'),
to: new DateTimeImmutable('2026-12-31T23:59:59.999999+00:00'),
));
$summary = (new UsageSummaryService())->summarize(
$entries,
['step_id', 'agent_id', 'model_id'],
);
foreach ($summary->rows as $row) {
printf("%s: %d requests\n", $row->group['model_id'], $row->requestCount);
}
printf("Total requests: %d\n", $summary->total->requestCount);
Cost amounts are decimal strings. Summary calculations use BCMath with a scale of 10; costs are kept separate by currency.
Recording and querying notes
- Record an entry only after a model response containing usage has arrived. Attempts that fail or time out without a response are not counted.
- Daily files are named
YYYY-MM-DD.jsonlusing the entry'srecordedAtvalue converted to UTC. - Queries with
fromand/ortoread only daily files that can overlap those date bounds, then apply the inclusive timestamp bounds to each entry. - A query without date bounds scans all
*.jsonlfiles in the ledger directory. Correlation, provider, and model filters use exact matches; anullfilter means no filtering.