Skip to main content

llmtrack

PyPI version Python versions License: MIT Downloads

LLM cost attribution per feature — track which parts of your product are spending your AI budget.


The Problem

Every company using LLMs knows their total monthly bill, but almost none know which user-facing feature or internal workflow is responsible. Without granular attribution, teams cannot optimize high-cost features, set feature-level unit economics, or enforce sub-budgets.


Installation

pip install llm-cost-track

Quickstart

import openai
from llmtrack import CostTracker

tracker = CostTracker()

with tracker.feature("document_summary"):
    response = openai.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Summarize this text: ..."}]
    )

tracker.report()

Features

  • 🎯 Feature-Level Cost Attribution: Tag LLM calls with clear product or feature names.
  • ⚡ Zero-Config Auto-Patching: Automatically captures usage from OpenAI and Anthropic SDKs with safe fallbacks.
  • 🧵 Thread-Safe Context Manager: Safely isolate concurrent requests and nested execution flows.
  • 💰 Built-in Model Pricing: Accurate per-million token pricing for 25+ major models across OpenAI, Anthropic, Google, Mistral, Meta, and DeepSeek.
  • 📊 Rich Terminal & HTML Reports: Generate rich ASCII terminal breakdown tables or self-contained dark-mode HTML dashboards.
  • 🚨 Budget Alerts: Set daily spending limits per feature with custom webhook/callback notifications.
  • 💾 Lightweight & Local Storage: Defaults to embedded SQLite (llmtrack.db) or in-memory storage.
  • 💻 CLI Tooling: Query stats and manage tracking databases directly from the terminal with llmtrack.

Supported Models

Provider Supported Models
OpenAI gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-4, gpt-3.5-turbo, o1, o1-mini, o3, o3-mini, o4-mini
Anthropic claude-opus-4, claude-sonnet-4-5, claude-haiku-4-5, claude-3-5-sonnet, claude-3-opus, claude-3-haiku
Google gemini-1.5-pro, gemini-1.5-flash, gemini-2.0-flash
Mistral mistral-large, mistral-small, mistral-7b, mixtral-8x7b
Meta llama-3.1-70b, llama-3.1-8b
DeepSeek deepseek-chat, deepseek-coder

Custom and unknown models fallback gracefully or can be registered with register_custom_model.


API Reference

CostTracker

tracker = CostTracker(
    storage: Optional[BaseStorage] = None,
    db_path: str = "llmtrack.db",
    auto_patch: bool = True
)
  • with tracker.feature(name: str):
    Context manager tagging all calls in the block with name.
  • tracker.log_call(model: str, input_tokens: int, output_tokens: int, feature: Optional[str] = None, latency_ms: float = 0.0, metadata: dict = {}) -> CallEvent
    Manually record an LLM call event.
  • tracker.report(days: int = 7, output: str = "terminal", filepath: Optional[str] = None) -> None
    Display or export a cost attribution report (output="terminal" or output="html").
  • tracker.summary(days: int = 7) -> dict
    Return an aggregated summary dict with total cost, calls, and per-feature breakdowns.
  • tracker.set_budget_alert(feature: str, daily_limit_usd: float, callback: Optional[Callable] = None) -> None
    Register daily spending alerts.

CLI Usage

# View terminal summary table (default: last 7 days)
llmtrack report

# Generate report for the last 30 days
llmtrack report --days 30

# Export self-contained HTML report
llmtrack report --html --output cost_report.html

# Clear database
llmtrack clear --db llmtrack.db

Storage Backends

  • SQLiteStorage(db_path="llmtrack.db"): Default persistent storage. Auto-creates schema and indexes.
  • MemoryStorage(): Thread-safe in-memory store, ideal for testing, serverless functions, or short-lived scripts.
from llmtrack import CostTracker, MemoryStorage

tracker = CostTracker(storage=MemoryStorage(), auto_patch=False)

Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Release files for llm-cost-track 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for llm-cost-track 0.1.0
File Size Uploaded
llm_cost_track-0.1.0.tar.gz 23.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for llm-cost-track 0.1.0
File Interpreter ABI Platform
llm_cost_track-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 47.2 kB

Release files / llm_cost_track-0.1.0.tar.gz

Download URL llm_cost_track-0.1.0.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
c445c00a3908a4f1286cd61bb675edb8f54082fb2874df185d46ace588c39639
BLAKE2b-256 checksum
How to use checksums
d050579578fb9ac028b419de43caeffd22f2721b0c3879a754ba51b551d7ef8a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release files / llm_cost_track-0.1.0-py3-none-any.whl

Download URL llm_cost_track-0.1.0-py3-none-any.whl
Size 23.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9b84d1019243ae511594584612433bf5912370a2975f8e1d3c3b106a35d65e8f
BLAKE2b-256 checksum
How to use checksums
934291a62a8c8af94a49da2187663d4a2e2ace45b2187dbf22691b7752a794c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release history Release notifications | RSS feed

0.3.0

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page