Skip to main content

Plug-and-play LLM token/cost tracking SDK with multiple sinks and audit metadata

Project description

llm-cost

Plug-and-play LLM token/cost tracking SDK with multiple sinks (SQLite, Postgres, Supabase, HTTP collector) and comprehensive audit metadata.

Features

  • 🎯 Decorator-first DX: @track_cost for non-streaming, finalize_llm_call for streaming
  • 🔒 Multi-tenant safe: Idempotent upserts scoped to workspace_id or project_id
  • 📊 Audit-ready: Every row includes usage_raw and rates_used for provable cost recomputation
  • 🚀 Non-blocking: Background batcher with bounded queue and outbox fallback
  • 💰 Dynamic pricing: Fetch live rates from OpenRouter with local cache
  • 🔌 Pluggable sinks: SQLite (default), Postgres/Supabase, HTTP collector
  • 🛡️ Privacy by default: No prompt/response content captured

Quick Start

import llm_cost as cost

# Initialize with Supabase (or SQLite, Postgres, HTTP)
cost.init_supabase(
    supabase_url="https://your-project.supabase.co",
    supabase_key="your-service-role-key",
)

# Set sticky context (workspace, session, user)
cost.set_context({
    "workspace_id": "ws-123",
    "session_id": "sess-456",
    "user_id": "user-789",
})

# Track non-streaming calls
from openai import OpenAI
client = OpenAI()

@cost.track_cost(model_arg='model', provider='openai')
def run_completion(model: str, prompt: str):
    return client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
    )

response = run_completion(model="gpt-4o", prompt="Hello!")

# Track streaming calls
@cost.track_cost(mode='defer')
def run_streaming(model: str, prompt: str):
    return client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        stream=True,
    )

stream = run_streaming(model="gpt-4o", prompt="Hello!")
tokens_in, tokens_out = 0, 0
for chunk in stream:
    # ... process chunk
    pass

# Finalize with actual token counts
cost.finalize_llm_call(
    provider="openai",
    model="gpt-4o",
    tokens_in=tokens_in,
    tokens_out=tokens_out,
    request_id=cost.new_request_id(),
)

Configuration

All config can be set via environment variables or passed to init():

# Supabase mode
export SUPABASE_URL=https://your-project.supabase.co
export SUPABASE_SERVICE_ROLE_KEY=your-key

# SQLite mode (default)
export COST_SINK_DSN=sqlite:///./llm_cost.db

# HTTP collector mode
export COST_COLLECTOR_ENDPOINT=https://your-collector.com/v1/batch
export COST_WRITE_KEY=your-write-key

# Flush behavior
export COST_FLUSH_AT=20
export COST_FLUSH_INTERVAL_MS=3000

Audit Metadata

Every ledger row includes:

{
  "context": {
    "metadata": {
      "billing": {
        "usage_raw": {
          "prompt_tokens": 123,
          "completion_tokens": 456,
          "reasoning_tokens": 100,
          "cached_input_tokens": 50
        },
        "rates_used": {
          "input_rate": 1.25,
          "cached_input_rate": 0.125,
          "output_rate": 10.0,
          "reasoning_rate": 10.0,
          "model_resolved": "gpt-4o",
          "pricing_source": "default",
          "pricing_version": "abc123"
        }
      }
    }
  }
}

This enables:

  • Row-by-row cost recomputation
  • Audit trails for billing disputes
  • Reconciliation jobs to detect drift

Installation

pip install llm-cost

License

MIT

Links

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

orchestra_llm_cost-0.1.2.tar.gz (17.3 kB view details)

Uploaded Source

Built Distribution

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

orchestra_llm_cost-0.1.2-py3-none-any.whl (18.3 kB view details)

Uploaded Python 3

File details

Details for the file orchestra_llm_cost-0.1.2.tar.gz.

File metadata

  • Download URL: orchestra_llm_cost-0.1.2.tar.gz
  • Upload date:
  • Size: 17.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for orchestra_llm_cost-0.1.2.tar.gz
Algorithm Hash digest
SHA256 7c34861da0cd56cc45b9f6d0d69453f97d8cee6cc05fd3f4581d905d5d96e229
MD5 7ac6cae21ff436442cd6bd6e7d24388c
BLAKE2b-256 ae028decf075a22c0987f8a26cb1f79c7612cd72c78e03575327b8e51d0e94ad

See more details on using hashes here.

File details

Details for the file orchestra_llm_cost-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for orchestra_llm_cost-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 5fa6b2e131839cd90249af9ce1bf7fc995b0e0af7c23cd29c85c396d31fc91ff
MD5 1d0ebb6cb6335389e8b919a27938f66b
BLAKE2b-256 3d5c618054b51ff4e91b0a92bbb541544f9b0ed05b03d94512c3a28930bce4e4

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