Skip to main content

LLM cost observability and smart routing — stays in your code, works everywhere.

Project description

TokenSense

by Visual Vortex

LLM cost observability and smart routing — stays in your code, works everywhere.

License: MIT PyPI version Python 3.10+ PyPI Downloads


pip install tokensense-ai
from tokensense import observe
import anthropic

client = observe(anthropic.Anthropic())
response = client.messages.create(
    model="claude-sonnet-4-6",
    messages=[{"role": "user", "content": "Hello"}]
)
# → model=claude-sonnet-4-6 | in=12 out=24 tokens | $0.0003 | 847ms

That's it. One import. One wrapper. Every LLM call you make is now tracked.


Why TokenSense?

Other observability tools make you choose between easy and private. A proxy is easy but your API keys and prompts go through someone else's server. A self-hosted platform is private but takes 30 minutes to set up before you see anything.

TokenSense does neither. It runs inside your process. Nothing leaves unless you tell it to.

  • Privacy by default — prompts never leave your process. Ever. Not to us, not to anyone.
  • Zero latency — the observer fires after the response returns. Your call time is unchanged.
  • Works everywhere — dev, prod, Docker, Lambda, K8s. No infra required.
  • Smart routing — context-budget-aware model switching with automatic escalation on failure.
  • Framework agnostic — wraps OpenAI, Anthropic, Groq directly. Not tied to LangChain or anything else.
  • You own the data — output to your terminal, SQLite, your existing logger, or any HTTP endpoint.

Quickstart

Observe any LLM client

from tokensense import observe
import openai

# OpenAI
client = observe(openai.OpenAI())

# Anthropic
client = observe(anthropic.Anthropic())

# Groq
client = observe(groq.Groq())

# your existing code stays exactly the same
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Explain async/await"}]
)
# → model=gpt-4o-mini | in=18 out=312 tokens | $0.0001 | 623ms

Change where data goes

from tokensense import observe
from tokensense.outputs import SQLite, Logger, HTTP

# save locally — great for dev
client = observe(anthropic.Anthropic(), output=SQLite("./usage.db"))

# write to Python logger — goes to CloudWatch, Datadog, whatever you already use
client = observe(anthropic.Anthropic(), output=Logger("tokensense"))

# post to your own endpoint
client = observe(anthropic.Anthropic(), output=HTTP("https://your-server.com/ingest"))

Default output when you don't specify anything:

  • In development → prints to terminal + writes to ./tokensense.db
  • In production (ENV=production) → writes to Python logger, goes to your existing log infra

Add metadata per call

client = observe(
    anthropic.Anthropic(),
    user_id="user_123",
    session_id="sess_abc",
    tags=["production", "chat"],
)

Smart routing

from tokensense import Router, Rule

router = Router(
    tiers={
        "small":  ["llama-3.1-8b-instant", "claude-haiku-4-5"],
        "large":  ["claude-sonnet-4-6", "gpt-4o"],
    },
    rules=[
        # never route to small model if history is long
        Rule(if_context_tokens_gt=4000, deny_tiers=["small"]),

        # pin sensitive tasks to large model always
        Rule(if_task="legal-review", pin_tier="large"),
    ]
)

decision = router.route(
    messages=[{"role": "user", "content": "Review this contract"}],
    task_hint="legal-review"
)

print(decision.model) # → 'claude-sonnet-4-6'
print(decision.reason) # → 'pinned to large by rule'

What gets logged

By default, TokenSense logs only metadata — never your prompt content or response text.

Field Logged by default Opt-in
Model name
Input tokens
Output tokens
Cost (USD)
Latency (ms)
Routing decision
Status (success/error)
Prompt content log_prompts=True
Response content log_responses=True
User ID / tags pass as kwargs

To enable prompt logging explicitly:

client = observe(anthropic.Anthropic(), log_prompts=True, log_responses=True)

Output options

Output Best for Setup
Stdout() Development, debugging None
SQLite(path) Local persistence, single process None
Logger(name) Production — any log infra None
HTTP(url) Custom server, self-hosted dashboard Your endpoint
from tokensense.outputs import Stdout, SQLite, Logger, HTTP

# chain multiple outputs
from tokensense.outputs import Multi

client = observe(
    anthropic.Anthropic(),
    output=Multi(Stdout(), SQLite("./usage.db"))
)

Supported providers

Provider Sync Async Streaming
Anthropic
OpenAI
Groq
Google Gemini 🔜 🔜 🔜

No telemetry. Ever.

TokenSense does not call home. There is no usage tracking, no anonymous analytics, no background pings to any server. The framework has no network dependency of its own.

Read PRIVACY.md for exactly what is and isn't captured.


Roadmap

  • observe() wrapper — OpenAI, Anthropic, Groq
  • Stdout, SQLite, Logger, HTTP outputs
  • Auto environment detection (dev vs prod)
  • Router with context budget check
  • Shadow testing before switching tiers
  • tokensense report CLI — spend summary in terminal
  • Google Gemini support
  • LangChain integration
  • LlamaIndex integration

Contributing

TokenSense is MIT licensed and built in public. Issues, PRs, and feedback are welcome.

git clone https://github.com/SahilSelokar/Tokensense
cd Tokensense
pip install -e ".[dev]"
pytest

See CONTRIBUTING.md for guidelines.


License

MIT — see LICENSE


Built by Visual Vortex

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

tokensense_ai-0.1.1.tar.gz (15.3 kB view details)

Uploaded Source

Built Distribution

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

tokensense_ai-0.1.1-py3-none-any.whl (12.5 kB view details)

Uploaded Python 3

File details

Details for the file tokensense_ai-0.1.1.tar.gz.

File metadata

  • Download URL: tokensense_ai-0.1.1.tar.gz
  • Upload date:
  • Size: 15.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for tokensense_ai-0.1.1.tar.gz
Algorithm Hash digest
SHA256 b95c79ea8517f759aa2b1430eb72042ef7b2a85337a2a68e10a6eec504c761be
MD5 f4279944ad7d4a0367efab3c018bf22f
BLAKE2b-256 8816ecfa3f94bb0c3c9b6e60d3817ff305df04e68f8717aa41b200685b7a1ebf

See more details on using hashes here.

File details

Details for the file tokensense_ai-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: tokensense_ai-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 12.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for tokensense_ai-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 00d777786e6442aae33211cbd2600116b6eabcb8cc90625bd9d949a53fda3537
MD5 d29d2a69cdb98542bfd2a4f304b33bdd
BLAKE2b-256 167b55a9876eaf5720688163c98d0cfa3f2256979cdf4a129bce08afd0248825

See more details on using hashes here.

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