Skip to main content

adk-ledger

Token, cost, tool-call, cache and budget metering for Google ADK agents, exported to OpenTelemetry, JSONL or any sink you plug in.

  • One record per LLM call — whether ADK made the call or your tool called google.genai, openai or anthropic directly — with exact counts from the provider's usage_metadata (prompt, output, cached, cache writes, thoughts, per-modality). Never double counted.
  • Cost on every event, opt-in, from Google's Cloud Billing catalog, the LiteLLM price list or your own table; long-context tiers, cache discounts, per-modality rates.
  • Tool-call metering: latency, failures, retries / loops, argument and result sizes — never content.
  • Budgets: cap tokens, cost or calls per session / user / tenant / invocation, per day or hour; warn, block (refuse the run, model call or tool call) or raise.
  • Cache effectiveness and context-window pressure: hit ratio, "configured but never hits" detection, dollars saved, prompt size vs the model's input window.
  • Configuration-first: adk_ledger.setup().plugins wires everything from adk_ledger.toml / pyproject.toml / YAML and ADK_LEDGER_* env vars; the imperative API is there when you want the objects in code.

Counts and identifiers only: no prompt, response or tool payload is ever stored.

Install

uv add adk-ledger            # or: pip install adk-ledger
uv add "adk-ledger[otel]"    # + OpenTelemetry SDK, for local exporters

Requires Python ≥ 3.13 (the code uses PEP 695 generics, StrEnum and datetime.UTC; older interpreters are deliberately not supported in this release) and google-adk ≥ 2.12 (the version the test suite runs against; the plugin error hooks, App object and branch-aware callback context it relies on are 2.x APIs). google-genai and opentelemetry-api come with it; openai / anthropic are only needed if you meter those SDKs.

Quick start — see your first event in 60 seconds

1. Wire it in. One line of Python; the plugins go on the App, not on individual agents.

from google.adk.agents import LlmAgent
from google.adk.apps import App
import adk_ledger

wiring = adk_ledger.setup(sinks=["memory"])  # keep events in process, for now
root_agent = LlmAgent(name="helper", model="gemini-3.8-flash", instruction="Be brief.")
app = App(name="my_app", root_agent=root_agent, plugins=wiring.plugins)

2. Run one turn as you normally would — Runner, adk run, adk web, anything.

3. Look. The memory sink is the first (here, only) entry of wiring.sinks:

mem = wiring.sinks[0]
mem.total()  # TokenUsage(prompt=212, candidates=38, thoughts=17, total=267, ...)
mem.totals_by_agent()  # {"helper": TokenUsage(...)}
mem.events[
    -1
].as_dict()  # {"event": "llm_call", "source": "adk", "model": "gemini-3.8-flash", "latency_ms": 731.2, "usage": {...}, ...}

memory is for exactly this — seeing output, tests, notebooks. It is per process and in memory only: gone on restart, and with several workers (uvicorn --workers N) each sees just its own events, so for anything you act on use a real sink: jsonl / otel below, or a CallbackSink.

Prefer a file? ADK_LEDGER_SINKS=jsonl:./ledger.jsonl (no code change, setup() reads it) and tail -f ledger.jsonl — one JSON line per model call, shown in full in the feature guide. Both work with no config file and no credentials beyond the model's own.

Or, in code — the same wiring without setup(), for when you want to construct the objects yourself
from google.adk.agents import LlmAgent
from google.adk.apps import App
from adk_ledger import InMemorySink, TokenMeterPlugin, ToolMeterPlugin, configure

mem = InMemorySink()
configure(
    sinks=[mem], instrument_genai=True
)  # once, at start-up; instrument_genai also meters direct google.genai calls

root_agent = LlmAgent(name="helper", model="gemini-3.8-flash", instruction="Be brief.")
app = App(name="my_app", root_agent=root_agent, plugins=[TokenMeterPlugin(), ToolMeterPlugin()])

setup() and configure() are the same machinery: every config key is an argument of configure() or of a plugin constructor. The feature guide uses the imperative form because it names the objects; each heading's configuration equivalent is in docs/configuration.md.

Nothing shows up? setup() with no file, no sinks= and no ADK_LEDGER_SINKS configures the plugins but no sink — events are produced and dropped. See Troubleshooting.

The production file

