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 providerprovider-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 whenLLMCOST_E2E_OPENAI_COMPLETIONS_MODELis 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ai_cost_calculator-0.1.17.tar.gz.
File metadata
- Download URL: ai_cost_calculator-0.1.17.tar.gz
- Upload date:
- Size: 19.9 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
07468ab84b17e1ec9c6a8740a36fa45d967e8d474b2a5dd4d309f5cc5e23eb5c
|
|
| MD5 |
930bfc30994807269b7c6e8950f19794
|
|
| BLAKE2b-256 |
0567ace618aba05360fb96b777aa11aaae489a8461c21ac6651aeb60fb606182
|
File details
Details for the file ai_cost_calculator-0.1.17-py3-none-any.whl.
File metadata
- Download URL: ai_cost_calculator-0.1.17-py3-none-any.whl
- Upload date:
- Size: 20.7 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
85fb2935ddb46a7854bd4f2676d76a619f3a33e1a97f65c78b02de4374875fbc
|
|
| MD5 |
d24c241ab9899d2b942730882779f8e6
|
|
| BLAKE2b-256 |
8f11055161506175db010f5c5503fc7c2f082308cd46bf2578f7a45707c3f2c1
|