AI Coding Agents
Build a SQLite Cost Ledger for Coding Agent Runs
Coding agent cost telemetry starts with a ledger of API requests, including fresh input, cached input, cache writes, output, model, and the task each request served. Use provider-specific adapters to fill those buckets, then query SQLite for cache hit ratio, estimated spend, and spend per accepted task while keeping aggregate telemetry available for diagnosis.
Give the ledger a billing grain
Use one row in turns for each API request with a final usage record. An interaction with a coding agent can require multiple API requests, so attach those requests to the same application task and preserve their order. Distinguish a retry that generated a second billable request from a repeated export of the same completed request. Carry an identifier that stays stable across replay. For example, use the API request_id when Claude Code’s claude_code.api_request event includes it. If a wrapper and a CLI exporter both observed the same call, reconcile them before importing. A duplicate under two identifiers would charge the task twice in the report.
The schema below keeps session order, model, latency, and task_id next to the token buckets. Its input column means ordinary fresh input after normalization. A prefix fingerprint and its byte length are optional. If your application controls request construction, hash the stable prefix it assembled at the intended reuse boundary. Leave the field empty when an exporter cannot provide that information. The hash describes your captured bytes, which may differ from the provider’s cache representation. Keep the snapshot metadata private and leave prompts, file bodies, and tool arguments out of this ledger. Debug a prompt cache miss with a prefix diff
| Source | What enters SQLite | What to establish first |
|---|---|---|
| Anthropic SDK wrapper | One request with fresh, output, read, and write counts | Capture the final usage record and model |
| OpenAI Responses wrapper | One request with total input split into disjoint buckets | Confirm the cache detail fields and write lifetimes |
| Claude Code OpenTelemetry | An API request event with usage and latency | Correlate to the application task and check whether lifetime details are present |
| Codex OpenTelemetry | A separate observation with per-turn token counts | Obtain a correlated turn record before ingesting and use request usage for pricing |
| Task outcome | One explicit acceptance decision | Apply the same verification and acceptance criteria across runs |
Save this block as schema.sql. Use a separate database per evaluation cohort in this reference. The reporting query reads the entire database, so splitting experiments before import gives each comparison a clear numerator and denominator.
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY, accepted INTEGER NOT NULL CHECK (accepted IN (0, 1))
);
CREATE TABLE IF NOT EXISTS prefix_snapshots (
hash TEXT PRIMARY KEY, byte_length INTEGER NOT NULL CHECK (byte_length >= 0)
);
CREATE TABLE IF NOT EXISTS turns (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES sessions(id), seq INTEGER NOT NULL CHECK (seq >= 0),
model TEXT NOT NULL, input INTEGER NOT NULL, output INTEGER NOT NULL,
cache_read INTEGER NOT NULL, cache_write_5m INTEGER NOT NULL, cache_write_1h INTEGER NOT NULL,
cache_write_30m INTEGER NOT NULL, cache_write_12h INTEGER NOT NULL,
unknown_write INTEGER NOT NULL,
latency_ms INTEGER NOT NULL CHECK (latency_ms >= 0),
prefix_hash TEXT REFERENCES prefix_snapshots(hash), task_id TEXT NOT NULL,
UNIQUE (session_id, seq)
);
CREATE TABLE IF NOT EXISTS codex_turns (
id TEXT PRIMARY KEY, session_id TEXT NOT NULL REFERENCES sessions(id),
model TEXT NOT NULL, task_id TEXT NOT NULL,
total INTEGER NOT NULL, input INTEGER NOT NULL, cached_input INTEGER NOT NULL,
output INTEGER NOT NULL, reasoning_output INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS rates (
model TEXT PRIMARY KEY, fresh REAL NOT NULL, output REAL NOT NULL, read REAL NOT NULL,
write_5m REAL NOT NULL, write_1h REAL NOT NULL,
write_30m REAL NOT NULL, write_12h REAL NOT NULL
);
Normalize SDK usage before pricing it
In an Anthropic wrapper, capture input_tokens, output_tokens, cache_read_input_tokens, and cache_creation_input_tokens from the final usage. Anthropic’s input_tokens exclude reads and writes. Split the write total using cache_creation.ephemeral_5m_input_tokens and cache_creation.ephemeral_1h_input_tokens when reported. Add fresh input, reads, and write buckets to get full input. If the breakdown falls short of the aggregate write count, keep those remaining tokens in unknown_write. Their presence should keep the dollar estimate unavailable until you know the rate. Anthropic prompt caching
For OpenAI’s Responses API, read input_tokens_details.cached_tokens and start from total input_tokens. For models that report writes, subtract cache_write_tokens along with cached reads to obtain ordinary input. The documented cache_write_tokens_details splits those writes into ttl_30m_tokens and ttl_12h_tokens on supported Responses models. Keep these tiers separate from Anthropic’s five-minute and one-hour buckets. Import output_tokens once. Taking the final total from the response avoids treating detail counts as extra output. The adapter expects a Responses usage object, with the wrapper’s latency, identifiers, and prefix metadata carried outside it. OpenAI prompt caching
Bring in Claude Code and Codex telemetry
As of November 30, 2026, Anthropic documents CLAUDE_CODE_ENABLE_TELEMETRY=1 for Claude Code’s OpenTelemetry collection. The claude_code.token.usage metric reports type values input, output, cacheRead, and cacheCreation. Use it for aggregate reconciliation. Its cacheCreation count combines both write lifetimes. For the request ledger, use the claude_code.api_request event. Its cache_read_tokens and duration_ms give the read count and request latency. The docs specify cache_creation_5m_tokens and cache_creation_1h_tokens for Claude Code v2.1.300 and later. Both details can be zero when the API response supplied only a positive total. The adapter preserves that uncertainty. Claude Code monitoring
Codex configures OpenTelemetry under [otel]. Its advanced configuration guide lists a turn.token_usage histogram with token_type values total, input, cached_input, output, and reasoning_output. Preserve those labels exactly. A histogram exported over a collection interval may aggregate observations from several turns, so its buckets cannot restore a row per request. The example accepts a Codex observation only after your collector supplies counts tied to one turn, and keeps it in codex_turns for diagnostics. Codex also documents token counts in codex.sse_event on response.completed. For billing, reconcile request-level usage with the relevant provider schema and send it through the appropriate wrapper adapter. This also avoids adding reasoning output twice or pricing a whole agent turn as one API request. Codex advanced configuration
Save the next block as normalize.py. The usage object for Claude Code is the selected event attributes, and the ledger envelope carries duration_ms as its local latency_ms. The sample envelope is intentionally small. Flatten your exporter’s batch, attach your application task and request IDs, and convert the count attributes to integers before handing them to the importer. The importer consumes JSON lines in its own format.
def count(value):
if type(value) is not int or value < 0:
raise ValueError("expected a nonnegative integer")
return value
def split_writes(total, first, second):
total, first, second = map(count, (total, first, second))
unknown = total - first - second
if unknown < 0:
raise ValueError("write details exceed the reported total")
return first, second, unknown
def normalize(source, usage):
w5 = w1h = w30 = w12 = unknown = 0
if source == "anthropic":
fresh, out = usage["input_tokens"], usage["output_tokens"]
read = usage.get("cache_read_input_tokens", 0)
details = usage.get("cache_creation") or {}
w5, w1h, unknown = split_writes(
usage.get("cache_creation_input_tokens", 0),
details.get("ephemeral_5m_input_tokens", 0),
details.get("ephemeral_1h_input_tokens", 0),
)
elif source == "claude_code":
fresh, out = usage["input_tokens"], usage["output_tokens"]
read = usage["cache_read_tokens"]
w5, w1h, unknown = split_writes(
usage["cache_creation_tokens"], usage.get("cache_creation_5m_tokens", 0),
usage.get("cache_creation_1h_tokens", 0),
)
elif source == "openai":
details = usage["input_tokens_details"]
read, out = details["cached_tokens"], usage["output_tokens"]
writes = details.get("cache_write_tokens", 0)
tiers = details.get("cache_write_tokens_details") or {}
w30, w12, unknown = split_writes(
writes, tiers.get("ttl_30m_tokens", 0), tiers.get("ttl_12h_tokens", 0),
)
fresh = count(usage["input_tokens"]) - count(read) - writes
else:
raise ValueError(f"unknown source: {source}")
return tuple(map(count, (fresh, out, read, w5, w1h, w30, w12, unknown)))
Define each metric before you query it
| Metric | Definition used by this ledger |
|---|---|
| Cache hit ratio | Sum of cache-read tokens divided by sum of full input tokens, including both fresh and written tokens |
| Effective input multiplier | Observed input cost estimated from billed buckets divided by what the same input token counts would cost at each row’s ordinary input rate |
| Cache-bust cost | Excess observed input cost over a defined warm baseline, summed for qualifying drops |
| Cost per accepted task | Total estimated cohort spend divided by accepted tasks, including spend on attempts that failed or were abandoned |
The effective input multiplier is this guide’s definition. It compares dollar-weighted inputs even when the cohort uses models with different rates. A value above one can occur when paid writes outweigh discounts on cache reads. The cache hit ratio weights requests by input size, so a long recycled prefix can dominate the result. Read the two metrics together. For a smaller experiment that aims only to measure reuse, inspect cold requests and warm continuations by turn as well. Measure prompt cache hit rate
The cache-bust rule is a diagnostic chosen for this guide. It flags a request with at most 5% cached input immediately after a consecutive request in the same session and model with at least 50% cached input. For the flagged row, assume the previous read count would have stayed warm, capped at current input size. Price those assumed hits at the current read rate and the remainder at the current ordinary input rate. Subtract that counterfactual from the actual input estimate and floor the result at zero. The difference can reflect a TTL lapse, a changed prefix, or a change in request shape. Inspect those cases before attributing the estimate to a regression. Debug a prompt cache miss with a prefix diff
Cost per accepted task is ByteCosts’ definition for this comparison, with acceptance measured by a human decision or a verification rule chosen before the run. Vendor usage fields describe tokens or requests. The acceptance label comes from your workflow. Retain the costs of rejected or abandoned attempts in the numerator so the number reflects what you spent to deliver the accepted work. If there are no accepted tasks, the query returns an unavailable per-task result. Separate paid API use from subscription usage when comparing dollars. Compare models by accepted-task cost
Load rates, import a fixture, and read the report
Save the query as report.sql. It makes the price of unknown write tiers unavailable and counts those events so you can repair the data. Use one rates snapshot for a run. Start a new database to compare a different snapshot. The price estimate multiplies each token bucket by its rate per million, sums the bucket charges, and divides by 1,000,000. This estimates model token charges for the cohort at the included rates. Apply any other billing charges or discounts in a separate reconciliation against your invoice.
WITH billed AS (
SELECT t.*,
input + cache_read + cache_write_5m + cache_write_1h
+ cache_write_30m + cache_write_12h + unknown_write AS full_input,
r.fresh AS fresh_rate, r.read AS read_rate, r.output AS output_rate,
CASE WHEN unknown_write = 0
AND (cache_write_5m = 0 OR r.write_5m > 0)
AND (cache_write_1h = 0 OR r.write_1h > 0)
AND (cache_write_30m = 0 OR r.write_30m > 0)
AND (cache_write_12h = 0 OR r.write_12h > 0)
THEN (input * r.fresh + cache_read * r.read + cache_write_5m * r.write_5m
+ cache_write_1h * r.write_1h + cache_write_30m * r.write_30m
+ cache_write_12h * r.write_12h) / 1000000.0 END AS input_usd
FROM turns AS t LEFT JOIN rates AS r USING (model)
), history AS (
SELECT *, lag(seq) OVER w AS previous_seq, lag(model) OVER w AS previous_model,
lag(cache_read) OVER w AS previous_reads,
lag(1.0 * cache_read / nullif(full_input, 0)) OVER w AS previous_ratio
FROM billed WINDOW w AS (PARTITION BY session_id ORDER BY seq)
), classified AS (
SELECT *, CASE WHEN previous_seq = seq - 1 AND previous_model = model
AND previous_ratio >= 0.50 AND 1.0 * cache_read / nullif(full_input, 0) <= 0.05
THEN 1 ELSE 0 END AS bust,
min(previous_reads, full_input) AS assumed_reused
FROM history
), costs AS (
SELECT *, input_usd + output * output_rate / 1000000.0 AS total_usd,
CASE WHEN bust = 1 THEN max(0, input_usd -
(assumed_reused * read_rate + (full_input - assumed_reused) * fresh_rate)
/ 1000000.0) END AS bust_usd
FROM classified
)
SELECT count(*) AS turns,
1.0 * sum(cache_read) / nullif(sum(full_input), 0) AS hit_ratio,
CASE WHEN count(input_usd) = count(*) THEN sum(input_usd)
/ nullif(sum(full_input * fresh_rate) / 1000000.0, 0) END AS input_multiplier,
count(*) - count(total_usd) AS unpriced,
CASE WHEN count(total_usd) = count(*) THEN coalesce(sum(total_usd), 0) END AS spend_usd,
coalesce(sum(bust), 0) AS busts,
coalesce(sum(bust), 0) - count(bust_usd) AS unpriced_busts,
CASE WHEN coalesce(sum(bust), 0) = count(bust_usd)
THEN coalesce(sum(bust_usd), 0) END AS cache_bust_usd,
(SELECT count(*) FROM tasks WHERE accepted = 1) AS accepted_tasks,
CASE WHEN count(total_usd) = count(*) THEN coalesce(sum(total_usd), 0)
/ nullif((SELECT count(*) FROM tasks WHERE accepted = 1), 0)
END AS usd_per_accepted_task,
(SELECT count(*) FROM codex_turns) AS codex_observations
FROM costs;
Save the next block as ledger.py and its rate data as rates.csv. The rate snapshot is as of November 30, 2026. The Sonnet 5.5 one-hour write rate is derived as twice the $2 ordinary input rate. The GPT-6.2 Sol 12-hour rate is derived at 2.5 times its $2 ordinary input rate for the documented Responses cache-write lifetime. A zero write rate in the file denotes an inapplicable tier for that model. The query treats a positive count in that tier as an unpriced request. Anthropic pricing, OpenAI USD usage-based pricing, OpenAI cache write pricing, Current provider rates
import argparse
import csv
import json
from pathlib import Path
import re
import sqlite3
from normalize import count, normalize
HERE = Path(__file__).resolve().parent
CODEX_TYPES = ("total", "input", "cached_input", "output", "reasoning_output")
def setup(db):
db.row_factory = sqlite3.Row
db.executescript((HERE / "schema.sql").read_text())
with db, (HERE / "rates.csv").open(newline="") as file:
rows = csv.reader(file)
next(rows)
db.executemany("INSERT INTO rates VALUES (?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING",
rows)
def insert_once(db, table, key, values):
# Table and column names come only from the call sites below.
placeholders = ",".join("?" for _ in values)
db.execute(f"INSERT INTO {table} VALUES ({placeholders}) ON CONFLICT({key}) DO NOTHING",
values)
existing = db.execute(f"SELECT * FROM {table} WHERE {key} = ?", (values[0],)).fetchone()
if tuple(existing) != values:
raise ValueError(f"conflicting replay in {table}: {values[0]}")
def ingest(db, lines):
with db:
for line in lines:
row = json.loads(line)
source = row["source"]
if source == "task":
accepted = row["accepted"]
if type(accepted) is not bool:
raise ValueError("task acceptance must be true or false")
insert_once(db, "tasks", "id", (row["id"], int(accepted)))
continue
session = row["session_id"]
insert_once(db, "sessions", "id", (session,))
if source == "codex":
fields = (row["id"], session, row["model"], row["task_id"])
observations = tuple(count(row["usage"][kind]) for kind in CODEX_TYPES)
insert_once(db, "codex_turns", "id", fields + observations)
continue
prefix = row.get("prefix_hash")
if prefix is not None:
if not re.fullmatch(r"[0-9a-f]{64}", prefix):
raise ValueError("prefix_hash must be a lowercase SHA-256 hex digest")
insert_once(db, "prefix_snapshots", "hash", (prefix, count(row["prefix_bytes"])))
fields = (row["id"], session, count(row["seq"]), row["model"])
usage = normalize(source, row["usage"])
insert_once(db, "turns", "id",
fields + usage + (count(row["latency_ms"]), prefix, row["task_id"]))
def report(db):
return dict(db.execute((HERE / "report.sql").read_text()).fetchone())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("jsonl", type=Path)
parser.add_argument("--db", default=":memory:")
args = parser.parse_args()
db = sqlite3.connect(args.db)
try:
with db, args.jsonl.open() as lines:
setup(db)
ingest(db, lines)
for label, value in report(db).items():
print(f"{label:24} {value:.6f}" if isinstance(value, float)
else f"{label:24} {value if value is not None else 'unavailable'}")
finally:
db.close()
model,fresh,output,read,write_5m,write_1h,write_30m,write_12h
claude-sonnet-5-5,2,10,0.10,2.50,4,0,0
gpt-6.2-sol,2,10,0.10,0,0,2.50,5
Save the JSON lines below as sample.jsonl alongside ledger.py. Its counts and latencies are synthetic assumptions. Running python3 -B ledger.py sample.jsonl printed four priced requests, one Codex diagnostic observation, and one accepted task. It reported a hit ratio of 0.321839 and an effective input multiplier of 1.136782. The $0.105900 total spend estimate is also the estimated cost per accepted task because only one task passed. The abandoned attempt contributes to the spend numerator. To keep the data beyond the run, pass --db with a new database path.
{"source":"anthropic","id":"a1","session_id":"alpha","seq":1,"task_id":"fix","model":"claude-sonnet-5-5","latency_ms":850,"usage":{"input_tokens":500,"output_tokens":200,"cache_creation_input_tokens":10000,"cache_creation":{"ephemeral_5m_input_tokens":10000,"ephemeral_1h_input_tokens":0}}}
{"source":"anthropic","id":"a2","session_id":"alpha","seq":2,"task_id":"fix","model":"claude-sonnet-5-5","latency_ms":700,"usage":{"input_tokens":500,"output_tokens":200,"cache_read_input_tokens":10000}}
{"source":"claude_code","id":"a3","session_id":"alpha","seq":3,"task_id":"fix","model":"claude-sonnet-5-5","latency_ms":900,"usage":{"input_tokens":500,"output_tokens":200,"cache_read_tokens":0,"cache_creation_tokens":10000,"cache_creation_5m_tokens":0,"cache_creation_1h_tokens":10000}}
{"source":"openai","id":"o1","session_id":"beta","seq":1,"task_id":"abandoned","model":"gpt-6.2-sol","latency_ms":600,"usage":{"input_tokens":12000,"output_tokens":100,"input_tokens_details":{"cached_tokens":4000,"cache_write_tokens":7000,"cache_write_tokens_details":{"ttl_30m_tokens":3000,"ttl_12h_tokens":4000}}}}
{"source":"codex","id":"c1","session_id":"gamma","task_id":"diagnostic","model":"gpt-6.2-sol","usage":{"total":12100,"input":12000,"cached_input":4000,"output":100,"reasoning_output":20}}
{"source":"task","id":"fix","accepted":true}
{"source":"task","id":"abandoned","accepted":false}
The third request had an assumed 10,000-token one-hour write and 500 fresh tokens. Its input cost estimate is (10,000 × $4 + 500 × $2) ÷ 1,000,000 = $0.041. The previous request read 10,000 tokens from cache. Holding that much reuse constant gives (10,000 × $0.10 + 500 × $2) ÷ 1,000,000 = $0.002 for the warm input estimate. Their $0.039 difference matches the cache-bust line in the report. Write a test that imports the fixture twice and checks that the request count and spend stay the same. In a fresh in-memory database, omit cache_creation_1h_tokens from the third request and check that the report flags the write as unpriced.
Choose a change from the ledger
Start with one workflow that repeats often enough to compare similar tasks. Look at the first request after each flagged drop and check the prefix fingerprint, request order, and model. If the flag comes from an expected cold start, preserve that cold start in both sides of the experiment. If it tracks an unexpected change in the prefix, fix that change and replay the same task mix. Once the ledger reconciles with your usage records, try routing a subset of comparable tasks by effort and compare latency and cost per accepted task under the same acceptance checks. Debug a prompt cache miss with a prefix diff, Coding agent effort routing
Sources
- Prompt caching (Anthropic, accessed 2026-11-30)
- Pricing (Anthropic, accessed 2026-11-30)
- Monitor Claude Code usage (Anthropic, accessed 2026-11-30)
- Advanced configuration (OpenAI, accessed 2026-11-30)
- Prompt caching (OpenAI, accessed 2026-11-30)
- Codex pricing (OpenAI, accessed 2026-11-30)
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
Build a SQLite Cost Ledger for Coding Agent Runs. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/agent-cost-telemetry-sqlite/