setup() reads ./adk_ledger.toml (or adk_ledger.yaml, [tool.adk_ledger] in pyproject.toml, or the file named by ADK_LEDGER_CONFIG), applies ADK_LEDGER_* environment variables on top, calls configure() and returns the plugins. A typical production file — it needs an OpenTelemetry exporter installed before setup() and Google credentials for the price catalog; on a laptop start from sinks = ["memory"] / pricing = "litellm" instead:

# adk_ledger.toml
default_tags = { env = "prod", service = "my_app" }
instrument = ["genai"]                       # explicit google.genai calls are metered too
pricing = "cloud_billing"                    # or "litellm", or a composed table — see docs/configuration.md
context_limits = { source = "genai", prefetch = true }

[[sinks]]
type = "otel"                                # adk_ledger.llm.* / adk_ledger.tool.* metrics

[[sinks]]
type = "jsonl"
path = "/var/log/my_app/adk_ledger.jsonl"

[budgets]
default_action = "block"

[[budgets.items]]
name = "session-tokens"
limit = 200000                               # total_tokens per session (defaults)

[[budgets.items]]
name = "tenant-daily-spend"
metric = "cost"
limit = 50.00
scope = "tag:tenant"
window = "1d"
action = "warn"

Prefer to keep it in pyproject.toml? Put the same keys under [tool.adk_ledger] ([[tool.adk_ledger.sinks]], [[tool.adk_ledger.budgets.items]], …) and run from the project root; setup() finds it — see configuration.md → In pyproject.toml and examples/pyproject_config/.

Every key maps 1:1 onto an argument of the imperative API (docs/api.md); the full schema and environment-variable table are in docs/configuration.md, and examples/zero_code.py is the runnable version.

Documentation

docs/features.md feature guide: each feature in depth, in code — attribution of SDK calls, cost, explicit calls, tool metering, budgets (client hook, counter stores, notifying the user), cache & context-window metrics, tags, sinks, the JSONL recipe, OpenTelemetry, extension points
docs/configuration.md every knob: adk_ledger.toml / YAML / pyproject.toml schema, each key's type, default and accepted values, ADK_LEDGER_* environment variables, resolution order
docs/events.md field reference: every field of LlmCallEvent / ToolCallEvent / BudgetEvent, the enumerated values (source, kind, hook, …), the JSONL shape, the OpenTelemetry instruments and attributes, InMemorySink aggregates
docs/api.md the imperative Python API, parameter by parameter: setup(), configure(), the three plugins, Budget, PriceTable / Price, ContextLimits, sinks, the explicit-call helpers
docs/troubleshooting.md symptom → cause → fix
docs/telemetry.md walkthrough: annotated output of four live runs — what the numbers look like against a real model, and what they revealed
docs/performance.md per-event and per-invocation overhead, measured
examples/README.md one runnable script per feature, plus the concierge agent for adk web
CHANGELOG.md what changed in each release
CONTRIBUTING.md development set-up, test suites, security scanning, releasing

Features

Each feature in depth, with code: docs/features.md. In brief:

feature what you get details
Token metering one LlmCallEvent per model call — ADK-issued or a tool's own google.genai / openai / anthropic call — with exact usage_metadata counts, never double counted; side calls inherit the agent's session; implicit metering can be switched off attribution · on/off · reading counts
Cost attribution opt-in Cost on every priced event from Google's Cloud Billing catalog, the LiteLLM list or your own PriceTable; composable, cached, never guessed cost
Explicit calls @meter_llm_call, track_llm_call(), record_usage() for calls you make yourself explicit
Tool calls ToolCallEvent per tool run: latency, errors, retries / loops (attempt), argument and result sizes — never content tools
Budgets declarative caps on tokens / cost / calls per session, user, tenant, invocation or globally, per day or hour; warn, block or raise at ADK's pre-call hooks; counters in process, session state or Redis; the agent can tell the user budgets · client hook · counters · notify
Cache & context window hit ratio, "configured but never hits", dollars saved; prompt size vs the model's input window cache & context
Tags bind_tags(tenant=…) stamps every event inside the block tags
Sinks & OpenTelemetry InMemorySink, JsonlSink, OpenTelemetrySink (adk_ledger.* metrics with GenAI semantic-convention attributes), CallbackSink; a JSONL recipe for adk web / adk run sinks · JSONL recipe · OpenTelemetry
Extending new sinks, providers (BaseUsageExtractor), pre-call estimators; how double counting is avoided extending · double counting

What gets recorded

