Skip to main content
Track cumulative token spend per gateway identity in a restart-safe SQLite ledger — no new dependencies.

Quick Start

1

Ephemeral (in-memory) for tests

Use ":memory:" for a throwaway database that never touches disk.
2

On-disk for production gateways

Pass a file path — ~ is expanded and parent directories are created for you.
3

Attribute a turn to an identity

Call persist from the telemetry path, passing identity, scope, and cost_usd via metadata.
4

Query cumulative spend for a /usage command

Read aggregate spend and token totals for one identity.

How It Works

Each turn’s metrics are persisted keyed by canonical identity + scope, then read back cumulatively for admission or a /usage reply. Lookups stay fast because rows are indexed on (identity, scope, ts) via idx_token_usage_identity_scope_ts.

Imports


API Reference

SqliteTokenUsageSink

Implements the existing TokenUsageSinkProtocol using stdlib sqlite3. Thread-safe and context-manager friendly.

Schema

The idx_token_usage_identity_scope_ts index is why per-identity spend lookups stay fast even as the ledger grows.

SDK Reference

Full auto-generated API surface for the telemetry package.

Configuration Options

Three ways to construct the sink.

Common Patterns

Attribute a turn to a gateway identity

Fall back to agent name

Rolling-window spend for admission

/usage command reply

Accurate retry hints


Best Practices

Pass a full path like ~/.praisonai/usage.db. ~ is expanded and parent directories are created automatically, so the ledger persists across restarts.
The sink is thread-safe (check_same_thread=False plus an internal lock). One instance is fine to share between async event loops and worker threads.
oldest_spend_ts ignores rows with cost_usd == 0, so free events don’t skew the retry hint fed to the spend-budget policy.
This sink uses stdlib sqlite3 — no extra dependency. For Postgres or Redis, implement TokenUsageSinkProtocol as a separate sink instead.

Token Usage Protocol

The TokenUsageSinkProtocol this sink implements

Spend Budget

Cap per-identity spend using this sink’s readings

Token Tracking

Measure token consumption per turn

Cost Tracking

Estimate and report LLM costs