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.1.16.tar.gz (18.7 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.1.16-py3-none-any.whl (19.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ai_cost_calculator-0.1.16.tar.gz
  • Upload date:
  • Size: 18.7 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.1.16.tar.gz
Algorithm Hash digest
SHA256 fc581d278979801129acd56d157e0702f0373b19c864bcc6aa24e2052cf6f72e
MD5 1f96f67324b5d7b8dddb211d11d771f4
BLAKE2b-256 3c056d264ec583e61eb4ba06f54e5bb6cee738b8a4fdbd3c10e6dd4be3769005

See more details on using hashes here.

File details

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

File metadata

  • Download URL: ai_cost_calculator-0.1.16-py3-none-any.whl
  • Upload date:
  • Size: 19.4 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.1.16-py3-none-any.whl
Algorithm Hash digest
SHA256 961f9fb8f17039ed251cd171f713374b428c47b963c0e87a3b2a9ab763cfa9fd
MD5 7a3fb953da96e4619f3721482c18a332
BLAKE2b-256 5fcc994bebc89826705b6bbcf4757ba0720e87ea27a1abd67a4d8713f2775a3f

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