Three event types, counts and identifiers only — never prompt, response or tool content:

  • LlmCallEvent — one per model call: source (how it was observed: adk, genai_auto, openai_auto, anthropic_auto, explicit), provider, model, usage (prompt / candidates / cached / cache writes / thoughts / per-modality), cost, cache and context-window fields, latency, error, the ADK context (app_name … invocation_id) and tags.
  • ToolCallEvent — one per tool invocation: name, latency, error, argument / result sizes, attempt (a retry / loop detector), ADK context and tags.
  • BudgetEvent — a warning, exceeded or blocked (with the refusing hook), the budget's numbers, ADK context and tags.

All three serialise with an "event" discriminator and reach every sink. Field-by-field definitions, when each is null, every enumerated value and the JSONL shape: docs/events.md.

Troubleshooting

Symptom → cause → fix, for the usual surprises (no events, nothing in OpenTelemetry, cost is None, budgets that never block, double-counted SDK calls, …): docs/troubleshooting.md.

Examples

examples/all_features.py is the whole library wired up in one file and examples/concierge/ is the same thing as an agent you can chat with in adk web — including a ledger_report tool that answers "what has this chat cost so far, and is the cache working?", and a system instruction sized to clear Gemini's minimum cacheable prefix. examples/ also has quickstart.py and one focused script per feature — cost attribution, tool metering, budgets, cache & context-window metrics, SDK auto-instrumentation

  • explicit API, sinks & tags. Each runs live against Gemini or offline against a scripted model (ADK_LEDGER_EXAMPLE_OFFLINE=1, no keys):
ADK_LEDGER_EXAMPLE_OFFLINE=1 uv run python -m examples.all_features
mise run examples        # all of them, offline
mise run example budgets # one of them (no name lists them; --live for real services)
mise run web             # adk web → "concierge" (live)

API reference

The imperative API — setup(), configure(), TokenMeterPlugin, ToolMeterPlugin, BudgetPlugin / Budget, PriceTable / Price, ContextLimits, the sinks, the explicit-call helpers, and how non-Gemini providers are handled — is documented parameter by parameter in docs/api.md. Its data form (TOML / YAML / env vars) is docs/configuration.md; the two map one-to-one.

Performance

Everything on costs ≈ 40 µs per model call and well under 1 ms per agent invocation (0.03–0.3 % of a real model round-trip). The one hot-path cost to configure deliberately is the lazy context-limit lookup (one Gemini API call per new model id) — prefetch it at start-up in latency-sensitive services. Numbers, method and the full cost table: docs/performance.md; reproduce with mise run bench.

What the telemetry looks like

docs/telemetry.md is the unedited output of examples/all_features.py and of the examples/concierge/ agent against a live Gemini model: the in-memory reports, every JSONL record, and the OpenTelemetry export side by side with ADK's own gen_ai.* metrics — including a context cache that never hits (and why), one that does, and a tool's own google.genai call attributed back to its session.

Contributing

Development set-up, the test suites, security scanning and the release process are in CONTRIBUTING.md. Licensed under Apache-2.0 (LICENSE).

Metadata

Release files for adk-ledger 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for adk-ledger 0.3.0
File Size Uploaded Provenance Actions
adk_ledger-0.3.0.tar.gz 308.2 kB Without provenance Details for adk_ledger-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for adk-ledger 0.3.0
File Interpreter ABI Platform Actions
adk_ledger-0.3.0-py3-none-any.whl Python 3 none any Details for adk_ledger-0.3.0-py3-none-any.whl

Total release size: 444.5 kB

Release files / adk_ledger-0.3.0.tar.gz

Download URL adk_ledger-0.3.0.tar.gz
Size 308.2 kB
Tags Source
SHA-256 checksum
How to use checksums
29f8191db75ed3eaf991ed354582815bc69383dad7c67733ef83725f280953a1
BLAKE2b-256 checksum
How to use checksums
620a9bf62ea7040578c22c72cf88652038e910d18dbbe9fde89a41af17f58b51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / adk_ledger-0.3.0-py3-none-any.whl

Download URL adk_ledger-0.3.0-py3-none-any.whl
Size 136.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb513e37953a4c201153c154b88283f6f75f76c268e66e5e63462f76f4c227e5
BLAKE2b-256 checksum
How to use checksums
4fa0d272405785089d27e5379a3ff961ddff54fadbc3076a001967122b725301
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for adk-ledger 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page