README.md

llm-usage #

Ollama Cloud + Codex (ChatGPT) + Synthetic usage in one terminal view.

Single-file Python, stdlib + websockets, run via uv inline script. No install step, no config files to hand-write.

╭─ LLM USAGE ───────────────────────────────────────────────────────────────── 2026-09-01 09:00 CDT╮
│ ollama/alice  Pro                                                                                │
│   session 12.5% [██░░░░░░░░░░░░░░░░░░]  09-02 00:00Z                                             │
│   weekly   48.3% [██████████░░░░░░░░░░]  09-02 00:00Z                                            │
│ codex/alice  plus  alice@example.com                                                             │
│   5h      10.0% [██░░░░░░░░░░░░░░░░░░]  09-01 14:20Z                                             │
│   weekly  22.0% [████░░░░░░░░░░░░░░░░]  09-07 16:26Z                                             │
│   resets   1 free                                                                                │
│ codex/bob    plus  bob@example.com                                                               │
│   weekly   1.0% [░░░░░░░░░░░░░░░░░░░░]  09-06 18:55Z                                             │
│ synthetic  —                                                                                     │
│   5h       0.4% [░░░░░░░░░░░░░░░░░░]  09-01 09:10Z  used 10/2500                               │
│   weekly  36.0% [███████░░░░░░░░░░░░░]  09-01 23:02Z  $77.00 of $120.00                          │
│ 5 account(s) · one-shot · llm-usage --watch for live                                             │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯

Heat: green <60% · yellow <90% · red ≥90% · ! at 100%. --watch redraws in place with a countdown and ▲/▼ deltas between refreshes.

Install #

mkdir -p ~/.local/bin
cp llm-usage.py ~/.local/bin/llm-usage
chmod +x ~/.local/bin/llm-usage

Needs uv on PATH and python >= 3.10 (uv manages the interpreter + websockets automatically from the inline script header).

Usage #

llm-usage                      dashboard (one-shot)
llm-usage --watch [sec]        live loop, in-place redraw (default 60s)
llm-usage login <name> [url]   one-time Ollama sign-in in a visible Chrome window
llm-usage key [--stdin]        store Synthetic API key (masked prompt, live check)
llm-usage codex add <name>     add a Codex (ChatGPT) account (browser login)
llm-usage codex add <name> --home PATH   link an existing isolated CODEX_HOME
llm-usage codex remove <name>  drop a Codex account
llm-usage codex relogin <name> re-auth a Codex account whose tokens died
llm-usage --remove <name>      drop an Ollama account
llm-usage selftest             offline self-check (CI), no network needed
llm-usage --help               full usage

Ollama accounts #

login opens a real browser profile per account and waits for you to sign in:

llm-usage login alice https://ollama.com/signin
llm-usage login bob https://ollama.com/signin

Sessions persist in ~/.config/llm-usage/profiles/<name>/ and self-refresh via CDP (Network.getAllCookies). Scraped cookies are cached for 6h (~/.config/llm-usage/cookies/), so Chrome only spawns when the cache is cold/expired or the cookie is rejected — the next run re-scrapes and re-seeds automatically. Requires Chrome for Testing at ~/.agent-browser/browsers/chrome-*/chrome — the only host dependency.

