Skip to main content

Python client for ModelPricing.ai cost estimates and tracking

Project description

modelpricing-ai

Python client for the ModelPricing.ai API — estimate LLM usage costs and track spending with a single call.

Installation

pip install modelpricing-ai

For async support (requires aiohttp):

pip install modelpricing-ai[async]

Quick Start

from modelpricing_ai import ModelPricingClient

with ModelPricingClient(api_key="YOUR_API_KEY") as client:
    estimate = client.estimate(
        model="gpt-4o-mini",
        tokens_in=1000,
        tokens_out=500,
        trace_id={"requestId": "abc-123"},
    )
    print(f"Cost: ${estimate.total:.6f}")

Async Usage

Install the async extra, then use AsyncModelPricingClient as an async context manager:

import asyncio
from modelpricing_ai import AsyncModelPricingClient

async def main():
    async with AsyncModelPricingClient(api_key="YOUR_API_KEY") as client:
        estimate = await client.estimate(
            model="gpt-4o-mini",
            tokens_in=1000,
            tokens_out=500,
            trace_id={"requestId": "abc-123"},
        )
        print(f"Cost: ${estimate.total:.6f}")

asyncio.run(main())

Response Structure

Both estimate() and await estimate() return an EstimateResponse object:

estimate.total        # float — total USD cost
estimate.model        # str   — canonical model name
estimate.traceId      # dict | None — your pass-through trace ID
estimate.breakdown    # EstimateBreakdownGroup
  .input              # EstimateBreakdown
    .unit             #   str   — e.g. "token"
    .branch           #   str   — pricing tier that matched
    .qty              #   int   — number of input tokens
    .rate             #   float — per-unit rate
    .subtotal         #   float — input cost
  .output             # EstimateBreakdown (same fields for output tokens)

Configuration

Parameter Default Description
api_key required Your ModelPricing.ai API key (also reads MODELPRICING_API_KEY env var)
base_url "https://api.modelpricing.ai" API base URL (also reads MODELPRICING_BASE_URL env var)
timeout 30.0 Request timeout in seconds
max_retries 3 Maximum retry attempts for transient errors
session None Optional requests.Session (sync) or aiohttp.ClientSession (async)

Parameters are resolved in order: constructor argument > environment variable > default.

client = ModelPricingClient(
    api_key="YOUR_API_KEY",
    base_url="https://api.modelpricing.ai",
    timeout=30.0,
    max_retries=3,
)

Error Handling

The client raises typed exceptions for different failure modes:

Exception HTTP Status When
Unauthorized 401 Invalid or missing API key
ValidationError 422 Invalid model name or metrics
NotFound 404 Unknown endpoint
ServerError 5xx Server-side failures

All exceptions inherit from ModelPricingError and include a status_code attribute.

from modelpricing_ai.errors import Unauthorized, ValidationError, ServerError

try:
    estimate = client.estimate(model="gpt-4o-mini", tokens_in=1000, tokens_out=500)
except Unauthorized:
    print("Check your API key")
except ValidationError as e:
    print(f"Bad request: {e}")
except ServerError:
    print("Server error — will be retried automatically")

Retry Behavior

The client automatically retries on transient errors with exponential backoff:

  • Retries: 5xx server errors and network/connection errors
  • No retry: 4xx client errors (401, 404, 422)
  • Default: 3 retries with exponential backoff (0.1 s initial, 2 s max)
# Increase retries for unreliable networks
client = ModelPricingClient(api_key="YOUR_API_KEY", max_retries=5)

# Disable retries (no retry attempts)
client = ModelPricingClient(api_key="YOUR_API_KEY", max_retries=0)

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

modelpricing_ai-2026.2.14.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

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

modelpricing_ai-2026.2.14-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file modelpricing_ai-2026.2.14.tar.gz.

File metadata

  • Download URL: modelpricing_ai-2026.2.14.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for modelpricing_ai-2026.2.14.tar.gz
Algorithm Hash digest
SHA256 460e82ae2cf940c915b3af0b577922084a923befc59673fb44e8c478ccb47d07
MD5 b0fdb5810eae4ee7ac3c05c01e616490
BLAKE2b-256 8d526bb4a7258335c0bd79dcadf8547927c014f4751fa226437b6e4d31e691db

See more details on using hashes here.

Provenance

The following attestation bundles were made for modelpricing_ai-2026.2.14.tar.gz:

Publisher: publish-python.yml on humanspeak/modelpricing-ai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file modelpricing_ai-2026.2.14-py3-none-any.whl.

File metadata

File hashes

Hashes for modelpricing_ai-2026.2.14-py3-none-any.whl
Algorithm Hash digest
SHA256 b77918e2739a506f43299ae42f3ae0c82ce14cda7cb46eab728ae87a508b1f7b
MD5 ecfebb11a0f5fe39162822d15cb8dd26
BLAKE2b-256 a920dae5b9d0f83f44d1086841ccd9827a43ec5cd8f4b35dab86d4636ba35fb8

See more details on using hashes here.

Provenance

The following attestation bundles were made for modelpricing_ai-2026.2.14-py3-none-any.whl:

Publisher: publish-python.yml on humanspeak/modelpricing-ai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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