Overview
pennytrase tracks what each AI agent call costs, whether it worked, and whether the customer is profitable — per customer, per workflow, per call. Three parts:
- SDK (
pip install pennytrase, zero dependencies) — wrap agent calls, fire-and-forget. - Server (FastAPI + SQLite, one file DB) — prices calls server-side, serves metrics.
- Dashboard (one offline HTML file) — spend, margins, per-call drill-down.
Privacy: prompts and responses are never stored — only metadata (model, tokens, latency, cost, status).
Installation
pip install pennytrase
Requires Python ≥ 3.10, no dependencies. Alternative: copy src/pennytrase/__init__.py into your repo as pennytrase.py — it is a single stdlib-only file.
Server (for the dashboard + metrics API):
pip install -r requirements.txt
pip install -e .
uvicorn app.main:app --reload --port 8000
# or: docker compose up --build (persists ./data/pennytrase.db)
Quickstart
from pennytrase import Pennytrase
pt = Pennytrase(base_url="http://localhost:8000")
with pt.task(customer_id="acme", workflow="support_refund") as t:
t.llm(model="gpt-4o-mini", input_tokens=812, output_tokens=140, latency_ms=900)
t.tool(name="stripe_refund", cost_usd=0.002)
t.success(outcome_value=12.0) # or t.fail(); exception → auto-fail
Then tell pennytrase what the customer pays, and watch the margin:
curl -X PUT http://localhost:8000/v1/customers/acme \
-H 'Content-Type: application/json' -d '{"monthly_revenue": 800}'
Not sure it works? Run python examples/demo_seed.py and open the dashboard — Umbrella Corp glows red at the top.
Configuration
Environment variables (server)
| Variable | Default | Meaning |
|---|---|---|
PT_DB_PATH | ./data/pennytrase.db | SQLite file. Back up by copying it. |
PT_API_KEY | unset = auth off | If set, writes + pricing + delete require X-API-Key header. |
PT_DEFAULT_INPUT_PER_1M | 1.0 | $ / 1M fallback input price for unpriced models. |
PT_DEFAULT_OUTPUT_PER_1M | 3.0 | $ / 1M fallback output price for unpriced models. |
PENNYTRASE_PRICING_URL | unset | GET /v1/pricing/refresh pulls and merges this JSON doc. |
Client variables (Pennytrase(...))
| Parameter | Default | Meaning |
|---|---|---|
base_url | "http://localhost:8000" | Or PENNYTRASE_BASE_URL. Trailing slash stripped. |
api_key | None | Or PENNYTRASE_API_KEY. Sent as X-API-Key. |
timeout | 2.0 | Or PENNYTRASE_TIMEOUT. Tracking never blocks longer. |
batch_size | 10 | Background sender batch size. |
flush_interval | 0.5 | Or PENNYTRASE_FLUSH_INTERVAL. |
enabled | True | Or PENNYTRASE_ENABLED=0. False = everything no-ops. |
sample_rate | 1.0 | Or PENNYTRASE_SAMPLE_RATE. Fraction of tasks actually tracked. |
dry_run | None | Or PENNYTRASE_DRY_RUN=path.jsonl. Payloads to file, zero network. |
service / env / version | SERVICE_NAME / ENV / GIT_SHA | Labels attached to every task and event. |
on_error | None | fn(kind, exc, info) called on every pipeline failure. |
SDK reference
Pennytrase client
Pennytrase(base_url=..., api_key=None, timeout=2.0, batch_size=10, flush_interval=0.5, enabled=True, sample_rate=1.0, dry_run=None, service=None, env=None, version=None, on_error=None)Explicit args override PENNYTRASE_* env (see Configuration). Starts a daemon background thread on construction. pt.stats counters Dict: sent / send_failures / dropped_events. Async: async with pt.atask(...) + await pt.flush_async(), or the AsyncPennytrase wrapper.
task() & track()
pt.task(customer_id, workflow, task_id=None) # → context manager yielding a tracker@pt.track(customer_id="acme", workflow="w") # decorator for functionstask_id auto-generates (full uuid4 hex) unless given; restarts are idempotent and keep the original started_at. Entry enqueues tasks/start with service/env/version labels; exception → auto failed (re-raised, never swallowed); clean exit without explicit finish → auto success.
llm() / tool() / success() / fail()
t.llm(model="unknown", provider="unknown", input_tokens=0, output_tokens=0, latency_ms=0, response=None, name="llm", pricing_override=None, cache_hit=False, retry_attempt=0, fallback=False, streaming=False)t.tool(name="tool", cost_usd=0.0, latency_ms=0, ...same flags)t.success(outcome_value=None) · t.fail()llm:model/providerare opaque strings, never validated. Cost is computed server-side (explicitcost_usd→ exact → alias →pricing_override→ estimate); response carriespricing_source, estimates surfaced in summary.tool:cost_usdstored verbatim (your API/tool-bill cost).success/fail: idempotent (second call is a no-op).
Token extraction
extract_tokens(response) returns (in, out, extractor_name), trying the registry in order: openai → anthropic → google (usage_metadata) → bedrock (inputTokens/outputTokens) → langchain → generic alias scanner → (0, 0, "none"). Add your own shape with register_extractor(fn, name) — fn returns (in, out) or None. Adapters (langchain_handler, llamaindex_handler, custom_handler(tracker, usage_fn)) all lazy-import their frameworks.
Fail-open contract
- Logging methods only enqueue — they cannot raise for network reasons.
- One daemon thread POSTs with a short timeout; every send failure (refused, timeout, 429, 500) is logged to stderr and swallowed.
- The context manager never suppresses your exceptions.
Stopping the server can never crash or block your agent — you only lose tracking data for the outage.
Integrating your product
Map your world onto three strings: customer_id (who pays), workflow (which agent flow), task_id (one run — auto is fine).
OpenAI
import time
from openai import OpenAI
from pennytrase import Pennytrase
client, pt = OpenAI(), Pennytrase(base_url="http://localhost:8000")
with pt.task(customer_id=cust.id, workflow="support_chat") as t:
start = time.time()
resp = client.chat.completions.create(model="gpt-4o-mini", messages=msgs)
t.llm(model="gpt-4o-mini", response=resp, # tokens auto-read from resp.usage
latency_ms=int((time.time() - start) * 1000))
t.success(outcome_value=order_value)
Anthropic
from anthropic import Anthropic
client = Anthropic()
with pt.task(customer_id=cust.id, workflow="doc_summary") as t:
msg = client.messages.create(model="claude-3-haiku-20240307",
max_tokens=500, messages=msgs)
t.llm(model="claude-3-haiku-20240307", response=msg) # usage.input/output_tokens
t.success()
LangChain
from pennytrase import langchain_handler
with pt.task(customer_id=cust.id, workflow="research") as t:
chain.invoke(query, config={"callbacks": [langchain_handler(t)]})
t.success()
Serverless / background workers
Daemon threads may not outlive the invocation — call pt.flush() before returning. One Pennytrase instance per process is enough (thread-safe queue). Set monthly_revenue per customer once via PUT /v1/customers/{id}; the dashboard prorates it automatically.
Server & API
| Endpoint | Use |
|---|---|
POST /v1/tasks/start | {task_id, customer_id, workflow} |
POST /v1/events | {task_id, kind: llm|tool, model?, input_tokens?, output_tokens?, cost_usd? (tools), latency_ms?} |
POST /v1/tasks/finish | {task_id, status: success|failed, outcome_value?} |
PUT /v1/customers/{id} | {name?, monthly_revenue?} (upsert) |
GET /v1/tasks/recent | Newest-first feed (limit, offset, customer_id, workflow, status) |
GET /v1/tasks/{id} | Task + ordered events drill-down |
GET /v1/metrics/summary|customers|workflows|trend | Aggregates; ?from=&to= filters |
GET / PUT /v1/pricing | View / merge per-1M-token prices |
GET /health · GET / · GET /guide | Health · dashboard · this guide |
Interactive explorer: /docs (Swagger). Markdown version: docs/api.md.
Dashboard
Dashboard tab: spend/success/cost-per-success/wasted/margin cards; customers worst-margin-first (red < 0%, amber < 30%) with inline revenue editing + CSV export; workflows with retry-heavy flags; 14-day cost/success chart. Calls tab: newest tasks with filters; click a row for the per-event cost breakdown. Pricing tab: edit model prices (new events only).
Cost & margin (exact)
cost = in/1e6 × input_per_1M + out/1e6 × output_per_1M (server-side; unknown model → 0 + warning). Task cost = sum of events. revenue = monthly_revenue × days/30; margin = revenue − cost. cost/success = all-task cost ÷ successful tasks. retry-heavy = > 4 events/task. Full definitions: docs/methodology.md.
Troubleshooting & FAQ
Empty dashboard? Seed scripts hardcode port 8000 — serve there or edit them. Costs estimated? Model has no price: add it via Pricing tab / PUT /v1/pricing, or set PT_DEFAULT_*. Script exits before data lands? Call pt.flush(). Reset? rm ./data/pennytrase.db + reseed. More: docs/troubleshooting.md.