Billing mode is detected per account on every run — no configuration:

  • Legacy plans (GPU-time billing) show session (5h) + weekly (7d) lanes.
  • New per-token plans (Ollama's 2026-08-31 transparent pricing) show one monthly lane: $X of $Y used against the monthly credit pool, plus +$N extra when a pay-as-you-go balance is present.

Accounts can switch plans anytime in Ollama's billing settings; the dashboard follows automatically on the next refresh.

Synthetic #

llm-usage key                  # masked prompt, never echoed
printf '%s' "$K" | llm-usage key --stdin

Stored at ~/.config/llm-usage/synthetic.key (0600). Validated against api.synthetic.new/v2/quotas on save, rendered in dashboard style.

Codex (ChatGPT) accounts #

llm-usage codex add work         # browser login, own isolated CODEX_HOME
llm-usage codex add main --home ~/.codex   # or link an existing CODEX_HOME

Each account lives under ~/.config/llm-usage/codex/<name>/ (its own CODEX_HOME) — the codex CLI holds one ChatGPT login at a time, so isolation is how you run several. On first use it launches the codex CLI's browser login once. Tokens self-refresh automatically: the usage endpoint is the same chatgpt.com/backend-api/wham/usage the codex TUI polls, with server-side refresh on expiry. The codex CLI must be on PATH (login only; usage reads go straight over HTTPS).

Shows whatever rate windows the account has — most show a 5-hour and a weekly window, but some accounts get weekly only (labels are derived from each window's duration, never from its slot), plus any extra windows (e.g. Spark), remaining free resets, plan, and account email.

Error rows include the HTTP code. A 404 means the backend route is gone server-side (e.g. the 2026-09-03 wham/usage outage) — tokens are still valid, so do not relogin; the row self-recovers when OpenAI restores the endpoint.

Colors #

Colors default to auto: on when stdout is a TTY, plain when piped. Four ways to override, in precedence order:

  1. --color auto|always|never (or --no-color) — per run
  2. LLM_USAGE_COLOR=auto|always|never — per shell
  3. NO_COLOR — any non-empty value forces plain (no-color.org)
  4. ~/.config/llm-usage/settings.json — persistent:
{ "color": "never" }

Debugging #

llm-usage -d (or --debug, or LLM_USAGE_DEBUG=1) writes a per-run log to <tmp>/llm-usage/debug-<timestamp>.log and prints the path to stderr. It records every HTTP request (URL, status, size, latency), response snippets on failures, provider tracebacks, and per-refresh summaries. Secrets (the synthetic key) are redacted. Logs are plain text — keep a few around to compare a working run against a broken one.

Local CI #

Tool versions are pinned in mise.toml (mise is the package manager). The full gate is one command:

mise run ci    # ruff lint + format check + mypy + selftest (~150ms)
  • ruff — lint (pycodestyle/pyflakes/bugbear/async/pyupgrade/ruff) + formatter check; rules in ruff.toml (line-length = 100). No pyproject.toml — deliberate for a single-file repo.
  • mypy — type check on llm-usage.py.
  • selftest — offline parser/render gate (see below).

Git hooks (prek) run the same tasks: ruff on commit, the full mise run ci on pre-push, so only verified code reaches main. One-time setup:

prek install && prek install --hook-stage pre-push

Test #

llm-usage selftest — pure, no network, no Chrome. Asserts the three live Synthetic quota shapes, current + legacy Ollama HTML, the cookie-cache TTL rules, the lane label/pct junction, and exact frame width.

As a herdr pane #

The repo ships a herdr plugin in plugin/ — a thin launcher that opens the live --watch dashboard in a split pane (herdr owns the PTY; the tool renders into it, auto-adapting to the pane's width). No build, no state.

git clone <repo> /path/to/llm-usage        # or use an existing checkout
herdr plugin link /path/to/llm-usage/plugin

Bind it in ~/.config/herdr/config.toml (prefix+m here — pick any free key; check with prefix+?):

[[keys.command]]
key = "prefix+m"
type = "shell"
command = "herdr plugin action invoke open --plugin llm-usage"
description = "LLM usage dashboard in split"

Then apply without restarting herdr: herdr server reload-config.

The key opens (a fresh) dashboard pane next to the focused pane. Close it with prefix+x. Re-running the key opens another pane rather than focusing an existing one — ponytail: add focus-if-open if that becomes a nuisance. The tool needs to be installed (Install section) or the repo checkout must be on disk (the plugin prefers llm-usage on PATH, then the repo's llm-usage.py via uv).

Adding a provider #

Full how-to (probe → archetype → wiring → selftest → split trigger): docs/adding-a-provider.md. Agent rules: AGENTS.md. The short version:

The whole tool hangs on one contract: a provider is a fetch_x() function that returns a Row. fetch_all() gathers the rows, draw() renders them. Row/Lane are provider-agnostic (see the data layer in the file). That seam is what keeps it maintainable as providers grow — everything else is plumbing.

To add provider #N:

  1. Write fetch_x() -> Row (or -> list[Row] for multi-account). Return a Row whose lanes are Lane(name, pct, reset=...) — pct is a number draw turns into a heat bar; pct=None + detail="..." is a bare info line (e.g. "resets 1 free").
  2. Register it in fetch_all() as an async group (one gather line per account, like the others) — every group runs concurrently.
  3. Give it an auth subcommand only if it needs one (mirrors codex add).
  4. Add a selftest case that feeds a captured sample payload through parse_x() and asserts the lane names/percentages. This is the guardrail — when the provider's API changes shape, this line is what catches it.

Keep each provider's state namespaced and self-contained (Codex does this: _codex_* functions, its own accounts.json registry, its own codex/ dir under ~/.config/llm-usage/). Don't reach across providers.

The three integration archetypes you'll hit — matched by the existing three:

Archetype Example What you implement
Simple API Synthetic A key or cookie + one HTTPS GET. Parse JSON. Easiest.
OAuth / token-backed API Codex A token store + a private endpoint that reads it. Often needs server-side token refresh (single-use rotating) and per-account isolation.
Browser-scrape, no public endpoint Ollama Some providers expose usage only in a web page. Drive a real browser profile over CDP (websockets), grab cookies or HTML, parse it. The Ollama path here is the template.

Pick the archetype by probing the provider first: is there an endpoint the official client or TUI calls? (Codex's was found the same way.) Only fall back to browser-scrape when there genuinely is no endpoint.

When to actually split into modules #

Don't split by default. The single file is a feature (one copy, runs anywhere, easy selftest). The real trigger is structural, not line-count alone:

  • a provider hits provider #5–6, or
  • one provider grows its own subcommands + state and pushes the file past ~1500 lines.

At that point extract that one provider to llm_usage/<provider>.py (peel the biggest), rather than a wholesale reorg. A Go/compiled rewrite buys nothing here (it's I/O-bound, and the Ollama CDP flow is painful to port) and loses the single-file uv install — not worth it. A typed-SDK generator (Baml, etc.) doesn't apply either: these are three unrelated private APIs with no shared schema to model.

Notes #

  • Provider groups fetch concurrently (asyncio.gather in fetch_all()); --watch first paint is ~1s.
  • Ollama plan badge parsed from the settings page (Cloud usage + capitalize badge span); legacy Cloud Usage … Pro markup still works as fallback.
  • Synthetic parser normalizes remaining/max, requests/limit, and percentRemaining quota shapes; credits shown as $remaining of $max.
  • Codex usage uses the private wham/usage endpoint + the codex CLI's public PKCE client id (no secret). Refresh tokens rotate single-use, so the rotated token is written atomically and never burned on a non-expired 401. Don't hand-copy an auth.json into two dashboard homes — two copies of one token family will poison each other on refresh (refresh_token_reused).
  • Single-file ANSI dashboard by design (no TUI dependency). The data layer (Row/Lane) is TUI-agnostic — add textual to the inline deps if a real TUI (keys, mouse) is ever wanted.