Metadata-Version: 2.5
Name: pennytrase
Version: 0.3.1
Summary: Local-first cost, outcome and margin tracking for AI agent tasks. Fail-open SDK, zero dependencies.
Project-URL: Homepage, https://github.com/ramsakalle45/pennytrase
Project-URL: Documentation, https://github.com/ramsakalle45/pennytrase#readme
Project-URL: Issues, https://github.com/ramsakalle45/pennytrase/issues
Author: pennytrase contributors
License: MIT
License-File: LICENSE
Keywords: agents,ai,cost-tracking,llm,observability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Provides-Extra: server
Requires-Dist: fastapi; extra == 'server'
Requires-Dist: uvicorn; extra == 'server'
Description-Content-Type: text/markdown

# pennytrase

**Know which customer your AI agents are losing money on — locally, in 5 minutes.**

pennytrase attributes AI spend and margin per customer, per workflow, per call. It answers the question most agent teams otherwise answer with spreadsheets weeks later: *who is unprofitable, and which calls made them so?* A local-first FastAPI server prices every call, and a single-file dashboard sorts customers worst-margin-first with per-call drill-down.

```python
pip install pennytrase

from pennytrase import Pennytrase
pt = Pennytrase()  # reads PENNYTRASE_BASE_URL / PENNYTRASE_API_KEY from env

with pt.task(customer_id="acme", workflow="support_refund") as t:
    t.llm(model="gpt-4o-mini", response=openai_resp, latency_ms=900)  # tokens auto-read
    t.tool(name="stripe_refund", cost_usd=0.002)
    t.success(outcome_value=12.0)  # or t.fail(); an exception auto-marks failed
```

Set what the customer pays once (`PUT /v1/customers/acme {"monthly_revenue": 800}`), open the dashboard — the margin math, worst-first sorting, and per-call cost breakdown are already there.

## Why pennytrase

- **Fail-open by contract.** Tracking runs on a background queue with a 2s timeout and swallows every transport error. Kill the server mid-task: your agent survives. Verified by test, not just claimed.
- **Zero-dependency SDK.** Stdlib only — no install conflicts. Or vendor the single file (`src/pennytrase/__init__.py` → `pennytrase.py`).
- **Honest pricing.** Costs resolve server-side (explicit → exact → normalized alias → caller override → configured estimate). Every event is stamped with `pricing_source`; estimates are counted in the open, never silently $0.
- **Provider-agnostic.** Token extraction is a registry (OpenAI, Anthropic, Google, Bedrock, LangChain, generic alias scanner) with `register_extractor` for the rest. `model`/`provider` are opaque strings — new models need zero SDK changes.
- **Private by design.** Prompts and responses are never stored — metadata only (model, tokens, latency, cost, status). A test enforces the column allowlist.

## Who this is for (and not for)

**Use it if** you sell agent outcomes to customers at different price points and model costs are material to your margin — indie teams and small shops get value the same day.

**Skip it if** you have one flat product, negligible inference spend, or already pay for Langfuse/Helicone (don't run both — pick one). This is a specialized margin instrument, not a tracing/evals platform, and it doesn't try to be one.

## How it fits together

```
your agent ──fire-and-forget──▶ pennytrase SDK ──POST──▶ server (FastAPI + SQLite)
     ▲                                                        │
     │ never blocks, never raises                    prices calls, stores metadata
     │                                                        ▼
     └────────────── dashboard (one offline HTML file): spend, margins, Calls explorer
```

## Install

```bash
pip install pennytrase              # SDK only, zero dependencies
pip install "pennytrase[server]"    # + FastAPI server, then run: pennytrase-server
```

Single-file vendor alternative: copy `src/pennytrase/__init__.py` as `pennytrase.py` (no pip deps).

## Run the server

```bash
pennytrase-server                                   # from pip install "pennytrase[server]"
# or from a checkout:
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt && pip install -e .
uvicorn app.main:app --reload --port 8000
# or: docker compose up --build                     # SQLite persists in ./data/pennytrase.db
```

Dashboard: http://localhost:8000 · Official guide: http://localhost:8000/guide · API explorer: http://localhost:8000/docs · Markdown docs: [`docs/`](docs/index.md)

## See it working (2 minutes)

```bash
# terminal 1: server (any method above); terminal 2:
python examples/demo_seed.py      # 5 customers, 3 workflows — Umbrella Corp lands red on top
python examples/example_usage.py  # SDK live demo; stop the server mid-run — it exits 0
```

## API quick ref (full reference with curl examples: [`docs/api.md`](docs/api.md))

- `POST /v1/tasks/start {task_id, customer_id, workflow, sample_rate?, service?, env?, version?}`
- `POST /v1/events {task_id, kind: llm|tool, model?, provider?, input_tokens?, output_tokens?, cost_usd?, pricing_override?, flags?, ...}` — LLM cost computed server-side; response carries `pricing_source`.
- `POST /v1/tasks/finish {task_id, status: success|failed, outcome_value?}`
- `PUT /v1/customers/{id}` / `DELETE /v1/customers/{id}` (erasure)
- `GET /v1/tasks/recent` + `GET /v1/tasks/{id}` — per-call explorer feed and drill-down
- `GET /v1/metrics/summary|customers|workflows|trend?days=14` (spend split, sampling flag, estimate counters; `?from=&to=` supported)
- `GET/PUT /v1/pricing`, `GET /v1/pricing/refresh`, `DELETE /v1/tasks/before?date=` (retention), `GET /health`
- Auth: `PT_API_KEY` set → `X-API-Key` required on all `/v1/*` (reads included); off by default. The dashboard has a key field for this.

Cost: `in/1e6*in_price + out/1e6*out_price`. Margin = `monthly_revenue prorated (days/30)` − cost. Exact definitions: [`docs/methodology.md`](docs/methodology.md).

## Configuration

Client args override env; server env documented in [`docs/server.md`](docs/server.md). Key names: `PENNYTRASE_BASE_URL/API_KEY/TIMEOUT/FLUSH_INTERVAL/ENABLED/SAMPLE_RATE/DRY_RUN` (+ `SERVICE_NAME/ENV/GIT_SHA` labels), `PT_DB_PATH/PT_API_KEY/PT_DEFAULT_*/PT_RETENTION_DAYS`. Pre-0.3 `PENNYTRACE_*` names still work (deprecated whisper).

## Tests

```bash
pytest -q
```

## Scale & limits

Single-node SQLite + single API key: comfortable into the low millions of events on local SSD, then set `PT_RETENTION_DAYS` or move on — see [`docs/server.md`](docs/server.md). Sampling is supported but flagged, never silent.
