Skip to main content

TokenJam — local-first OTel-native observability for Autonomous AI agents

Project description

TokenJam

Token Efficiency For AI Agents

TokenJam reads your agent's telemetry and tells you when to downsize, when to trim prompts, what to cache, what to script, and what plans you've already paid to figure out — then shows it all in a local browser dashboard. Runs entirely on your machine.

CI PyPI Downloads Python npm License: MIT OTel

No cloud · No signup · No vendor lock-in

tj quickstart output: a quota-composition panel showing what share of tokens went to re-reading context vs. net-new work, plus a session timeline with per-session token counts and re-read percentages

Quickstart

See where your Claude Code quota goes — 15 seconds, no install (reads the session logs you already have):

npx tokenjam                          # or: uvx tokenjam

Keep it — the full install adds live capture, all 8 analyzers, Lens (the local dashboard), and the zero-token statusline:

pipx install tokenjam && tj onboard

Building your own agent with the SDK? Install in your project (pip install tokenjam) — see the table below.

Zero config, no signup, local-first: npx tokenjam reads the Claude Code session transcripts you already have on disk (~/.claude/projects/*.jsonl) into a throwaway in-memory database. Nothing is written to disk, no daemon runs, no config is created. It prints:

  • Quota composition — what share of your tokens went to re-reading context (history, CLAUDE.md, accumulated tool output) versus net-new work.
  • A session timeline — your most recent sessions, token spend, and re-read share.

npx tokenjam and uvx tokenjam launch the Python CLI via uvx/pipx under the hood — see docs/installation.md for the runner requirements and the full install matrix.


Which path are you?

You are Run this What you get
Claude Code user pipx install tokenjam && tj onboard --claude-code Auto-backfills your last 30 days, wires a zero-token statusline, unlocks all six analyzers + Lens
Codex CLI user pipx install tokenjam && tj onboard --codex Same onboarding flow, wired for Codex's session logs
Python SDK / API agent dev pipx install tokenjam && tj onboard + @watch() in your code (below) Live capture from your own agent process, no CLI-specific backfill
Framework user (LangChain / CrewAI / AutoGen) pip install tokenjam[langchain] (or [crewai] / [autogen]) + one patch_*() call Framework-level spans with no manual instrumentation
Already on Langfuse / Helicone tj backfill langfuse --source-url <url> --api-key <key>
(swap langfusehelicone — same flags)
One-time import of your existing traces into the local DB
Any OTel-emitting agent Point your OTLP exporter at tj serve (http://127.0.0.1:7391/v1/traces) Zero-code ingestion — no SDK, no patch

LlamaIndex and the OpenAI Agents SDK ship their own native OTel support — point their exporter at tj serve rather than installing an extra. Full matrix: docs/framework-support.md.

Prefer a single page stacking all five paths in order, each ending with a verify step? See docs/getting-started.md.


Full setup — Claude Code

pipx install tokenjam
tj onboard --claude-code
tj optimize          # cost-saving candidates from your actual usage
tj serve             # open the dashboard at http://127.0.0.1:7391/

Onboarding also wires a zero-token statusline into Claude Code — tj statusline runs out-of-band each turn (no model quota) and shows this session's re-read share with a /compact nudge: ◆ Opus 4.8 2.4M tok 🕳️ re-read 95% → /compact to reclaim quota. It does not add an in-loop MCP server (that's an SDK / API surface — an MCP would tax every turn).

That's it. Run bare tj any time and it points you to the next best action (tj status, tj tokenmaxx, tj optimize, or tj serve).

To upgrade later: pipx upgrade tokenjam (then tj stop && tj serve & to reload the daemon, and tj --version to verify). See docs/installation.md.

For any Python agent:

from tokenjam.sdk import watch
from tokenjam.sdk.integrations.anthropic import patch_anthropic

patch_anthropic()

@watch(agent_id="my-agent")
def run(task: str) -> str:
    ...

Python SDK · TypeScript SDK · Codex onboarding · OTel-compatible agents


Six analyzers + Lens. One install.

TokenJam reads telemetry from every major agent runtime, framework, provider, and observability tool and surfaces savings across six areas — then brings them together in a local browser dashboard.

🪶 Downsize

Flags sessions where a cheaper model in the same family is worth a look. Never claims quality equivalence — surfaces examples so you can spot-check.

tj optimize downsize

Details →

💾 Cache

Shows your current caching ratio per (provider, model) and suggests Anthropic prompt-cache breakpoints from stable prefixes in your real usage. Two related CLI names under one product — cache measures the ratio, cache-recommend suggests the breakpoints.

tj optimize cache
tj optimize cache-recommend

Details →

📜 Script

Finds clusters of deterministic (tool_name, arg_shape) sequences that match the shape of work a plain script could replace.

tj optimize script

Details →

✂️ Trim

Predicts which regions of your prompts the model gives little weight to. Surfaces what's safe to cut.

tj optimize trim

Details →

🔁 Reuse

Detects clusters of sessions where your agent re-plans the same work and exports reviewable skeleton templates you can drop into a slash command or script.

tj optimize reuse

Details →

🧩 Subagent right-sizing

Breaks a session's cost down per subagent (Claude Code Task calls) and flags ones that ran on a premium model or were handed more context than the work needed — sometimes a large share of a session's spend, hidden inside the parent total.

tj optimize subagent

Details →

tj optimize (no args) runs every analyzer — the six above, plus budget-projection (projects your monthly run-rate against a configured [budget.<provider>] ceiling; powers Lens's Budget screen) and cache-recommend (the Cache card's breakpoint-suggestion half, above). Run a subset with tj optimize downsize cache reuse.

🔭 Lens

tj serve brings every analyzer's findings, your real spend, and your alerts together in one local browser dashboard. No cloud, no signup, fully offline.

tj serve

Details →


Lens — the local dashboard

tj serve runs Lens at http://127.0.0.1:7391/: a Dashboard that lands you on recoverable waste and health at a glance, with an embedded explorer to slice your usage any way (metric × dimension × chart); plus Status, Traces, Cost, Analytics, Alerts, Drift, Optimize, and Budget screens. Plan-tier-aware, fully offline, no signup.

Dashboard — recoverable waste, health at a glance, and the embedded pivot explorer Cost — spend over time + cache savings
Trace waterfall — session-level spans with cost annotations Status — per-agent cards
Analytics explorer — tool-usage leaderboard Analytics explorer — cost-by-model leaderboard

tokenjam.dev/products/lens for the visual walkthrough.


Beyond optimization

TokenJam is also a full observability stack. The six analyzers and Lens ride on top.

  • Real-time cost tracking — every LLM call priced as it happens
  • Safety alerts — 13 alert types, 6 channels (ntfy, Discord, Telegram, webhook, file, stdout)
  • Behavioral drift detection — Z-score baselines, no LLM required
  • Schema validation — declare or infer JSON Schema for tool outputs
  • Context & quota auditstj context (re-read vs. net-new split) and tj quota-audit (retroactive Opus usage check) over your Claude Code sessions
  • Close the looptj loop annotates a run with a verdict, promotes a bad run into a stored expectation, and tracks whether later runs pass or regress against it
  • Prompt summarization (advisory)tj summarize finds prompt files worth condensing and estimates the per-call saving
  • Enforcement-plane proxy (suggest mode)tj proxy surfaces routing suggestions locally, without rewriting requests
  • OTel-native — point any OTLP exporter at tj serve and you're done
  • Statusline — a zero-token Claude Code status line (tj statusline, wired by tj onboard --claude-code) showing this session's re-read share + a /compact nudge
  • MCP server — in-request-path tools for SDK / API users (not Claude Code / Codex subscription users — an in-loop MCP is a per-turn quota burden there; they get the out-of-band statusline instead)

Prove a swap holds — TokenJam Bench

tj optimize downsize flags candidates: cheaper models worth a look. It never claims the cheaper model would have produced the same answer. TokenJam Bench is the companion that checks. It runs your original and candidate models against real task suites and reports the pass-rate difference with statistics (Wilson CI + McNemar), so you get a hedged verdict ("holds" or "regressed") instead of a guess.

pip install tokenjam-bench
tjb run --original anthropic:claude-opus-4-7 --candidate anthropic:claude-haiku-4-5

Bench reports measured pass-rate on a suite, never "certified" or "quality preserved." Open source and local, like TokenJam. Learn more →


CLI

tj optimize            # every analyzer (the six above, plus budget-projection + cache-recommend)
tj optimize downsize   # one analyzer (positional args)
tj tokenmaxx           # shareable spend-tier callout
tj status              # current cost, tokens, active alerts
tj cost --since 7d     # spend by agent / model / day / tool
tj alerts              # everything that fired while you were away
tj drift               # behavioral drift Z-scores
tj report --reuse      # HTML + Markdown skeleton export for the Reuse analyzer
tj backfill claude-code # ingest historical ~/.claude/projects/ sessions
tj serve               # start Lens + REST API

Full CLI reference →


Documentation

Topic Where
🚦 Getting started — every entry path, least to most commitment docs/getting-started.md
⏱️ The first hour — what to do once data flows docs/first-hour.md
🪶 Downsize / Cache / Script / Trim deep-dives docs/optimize/
🔁 Reuse analyzer deep-dive docs/optimize/reuse.md
🧪 Prove a downsize candidate holds (TokenJam Bench) tokenjam-bench
Claude Code & Codex integration docs/claude-code-integration.md
Claude Code vs. Codex vs. SDK vs. OTLP — capability matrix docs/agent-capability-matrix.md
Harness run grouping (governors / fan-out launchers) docs/harness-integration.md
Python SDK reference docs/python-sdk.md
TypeScript SDK reference docs/typescript-sdk.md
Framework support (LangChain / CrewAI / etc.), including the full OTel provider/framework matrix docs/framework-support.md
Alert channels & rule reference docs/alerts.md
Backfill from Langfuse / Helicone / OTLP docs/backfill/
Enforcement-plane proxy (suggest mode) docs/proxy/overview.md
Policy rules docs/policy/overview.md
Configuration docs/configuration.md
Architecture deep-dive docs/architecture.md
Installation extras (Trim, framework patches) docs/installation.md
Export to Grafana / Datadog / NDJSON docs/export.md
NemoClaw sandbox observer docs/nemoclaw-integration.md
Release notes GitHub Releases

Roadmap

Shipped: Downsize · Cache · Script · Trim · Reuse · Subagent right-sizing · Claude Code + Codex onboarding · MCP server · Lens web UI · Backfill adapters (Langfuse, Helicone, OTLP) · Period comparison · Routing-config export · Read-only policy preview · Context & quota audits · Close-the-loop annotations/expectations · Prompt summarization (advisory) · Enforcement-plane proxy (suggest mode)

Up next (roughly):

  • Continued Lens polish + per-product visual branding
  • tj policy add | edit | apply — unified rule surface (today: tj policy list / tj policy decisions)
  • tj replay — replay captured sessions against new model versions
  • TypeScript framework patches (LangChain JS, OpenAI Agents SDK)
  • Vercel AI SDK & Mastra integrations
  • Published Docker image
  • GitHub Actions for CI drift/cost checks

Full version-by-version history: GitHub Releases.


Contributing

TokenJam is MIT, and contributions are welcome — from a one-line pricing fix to a whole new framework integration. A few easy on-ramps:

  • 🟢 Good first issues → — scoped, newcomer-friendly tasks, ready to pick up.
  • Bugs — notice something off? File a bug.
  • Documentation — struggled with something while getting started? Help the next person by writing or updating documentation.
  • 💸 Model pricingtokenjam/pricing/models.toml is community-maintained. Fix a rate or add a model in a single PR — no issue needed.
  • 🔌 Framework integrations — provider/framework patches follow one clear pattern (tokenjam/sdk/integrations/anthropic.py is the reference). Open an issue first to align on approach.
  • 🤖 Coding Agents are first-class citizens — TokenJam is built by Humans AND AI coding agents, and contributing with one is first-class. Claude Code: read CLAUDE.md and run /init to bring your agent up to speed. Codex / other agents: AGENTS.md has the critical rules.

Setup and the full dev workflow are in CONTRIBUTING.md.

If TokenJam saves you tokens, ⭐ star it and 👁 watch for releases — we ship often.


tokenjam.dev · PyPI · npm · TokenJam Bench · Issues

MIT License · Built by Metabuilder Labs

TokenJam was created by Anil Murty — reach him at anil@metabldr.com.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tokenjam-0.5.5.tar.gz (2.3 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tokenjam-0.5.5-py3-none-any.whl (826.7 kB view details)

Uploaded Python 3

File details

Details for the file tokenjam-0.5.5.tar.gz.

File metadata

  • Download URL: tokenjam-0.5.5.tar.gz
  • Upload date:
  • Size: 2.3 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for tokenjam-0.5.5.tar.gz
Algorithm Hash digest
SHA256 4527b482f5a950f98f2a165ee2d93de1549ab2437997557813ada2e56ea134f5
MD5 a663d8d6388624eea7c2297e70a20461
BLAKE2b-256 bbcdcb19d4e8319a50952acb136dd2c33a04b1ef45b953818b01d674035ed7e2

See more details on using hashes here.

Provenance

The following attestation bundles were made for tokenjam-0.5.5.tar.gz:

Publisher: publish-pypi.yml on Metabuilder-Labs/tokenjam

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tokenjam-0.5.5-py3-none-any.whl.

File metadata

  • Download URL: tokenjam-0.5.5-py3-none-any.whl
  • Upload date:
  • Size: 826.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for tokenjam-0.5.5-py3-none-any.whl
Algorithm Hash digest
SHA256 f7067082e03d8ab8a4d00374868bafb8ece82b26f7e4a8bfae9155c1ad61442e
MD5 db7961bd1643d9528a388095cc6240dc
BLAKE2b-256 ac45b0b177f85f67f65a34b13aad932abbb52d0c5f6389a9f5d604e65c3b34ab

See more details on using hashes here.

Provenance

The following attestation bundles were made for tokenjam-0.5.5-py3-none-any.whl:

Publisher: publish-pypi.yml on Metabuilder-Labs/tokenjam

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page