Skip to main content

Core Concepts

How TokenSense intercepts calls

TokenSense wraps your LLM client using Python’s __getattr__ proxy pattern. When you call client.messages.create(...), TokenSense:
  1. Forwards the call to the original client — unchanged
  2. Waits for the response
  3. Extracts metadata from the response (tokens, model, cost)
  4. Emits a CallEvent to a background thread
  5. Returns the original response to your code
Your code receives the exact same response object as before. The background thread handles the event asynchronously — your call latency is not affected.

observe()

The core function. Wraps any supported LLM client and returns a drop-in replacement.

Signature

Parameters

Examples

Minimal — just observe:
With output:
With user context:
Wrapping OpenAI:
Wrapping Groq:
Async client:
With explicit prompt logging: