Metadata-Version: 2.5
Name: adk-ledger
Version: 0.3.0
Summary: Token, cost, tool-call, cache and budget metering for Google ADK agents, exported to OpenTelemetry, JSONL or any sink.
Project-URL: Homepage, https://github.com/delta-fde/ravidalal-adk-ledger
Author: Ravi Dalal
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: adk,anthropic,budgets,cost,gemini,google-adk,observability,openai,opentelemetry,tokens
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: <3.15,>=3.13
Requires-Dist: google-adk>=2.12
Requires-Dist: google-genai>=1.0
Requires-Dist: opentelemetry-api>=1.25
Requires-Dist: pydantic>=2.0
Provides-Extra: gcp
Requires-Dist: google-cloud-billing>=1.12; extra == 'gcp'
Provides-Extra: otel
Requires-Dist: opentelemetry-sdk>=1.25; extra == 'otel'
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == 'redis'
Description-Content-Type: text/markdown

# adk-ledger

Token, cost, tool-call, cache and budget metering for [Google ADK](https://adk.dev) 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

```bash
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.

```python
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`:

```python
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](docs/features.md#recipe-log-every-call-of-an-agent-to-a-jsonl-file). Both work with **no config file
and no credentials beyond the model's own**.

<details>
<summary><b>Or, in code</b> — the same wiring without <code>setup()</code>, for when you want to construct the objects yourself</summary>

```python
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](docs/features.md) uses the imperative form
because it names the objects; each heading's configuration equivalent is in
[docs/configuration.md](docs/configuration.md).

</details>

> **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](docs/troubleshooting.md).

### 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:

```toml
# 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`](docs/configuration.md#in-pyprojecttoml) and
[examples/pyproject_config/](examples/pyproject_config).

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

## Documentation

| | |
|---|---|
| [docs/features.md](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](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](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](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](docs/troubleshooting.md) | symptom → cause → fix |
| [docs/telemetry.md](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](docs/performance.md) | per-event and per-invocation overhead, measured |
| [examples/README.md](examples/README.md) | one runnable script per feature, plus the `concierge` agent for `adk web` |
| [CHANGELOG.md](CHANGELOG.md) | what changed in each release |
| [CONTRIBUTING.md](CONTRIBUTING.md) | development set-up, test suites, security scanning, releasing |

## Features

Each feature in depth, with code: [docs/features.md](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](docs/features.md#explicit-sdk-calls-inherit-the-agent-that-made-them) · [on/off](docs/features.md#turning-implicit-adk-issued-call-metering-on-or-off) · [reading counts](docs/features.md#reading-counts-at-runtime) |
| **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](docs/features.md#cost-attribution) |
| **Explicit calls** | `@meter_llm_call`, `track_llm_call()`, `record_usage()` for calls you make yourself | [explicit](docs/features.md#explicit-calls) |
| **Tool calls** | `ToolCallEvent` per tool run: latency, errors, retries / loops (`attempt`), argument and result sizes — never content | [tools](docs/features.md#tool-calls) |
| **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](docs/features.md#budgets) · [client hook](docs/features.md#capturing-budget-events-in-a-client) · [counters](docs/features.md#where-the-counters-live) · [notify](docs/features.md#telling-the-user) |
| **Cache & context window** | hit ratio, "configured but never hits", dollars saved; prompt size vs the model's input window | [cache & context](docs/features.md#cache-effectiveness-and-context-window-pressure) |
| **Tags** | `bind_tags(tenant=…)` stamps every event inside the block | [tags](docs/features.md#tags) |
| **Sinks & OpenTelemetry** | `InMemorySink`, `JsonlSink`, `OpenTelemetrySink` (`adk_ledger.*` metrics with GenAI semantic-convention attributes), `CallbackSink`; a JSONL recipe for `adk web` / `adk run` | [sinks](docs/features.md#sinks) · [JSONL recipe](docs/features.md#recipe-log-every-call-of-an-agent-to-a-jsonl-file) · [OpenTelemetry](docs/features.md#opentelemetry) |
| **Extending** | new sinks, providers (`BaseUsageExtractor`), pre-call estimators; how double counting is avoided | [extending](docs/features.md#extending) · [double counting](docs/features.md#how-double-counting-is-avoided) |

## 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](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](docs/troubleshooting.md).

## Examples

[`examples/all_features.py`](examples/all_features.py) is the whole library wired up in one
file and [`examples/concierge/`](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/`](examples/README.md) also has
[`quickstart.py`](examples/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):

```bash
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](docs/api.md). Its data form (TOML / YAML / env vars) is
[docs/configuration.md](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](docs/performance.md); reproduce with `mise run bench`.

## What the telemetry looks like

[docs/telemetry.md](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](CONTRIBUTING.md). Licensed under Apache-2.0 ([LICENSE](LICENSE)).
