Metadata-Version: 2.4
Name: agentfin
Version: 0.2.2
Summary: Agent FinOps: see which AI agent, task and team spent what, and whether it was worth it
Author-email: "Calas Automations Inc." <office@calasautomations.com>
License: MIT
Project-URL: Homepage, https://calasautomations.com
Project-URL: Repository, https://github.com/calasdan-sketch/agentfin
Project-URL: Issues, https://github.com/calasdan-sketch/agentfin/issues
Project-URL: Changelog, https://github.com/calasdan-sketch/agentfin/blob/master/CHANGELOG.md
Keywords: llm,agents,finops,cost,token-usage,budgets
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: Topic :: Office/Business :: Financial
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.1
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Dynamic: license-file

<!-- Image URLs are absolute on purpose: GitHub resolves relative paths, PyPI does not. -->
![agentfin: Which AI agent spent what, and was it worth it.](https://raw.githubusercontent.com/calasdan-sketch/agentfin/master/docs/brand/agentfin-banner.png)

**Agent FinOps: see which agent, task and team spent what on AI, and whether it was worth it.**

```bash
pip install agentfin && agentfin demo
```

Needs Python 3.10 or newer. `demo` uses built-in synthetic data and temp files, so it touches nothing of yours.

Real output from `agentfin demo` (the line naming the temp folder is left out; the numbers are synthetic and mean nothing about your spend):

```text
agentfin demo: synthetic usage for 3 teams over 20 days. Not your data.
ingested 537 events (0 duplicates skipped, 0 unpriced)

Spend by team:
dim                                   cost    events  notes
------------------------------------------------------------
platform                            $77.77       418
support                              $1.34       119

Anomaly check (which agent caused the spike?):
⚠ agent=claude-code on 2026-11-27: $72.28 = 254.97x median baseline (z=1199.11)
    · retry-storm: $72.00
    · pr-review: $0.28

Next: agentfin init, then agentfin ingest your-usage.jsonl
```

- **Attributes every event.** Usage from your agent stack goes into a local SQLite ledger and is tagged to a task, agent and team by rules you control.
- **Prices from your own price book.** Cost is stored as integer micro-USD. A model with no price shows up as UNPRICED in every report, never as zero.
- **Tells a spike from real work.** Anomaly detection names the likely cause, budgets forecast month-end spend before you overrun, and tagged outcomes give cost-per-outcome and ROI.

![PyPI](https://img.shields.io/pypi/v/agentfin)
![License](https://img.shields.io/badge/license-MIT-blue)
![Python](https://img.shields.io/pypi/pyversions/agentfin)

---

`agentfin` answers the Monday-morning question: *did the $4K spike come from a runaway agent or real work?* Read [Limitations](#limitations-read-before-trusting-the-numbers) before trusting the numbers.

## Install

```bash
pip install agentfin
# or from source:
pip install -e ".[dev]"
```

## 60-second start

```bash
agentfin demo                                   # synthetic data, temp files, touches nothing of yours
agentfin init                                   # scaffolds .agentfin/
agentfin ingest --adapter provider usage.jsonl  # Anthropic/OpenAI-style records
agentfin ingest --adapter gateway gateway.jsonl # calas-gateway ledger lines
agentfin ingest --adapter jsonl custom.jsonl    # your own shape
agentfin report --by team
agentfin anomalies                              # spikes + probable cause
agentfin budgets                                # month-end forecast vs caps
agentfin budgets set team:platform 500          # create/update a monthly cap
agentfin outcomes tag refactor --kind hours_saved --value 4
agentfin outcomes roi                           # cost-per-outcome per task
agentfin dashboard --out report.html            # static HTML, no server
```

## How it works

1. **Ingest** — adapters normalize provider usage records into one canonical
   event: `{ts_utc, provider, model, tokens in/cache/out, task, agent, team}`.
   Redaction runs *before* storage on each record's metadata (keys such as
   `prompt`/`content`/`api_key`, and credential-looking strings such as `sk-…`).
   It does not scan the agent, task or team tags: keep secrets out of those.
2. **Attribute** — `rules.yaml` maps model/provider/metadata regexes to
   task/agent/team tags. Adapter-supplied tags win; defaults catch the rest.
3. **Price** — `pricing.yaml` holds exact-SKU rates (USD per 1M tokens).
   Cost is computed at ingest and stored as **integer micro-USD** (no float
   drift). SKUs with no price land in the **UNPRICED** bucket — loud in every
   report, never silently zero. `agentfin reprice` backfills once you add rates.
4. **Ledger** — SQLite. Every event carries an idempotency key,
   so re-ingesting the same file is a no-op (no double-counting). Priced rows
   are never edited; `reprice` fills only NULL (unpriced) costs in place, once.
5. **Analyze** — reports by agent/task/team/model, daily trends, robust
   anomaly detection (median/MAD, 14-day baseline minimum, 24h cooldown,
   probable-cause attached), budget burn-rate forecasts that alert *before*
   overrun, and ROI from tagged outcomes.
6. **Trust** — `agentfin reconcile invoice.csv` diffs ledger totals against
   your actual provider invoice, per SKU.

## Config files (in `.agentfin/`)

| file | purpose |
|---|---|
| `pricing.yaml` | exact-SKU USD/1M-token rates. Paste from the provider pricing page, or import them (below). |
| `rules.yaml` | attribution rules, first match wins. |
| `budgets.yaml` | monthly caps per team/agent with forecast-alert thresholds. |
| `config.yaml` | display currency + FX (marked `*` as estimates), extra redact keys. |

## Importing prices from LiteLLM

```bash
# download model_prices_and_context_window.json from the LiteLLM repo yourself, then:
agentfin pricing import-litellm model_prices_and_context_window.json --match 'claude|gpt-4o'
```

Reads the local file only (no network). Per-token prices become USD per 1M
tokens; cache read/write prices are included when the file has them. SKUs are
named `<litellm_provider>:<model>`, so check they match the `provider:model`
your ingested events use (`agentfin doctor` lists unpriced SKUs). Existing SKUs
are kept unless `--overwrite`; entries with no token price (images, audio) are
skipped and counted. Re-saving `pricing.yaml` drops its comments. The prices
are a snapshot of LiteLLM's file, not the provider's page: reconcile against
your invoice.

## Adapters

- `jsonl` — generic JSONL, flat or nested `usage` blocks, flexible key names.
- `provider` — raw Anthropic (`msg_…`) / OpenAI (`chatcmpl-…`) API responses;
  cache tokens mapped correctly. Optional `agentfin` sidecar for tags.
- `gateway` — calas-gateway ledger lines (`route: provider/model`);
  gateway-computed `cost_usd` is preserved verbatim, never re-priced.

## Commands

`demo · init [--force] · ingest · report · trends · anomalies (detect) · alerts ·
budgets [check|set] · outcomes [tag|roi] · pricing import-litellm · reconcile ·
reprice · dashboard · doctor`

`budgets`, `budgets check` and `anomalies` take `--json` and
`--fail-on-alert` (exit 1 if a budget is forecast over its alert threshold
or an anomaly is reported; default exit 0). For cron. An anomaly already
reported within its 24h cooldown is not reported again, so it does not fail
the next run.

`doctor` surfaces unpriced SKUs and unattributed events — the two things
that silently ruin FinOps data. `init` refuses to overwrite existing config
files unless `--force` is given. `outcome`/`roi` remain as hidden aliases
for `outcomes tag` / `outcomes roi`.

## Development

```bash
python -m pytest
ruff check agentfin/ tests/
```

## Limitations (read before trusting the numbers)

Limits up front, in plain words:

- **Prices are yours to maintain.** Model prices change; `pricing.yaml` is a
  snapshot. Totals are only as right as your price book — reconcile monthly.
- **File-based ingest only.** v1 does not poll provider APIs; bring your own
  export or cron the API pull into JSONL.
- **Attribution is heuristic.** Rules are regexes over metadata. Garbage tags
  in → garbage attribution out. `doctor` shows the unattributed share.
- **Ledger is USD-only.** Multi-currency display is a report-time FX estimate
  (marked `*`), not accounting truth.
- **Anomalies need history.** 14 days of baseline minimum; new teams/agents
  get no anomaly coverage until then.
- **One source per call.** Idempotency keys stop same-file re-ingest, but the
  same API calls ingested via two adapters (e.g. gateway file + provider
  export) have different keys and will double-count. `doctor` warns on
  suspicious groups; ingest each source exactly once.
- **Anomalies evaluate the latest day in the data**, not necessarily today.
  Backfilled history gets a spike verdict on its last day.
- **Single-user SQLite.** No auth, no concurrency story beyond one writer.
  Fine for a team cron job; not a multi-tenant SaaS backend.
- **Outcome values are estimates.** `hours_saved × rate` is a model, not a
  bank deposit. ROI ranks tasks; don't put it in a 10-K.
- **`demo` data is synthetic.** It is generated on the fly so you can see the
  commands work; the numbers mean nothing about your spend.

## Links

- [Changelog](https://github.com/calasdan-sketch/agentfin/blob/master/CHANGELOG.md)
- [Report a problem](https://github.com/calasdan-sketch/agentfin/issues)
- License: MIT, Calas Automations Inc.
