Skip to main content

Python SDK for LLM Cost Monitor - Track, aggregate, and analyze LLM usage costs

Project description

LLM Cost Monitor - Python SDK

Official Python SDK for LLM Cost Monitor.

Installation

pip install llm-cost-monitor
# or
uv add llm-cost-monitor

Quick Start

from llm_cost_monitor import ApiClient, Configuration, EventsApi
from llm_cost_monitor.models import CreateEventRequest

config = Configuration(host="http://localhost:8080")
config.api_key["ApiKeyAuth"] = "Bearer YOUR_API_KEY"

with ApiClient(config) as client:
    events = EventsApi(client)
    
    response = events.create_event(
        CreateEventRequest(
            trace_id="unique-request-id",
            provider="openai",
            model="gpt-4o",
            input_tokens=1200,
            output_tokens=350,
            feature="chat",
            user_id="user_123",
        )
    )
    
    print(f"Cost: ${response.cost_usd}")

Authentication

from llm_cost_monitor import Configuration

config = Configuration(host=os.getenv("LLM_COST_MONITOR_URL"))
config.api_key["ApiKeyAuth"] = f"Bearer {os.getenv('LLM_COST_MONITOR_API_KEY')}"

API Reference

Events API

from llm_cost_monitor import EventsApi
from llm_cost_monitor.models import CreateEventRequest

events = EventsApi(client)

# Create event
result = events.create_event(
    CreateEventRequest(
        trace_id="req_abc123",
        provider="openai",
        model="gpt-4o",
        input_tokens=1200,
        output_tokens=350,
    )
)

# List events
event_list = events.list_events(limit=50)

Metrics API

from llm_cost_monitor import MetricsApi

metrics = MetricsApi(client)

# Get aggregated metrics
data = metrics.get_metrics(period="hour")

# Get usage summary
usage = metrics.get_usage(period="month")

Alerts API

from llm_cost_monitor import AlertsApi
from llm_cost_monitor.models import CreateAlertRequest

alerts = AlertsApi(client)

# Create alert
alerts.create_alert(
    CreateAlertRequest(threshold=100.0, window_interval="24h")
)

# List alerts
alert_list = alerts.list_alerts()

# Delete alert
alerts.delete_alert(id="alert-uuid")

Pricing API

from llm_cost_monitor import PricingApi

pricing = PricingApi(client)

# List all pricing
prices = pricing.list_pricing()

# Filter by provider
openai_prices = pricing.list_pricing(provider="openai")

FastAPI Middleware Example

from fastapi import FastAPI, Request
from llm_cost_monitor import ApiClient, Configuration, EventsApi
from llm_cost_monitor.models import CreateEventRequest
import uuid

app = FastAPI()

config = Configuration(host="http://localhost:8080")
config.api_key["ApiKeyAuth"] = "Bearer YOUR_API_KEY"

@app.middleware("http")
async def track_llm_costs(request: Request, call_next):
    response = await call_next(request)
    
    # If this request used LLM, track it
    if hasattr(request.state, "llm_usage"):
        usage = request.state.llm_usage
        
        with ApiClient(config) as client:
            events = EventsApi(client)
            events.create_event(
                CreateEventRequest(
                    trace_id=str(uuid.uuid4()),
                    provider=usage["provider"],
                    model=usage["model"],
                    input_tokens=usage["input_tokens"],
                    output_tokens=usage["output_tokens"],
                    feature=request.url.path,
                )
            )
    
    return response

Background Worker Example

import asyncio
from llm_cost_monitor import ApiClient, Configuration, EventsApi
from llm_cost_monitor.models import CreateEventRequest

async def track_costs_batch(events_batch: list):
    config = Configuration(host="http://localhost:8080")
    config.api_key["ApiKeyAuth"] = "Bearer YOUR_API_KEY"
    
    with ApiClient(config) as client:
        events = EventsApi(client)
        
        for event in events_batch:
            try:
                events.create_event(
                    CreateEventRequest(**event)
                )
            except Exception as e:
                print(f"Failed to track event: {e}")

# Usage
asyncio.run(track_costs_batch([
    {"trace_id": "1", "provider": "openai", "model": "gpt-4o", "input_tokens": 100, "output_tokens": 50},
    {"trace_id": "2", "provider": "anthropic", "model": "claude-3-5-sonnet", "input_tokens": 200, "output_tokens": 100},
]))

Error Handling

from llm_cost_monitor.exceptions import ApiException

try:
    events.create_event(...)
except ApiException as e:
    print(f"Error {e.status}: {e.body}")
    
    # Handle budget exceeded
    if e.status == 402:
        print("Budget limit exceeded!")

Environment Variables

LLM_COST_MONITOR_URL=http://localhost:8080
LLM_COST_MONITOR_API_KEY=your-api-key

License

MIT

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

llm_cost_monitor-1.1.0.tar.gz (32.9 kB view details)

Uploaded Source

Built Distribution

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

llm_cost_monitor-1.1.0-py3-none-any.whl (53.8 kB view details)

Uploaded Python 3

File details

Details for the file llm_cost_monitor-1.1.0.tar.gz.

File metadata

  • Download URL: llm_cost_monitor-1.1.0.tar.gz
  • Upload date:
  • Size: 32.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.1

File hashes

Hashes for llm_cost_monitor-1.1.0.tar.gz
Algorithm Hash digest
SHA256 019d638f7a5f92d159c6a1b4449e5ccaad30429498b1c5f8a072e074a0cc06f2
MD5 b66b530f22ea3e1ced037d03a4f55454
BLAKE2b-256 13bde7e19ba0b030b0622e54da408a45ab291fe4d3ee2d1b7165c428c112a4a0

See more details on using hashes here.

File details

Details for the file llm_cost_monitor-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for llm_cost_monitor-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0f0189e3daa5cfe87d599463c6b63b29af6bec6114ffba386ec91a7c2ead0034
MD5 56ccc6f87dde8464981dabfa2f2caa45
BLAKE2b-256 3a72295116e38896d4705f454ba822173aeb41086c890daea4fd22fcf06a2f41

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