agentcost
One-line cost tracking for AI agents.
agentcost is a local-first Python library for answering a simple question:
Which agent is spending my money?
It tracks token usage and estimated cost per agent across raw provider SDK calls and supported agent frameworks, stores the results in local SQLite, and prints a terminal report with no proxy, hosted dashboard, or sign-up flow.
Why
Provider billing dashboards give you one number for the whole project. That is not enough when a multi-agent workflow starts getting expensive.
agentcost is built for the stage before full observability tooling:
- Add one decorator to an agent function
- Patch the provider SDK or use a framework-native hook
- Run the workflow
- See per-agent cost, token usage, and call count
Design principles
- Integration-first, patching-second. Framework hooks are the preferred interception path. SDK patching is the fallback for raw API usage.
- One core runtime dependency.
rich is required for terminal output. Everything else is optional.
- Local-only data. History is stored in SQLite on disk. No telemetry, no hosted backend, no phone-home behavior.
- Zero config by default, full control when needed. Sessions, budgets, pricing refresh, export, and CLI support are all available when you need them.
Features
- Per-agent attribution with
@track_cost(agent="...")
- Sync and async tracking
- Session-level budget enforcement
- OpenAI and Anthropic SDK patchers
- LangChain / LangGraph callback integration
- CrewAI hook registration
- OpenAI Agents SDK hooks
- Rich terminal session reports
report(format="json") for programmatic use
- Historical summaries by agent or model
- CSV export
- Optional pandas DataFrame export
- Local pricing cache with runtime overrides
Installation
Core library:
CLI support:
pip install "agentcost[cli]"
History export with pandas:
pip install "agentcost[history]"
Everything:
pip install "agentcost[cli,history]"
Quick start
from openai import OpenAI
from agentcost import Session, patch_openai, report, track_cost
patch_openai()
client = OpenAI()
@track_cost(agent="researcher")
def run_research() -> None:
client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Summarize the latest findings."},
],
)
with Session(session_id="demo-session"):
run_research()
report()
Typical output:
agentcost · session demo-session
╭────────────┬───────┬────────┬─────────┬─────────╮
│ Agent │ Calls │ Tokens │ Cost │ % Total │
├────────────┼───────┼────────┼─────────┼─────────┤
│ researcher │ 1 │ 1,024 │ $0.0036 │ 100.0% │
├────────────┼───────┼────────┼─────────┼─────────┤
│ Total │ 1 │ 1,024 │ $0.0036 │ 100.0% │
╰────────────┴───────┴────────┴─────────┴─────────╯
Programmatic JSON report:
from agentcost import report
payload = report(format="json")
print(payload["totals"]["cost_usd"])
How it works
User code
│
├─ @track_cost(agent="X")
│ │
│ ├─ Framework hook
│ │ └─ record_call(...)
│ │
│ └─ SDK patcher fallback
│ └─ record_call(...)
│
├─ Session budget check
│
├─ SQLite persistence
│
└─ report() / history.summary()
Agent attribution uses contextvars.ContextVar, so sync code, threads, and async tasks can carry the active agent name without global-state collisions. Session budget enforcement uses locks to avoid concurrency races.
Core API
from agentcost import (
Session,
configure,
history,
log_call,
report,
track_cost,
track_scope,
)
@track_cost
Attach an agent name to a sync or async function:
from agentcost import track_cost
@track_cost(agent="planner")
def plan() -> None:
...
track_scope
Use a manual scope when a decorator is not the right fit:
from agentcost import track_scope
with track_scope(agent="reviewer"):
...
Session
Track a single run and optionally enforce a budget:
from agentcost import Session
with Session(session_id="run-001", budget=2.00, on_exceed="raise"):
...
Budget modes:
raise: raise BudgetExceeded when the budget is crossed
warn: emit a warning and continue
stop: stop accepting additional records after the budget is crossed
configure
Runtime configuration:
from agentcost import configure
configure(
pricing_refresh="weekly", # daily | weekly | never
storage_path="~/.agentcost/history.db",
)
Provider patchers
Patchers are the fallback path for raw provider SDK use.
OpenAI
from agentcost import patch_openai
patch_openai()
Covers:
openai.chat.completions.create
AsyncOpenAI().chat.completions.create
Anthropic
from agentcost import patch_anthropic
patch_anthropic()
Covers:
anthropic.Anthropic().messages.create
anthropic.AsyncAnthropic().messages.create
Patchers are idempotent, so calling them multiple times does not double-wrap the SDK.
Framework integrations
Framework-native hooks are the preferred path because they keep cost attribution closer to the agent runtime and avoid relying only on provider monkey-patching.
LangChain / LangGraph
from agentcost import AgentCostHandler
handler = AgentCostHandler()
chain.invoke(
{"topic": "agent cost analysis"},
config={"callbacks": [handler]},
)
CrewAI
from agentcost import register_crewai_hooks
registration = register_crewai_hooks()
register_crewai_hooks() returns a registration handle so hooks can be unregistered if needed.
OpenAI Agents SDK
from agentcost import AgentCostHooks
hooks = AgentCostHooks()
# await Runner.run(agent, input, hooks=hooks)
Reporting and history
Session reports
from agentcost import report
report() # Rich table
report(format="json") # dict payload
report(session_id="run-1") # specific session
Historical summaries
from agentcost import history
history.summary(days=7, group_by="agent")
history.summary(days=30, group_by="model")
history.summary(days=30, group_by="agent", format="json")
Export
from agentcost import history
history.to_csv("costs.csv")
df = history.to_dataframe()
CLI
Install with:
pip install "agentcost[cli]"
Commands:
agentcost report
agentcost report --format json
agentcost history --days 30
agentcost history --days 30 --group-by model --format json
agentcost export --format csv -o costs.csv
agentcost export --format json -o costs.json
agentcost pricing
agentcost pricing --update
Pricing
agentcost ships with a bundled pricing.json and can refresh pricing from a hosted source into a local cache.
Defaults:
- packaged fallback:
agentcost/pricing.json
- local cache:
~/.agentcost/pricing_cache.json
- refresh policy:
weekly
Override a model price at runtime:
from agentcost import set_pricing
set_pricing("custom-model", 1.25, 5.00)
If a model is unknown, agentcost still records the token counts and stores the call with cost_usd=0.0.
Storage and privacy
All persisted history is stored locally in SQLite.
Defaults:
- history database:
~/.agentcost/history.db
- pricing cache:
~/.agentcost/pricing_cache.json
The library does not send usage data to a hosted backend.
What agentcost is and is not
agentcost is:
- a lightweight local library
- focused on cost attribution
- optimized for fast adoption in Python agent workflows
agentcost is not:
- a hosted tracing platform
- a proxy service
- a team SaaS product
If you need full observability, traces, evals, and hosted collaboration, tools like Langfuse, Helicone, and LangSmith may be a better fit.
Supported Python versions
Development
Run tests:
Lint:
Project docs:
Status
Current public surface:
- version:
0.1.0
- provider patchers: OpenAI, Anthropic
- framework integrations: LangChain / LangGraph, CrewAI, OpenAI Agents SDK
- output surfaces: Rich reports, JSON reports, history summaries, CSV export, CLI