Skip to main content

Python SDK to calculate LLM API costs

Project description

ai-cost-calculator (Python)

Python SDK for calculating LLM API costs from provider response payloads with automatic usage extraction and live pricing lookups.

Installation

pip install ai-cost-calculator

Requires Python ≥ 3.10.

For development:

uv sync

Usage

Basic — Best-Effort Cost Calculation

The simplest way to get a cost. Tries multiple pricing sources until one succeeds:

from ai_cost_calculator import BestEffortCalculator

response = {
    "model": "gpt-4o-mini",
    "usage": {
        "prompt_tokens": 1000,
        "completion_tokens": 500,
        "total_tokens": 1500,
    }
}

result = BestEffortCalculator.get_cost(response)
print(result)
# {"currency": "USD", "cost": 0.000225}

Using a Specific Pricing Source

Pick a calculator to use a single pricing backend:

from ai_cost_calculator import (
    OpenRouterBasedCalculator,
    BerrilmBasedCalculator,
    PortkeyBasedCalculator,
    HeliconeBasedCalculator,
)

result = BerrilmBasedCalculator.get_cost(response)

With Provider-Prefixed Models

Models prefixed with a provider (e.g. from OpenRouter) are automatically normalized:

result = BestEffortCalculator.get_cost({
    "model": "openai/gpt-4o-mini",
    "usage": {"prompt_tokens": 1000, "completion_tokens": 500, "total_tokens": 1500},
})

Anthropic Response Format

Each provider's response format is handled automatically:

result = BestEffortCalculator.get_cost({
    "model": "claude-sonnet-4-20250514",
    "usage": {"input_tokens": 2000, "output_tokens": 800},
})

Google Response Format

result = BestEffortCalculator.get_cost({
    "model": "gemini-2.0-flash",
    "usageMetadata": {
        "promptTokenCount": 1500,
        "candidatesTokenCount": 600,
        "totalTokenCount": 2100,
    },
})

Error Handling

from ai_cost_calculator import BestEffortCalculator
from ai_cost_calculator.errors import (
    BestEffortCalculationError,
    ModelNotFoundError,
    UsageNotFoundError,
)

try:
    result = BestEffortCalculator.get_cost(response)
except BestEffortCalculationError as e:
    print("All pricing sources failed:")
    for cause in e.causes:
        print(f"  - {cause}")
except UsageNotFoundError:
    print("Could not extract token usage from response")

API Reference

Calculators

All calculators expose a single static method:

@staticmethod
def get_cost(response: Any) -> CostResult
Calculator Pricing Source Fallback Order
BestEffortCalculator All sources OpenRouter → Berri → Portkey → Helicone
OpenRouterBasedCalculator OpenRouter models API
BerrilmBasedCalculator BerriAI/LiteLLM JSON
PortkeyBasedCalculator Portkey pricing API
HeliconeBasedCalculator Helicone pricing API

Types

class CostResult(TypedDict):
    currency: str   # "USD"
    cost: float

@dataclass(frozen=True)
class TokenUsage:
    input_tokens: float
    output_tokens: float
    total_tokens: float

@dataclass(frozen=True)
class NormalizedPricingModel:
    model_id: str
    input_cost_per_1m: float
    output_cost_per_1m: float
    currency: str  # "USD"

class ResponseMetadata(TypedDict):
    model: str
    provider: str

Errors

All errors extend LlmcostError:

Error Description
UsageNotFoundError Token usage cannot be extracted from the response
ModelNotFoundError Model not found in the pricing source
PricingUnavailableError Pricing values are invalid
ModelInferenceError Model ID cannot be read from the response
ProviderInferenceError Provider cannot be determined from the model
BestEffortCalculationError All sources failed; .causes contains individual errors

Extending Provider Support

Add or update mappings in the root configs/ directory:

  • response-mappings.json — JSONPath expressions for extracting token usage per provider
  • provider-pricing-mappings.json — JSONPath expressions for normalizing pricing payloads

No code changes are required for mapping updates.

Tests

uv run pytest

Live E2E tests run only when LLMCOST_E2E_LIVE=true is set in the root .env.

When live mode is enabled, tests prefer OpenRouter (OPENROUTER_API_KEY) and fall back to native OpenAI (OPENAI_API_KEY). OpenAI endpoint coverage includes:

  • Responses API (/v1/responses)
  • Chat Completions API (/v1/chat/completions)
  • Legacy Completions API (/v1/completions) — runs only when LLMCOST_E2E_OPENAI_COMPLETIONS_MODEL is configured

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

ai_cost_calculator-0.2.1.tar.gz (20.8 kB view details)

Uploaded Source

Built Distribution

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

ai_cost_calculator-0.2.1-py3-none-any.whl (18.8 kB view details)

Uploaded Python 3

File details

Details for the file ai_cost_calculator-0.2.1.tar.gz.

File metadata

  • Download URL: ai_cost_calculator-0.2.1.tar.gz
  • Upload date:
  • Size: 20.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.7 {"installer":{"name":"uv","version":"0.10.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for ai_cost_calculator-0.2.1.tar.gz
Algorithm Hash digest
SHA256 1656e5a09aadc172204bf15c836295c4e4f638d13058f3edc2a6041f33f25b87
MD5 5346d7ea8b7441de5095347ca229289b
BLAKE2b-256 50833ba5f9339877f1388607ae02e661f0dee7b45865923f720bdb1fa1034150

See more details on using hashes here.

File details

Details for the file ai_cost_calculator-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: ai_cost_calculator-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 18.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.7 {"installer":{"name":"uv","version":"0.10.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for ai_cost_calculator-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b2974e47c062995b7bc1398e3e2cb014309f288004f7cab9e04eb0f768b3684d
MD5 382783b600e95b977e148a3d43cd50e6
BLAKE2b-256 e91b05adeb4bb33008b2b2f22a0c1351e99c88202d9e469bc157eeb4991fd332

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