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
Metadata
Release files for ai-cost-calculator 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ai_cost_calculator-0.2.1.tar.gz | 20.8 kB | Without provenance | Details for ai_cost_calculator-0.2.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ai_cost_calculator-0.2.1-py3-none-any.whl | Python 3 | none | any | Details for ai_cost_calculator-0.2.1-py3-none-any.whl |
Total release size: 39.6 kB
Release files / ai_cost_calculator-0.2.1.tar.gz
| Download URL | ai_cost_calculator-0.2.1.tar.gz |
|---|---|
| Size | 20.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1656e5a09aadc172204bf15c836295c4e4f638d13058f3edc2a6041f33f25b87
|
|
BLAKE2b-256 checksum How to use checksums |
50833ba5f9339877f1388607ae02e661f0dee7b45865923f720bdb1fa1034150
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is 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}
|
Release files / ai_cost_calculator-0.2.1-py3-none-any.whl
| Download URL | ai_cost_calculator-0.2.1-py3-none-any.whl |
|---|---|
| Size | 18.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b2974e47c062995b7bc1398e3e2cb014309f288004f7cab9e04eb0f768b3684d
|
|
BLAKE2b-256 checksum How to use checksums |
e91b05adeb4bb33008b2b2f22a0c1351e99c88202d9e469bc157eeb4991fd332
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is 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}
|
Security for ai-cost-calculator 0.2.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.