Search by

adachsoft / model-usage-ledger

Arkadiusz Adach

Append-only ledger of AI model requests (tokens, cost, correlation) with summaries grouped by correlation keys

Package info

gitlab.com/a.adach/model-usage-ledger

Issues

pkg:composer/adachsoft/model-usage-ledger

Statistics

Installs: 15

Dependents: 1

Suggesters: 0

Stars: 0

v0.1.0 2026-11-28 17:48 UTC

This package is auto-updated.

Last update: 2026-11-28 16:49:12 UTC


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-bcmath
  • ext-json

Integration

The library is framework-agnostic. Integrate it in your application as follows:

  1. Create a storage implementation (for example JsonlModelUsageLedger or JsonlAgentRunUsageLog) pointing to a writable directory.
  2. Call record() after each model response that contains usage data.
  3. Use find() with a query DTO to read entries for a time range or correlation key.
  4. Pass the result to UsageSummaryService to 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.jsonl using the entry's recordedAt value converted to UTC.
  • Queries with from and/or to read 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 *.jsonl files in the ledger directory. Correlation, provider, and model filters use exact matches; a null filter means no filtering.