Skip to main content

genai-prices

CI Coverage PyPI versions license Join Slack

Python package for github.com/pydantic/genai-prices.

Installation

uv add genai-prices

(or pip install genai-prices if you're old school)

To use the CLI with Rich output/help, install the optional CLI dependencies:

uv add "genai-prices[cli]"

(or pip install "genai-prices[cli]")

Warning: these prices will not be 100% accurate

See the project README for more information.

Usage

calc_price

from genai_prices import Usage, calc_price

price_data = calc_price(
    Usage(input_tokens=1000, output_tokens=100),
    model_ref='gpt-4o',
    provider_id='openai',
)
print(f"Total Price: ${price_data.total_price} (input: ${price_data.input_price}, output: ${price_data.output_price})")

Request pricing context

from datetime import datetime, timezone

from genai_prices import Usage, calc_price

price = calc_price(
    Usage(input_tokens=1_000_000, output_tokens=1_000_000),
    model_ref='o3',
    provider_id='openai',
    genai_request_timestamp=datetime(2026, 10, 12, tzinfo=timezone.utc),
    price_context={'service_tier': 'flex'},
)
assert price.total_price == 5

You pass price_context explicitly to select request-specific prices. Its keys and values are strings. Use the service_tier reported in OpenAI's response. The response can report default after a priority request is downgraded. auto is a request setting and does not identify the rate you were charged.

OpenAI variants cover flex, priority, and fast where the published rate table supports them. default selects standard prices on these models. Omit the context for ordinary standard pricing. You can also pass it to ExtractedUsage.calc_price(), ModelInfo.calc_price(), and DataSnapshot.calc(). Extraction does not infer a pricing context. Tier variants are specific to their provider. If model lookup falls back to another provider, you receive the standard-price estimate; the fallback provider's tier rates are not applied.

If a context matches no variant, you receive the standard-price estimate. This includes unsupported models, unknown tiers, misspelled keys, and dates without verified tier rates. The bundled tier rates are verified from October 12, 2026; earlier tier history is not modeled.

Batch API

from datetime import datetime, timezone

from genai_prices import Usage, calc_price

price = calc_price(
    Usage(input_tokens=1_000_000, output_tokens=1_000_000),
    model_ref='o3',
    provider_id='openai',
    genai_request_timestamp=datetime(2026, 10, 14, tzinfo=timezone.utc),
    price_context={'processing': 'batch'},
)
assert price.total_price == 5

You pass {'processing': 'batch'} for usage from a provider's batch API. Most providers do not mark batch results in the response, so you set it yourself. Batch is a separate key from service_tier because it is a way of submitting requests, not a tier: OpenAI batch results report service_tier: "default".

Batch rates are bundled for Anthropic, OpenAI, Google, Mistral, Groq and xAI, verified from October 14, 2026. A model the provider does not serve in batch returns the standard-price estimate.

For perplexity/sonar, pass the search type used in the Perplexity request:

from genai_prices import Usage, calc_price

price = calc_price(
    Usage(web_searches=2),
    model_ref='perplexity/sonar',
    provider_id='perplexity',
    price_context={'search_type': 'fast'},
)
print(price.total_price)  # 0.0020

The response reports the search count but not the search type, so extraction cannot select the rate automatically. Pass search_type: fast even when a Perplexity preset selects Fast Search. Omitting the context or passing search_type: web uses the standard estimate of $2.50 per thousand searches. The fast rate is $1 per thousand. The search type selects the rate independently of the request date. Token charges are calculated separately. See Perplexity's web-search documentation.

Cached input tokens

from genai_prices import Usage, calc_price

price_data = calc_price(
    Usage(
        input_tokens=4740,
        cache_read_tokens=0,
        cache_write_tokens=4735,
        output_tokens=255,
    ),
    model_ref='claude-sonnet-4-20250514',
    provider_id='anthropic',
)
print(price_data.total_price)

input_tokens is the total number of input tokens. It includes uncached tokens, cache-read tokens, and cache-write tokens. You also report cache_read_tokens and cache_write_tokens so that calc_price can apply their separate rates.

Do not pass only the uncached count as input_tokens. Cache tokens are partitions of the total, so their combined count cannot exceed input_tokens.

extract_usage

extract_usage can be used to extract usage data and the model_ref from response data, which in turn can be used to calculate prices:

from genai_prices import extract_usage

response_data = {
    'model': 'claude-sonnet-4-20250514',
    'usage': {
        'input_tokens': 504,
        'cache_creation_input_tokens': 123,
        'cache_read_input_tokens': 0,
        'output_tokens': 97,
    },
}
extracted_usage = extract_usage(response_data, provider_id='anthropic')
price = extracted_usage.calc_price()
print(price.total_price)

or with OpenAI where there are two API flavors:

from genai_prices import extract_usage

response_data = {
    'model': 'gpt-5',
    'usage': {'prompt_tokens': 100, 'completion_tokens': 200},
}
extracted_usage = extract_usage(response_data, provider_id='openai', api_flavor='chat')
price = extracted_usage.calc_price()
print(price.total_price)

UpdatePrices

UpdatePrices can be used to periodically update the price data by downloading it from GitHub.

Please note:

  • this functionality is explicitly opt-in
  • we download data directly from GitHub (https://raw.githubusercontent.com/pydantic/genai-prices/refs/heads/main/prices/new_data/v2/data.json) so we don't and can't monitor requests or gather telemetry

At the time of writing, the v2 data.json file downloaded by UpdatePrices is around 51KB when compressed, so is generally very quick to download.

By default UpdatePrices downloads price data immediately after it's started in the background, then every hour after that.

Usage with UpdatePrices as a context manager:

from genai_prices import UpdatePrices, Usage, calc_price

with UpdatePrices() as update_prices:
    update_prices.wait()  # optionally wait for prices to have updated
    p = calc_price(Usage(input_tokens=123, output_tokens=456), 'gpt-5')
    print(p)

Usage with UpdatePrices as a simple class:

from genai_prices import UpdatePrices, Usage, calc_price

update_prices = UpdatePrices()
update_prices.start(wait=True)  # start updating prices, optionally wait for prices to have updated
p = calc_price(Usage(input_tokens=123, output_tokens=456), 'gpt-5')
print(p)
update_prices.stop()  # stop updating prices

All UpdatePrices instances use one background task. Each instance keeps the task running from start() until stop(). When an instance starts, it supplies the settings and fetch() method for future fetches. Calling start() again while that instance remains started has no effect unless wait is set. This lets libraries such as Logfire and Pydantic AI update prices without creating duplicate tasks. If you customize fetch(), start your instance after other libraries start theirs.

Fetch failures are logged. If the latest fetch failed, wait() raises its error while its instance is started. The global wait functions raise it while any instance is started. stop() does not wait for the task or raise fetch failures. The task exits when no instances are started and any current fetch is finished. Any prices returned by that fetch are used. Fetched prices stay in use; they never revert to the data bundled with the package.

If you'd like to wait for prices to be updated without access to the UpdatePrices instance, you can use the wait_prices_updated_sync function:

from genai_prices import wait_prices_updated_sync

wait_prices_updated_sync()
...

Or its async variant, wait_prices_updated_async.

CLI Usage

Run the CLI with:

uvx genai-prices --help

Or, if installed locally, make sure CLI extras are present:

pip install "genai-prices[cli]"
genai-prices --help

If local CLI extras are not installed, the command will print an install hint for genai-prices[cli].

To list providers and models, run:

uvx genai-prices list

To calculate the price of models, run for example:

uvx genai-prices calc --input-tokens 100000 --output-tokens 3000 o1 o3 claude-opus-4

CLI output notes:

  • Rich output is the default.
  • Use --plain (-p) for legacy/plain output.
  • Use --no-color to keep rich formatting without colors.
  • Use -T / --table for wide table output.

Further Documentation

We do not yet build API documentation for this package, but the source code is relatively simple and well documented.

If you need further information on the API, we encourage you to read the source code.

Fractional usage values

Every reportable usage unit accepts finite non-negative integers or fractional values. For example, duration usage can include fractions of a second:

from decimal import Decimal

from genai_prices import Usage

duration = Usage(audio_seconds=0.1) + Usage(audio_seconds=0.2)
exact_duration = Usage(audio_seconds=Decimal('0.1')) + Usage(audio_seconds=0.2)

assert duration.audio_seconds == 0.3
assert type(duration.audio_seconds) is float
assert exact_duration.audio_seconds == Decimal('0.3')
assert type(Usage(audio_seconds=3.0).audio_seconds) is float

Python preserves supplied int, float, and Decimal values, including 3.0 as a float. Other accepted non-boolean integer implementations normalize to built-in int. Arithmetic interprets floats through their shortest round-trippable decimal spellings: a result is Decimal if any operand was Decimal, otherwise float if any operand was float, otherwise int. This cannot recover decimal precision that was already lost before a float reached Usage.

Standard JSON decoding normally supplies int and float, while callers may request Decimal parsing before extraction. Decimal-bearing usage is not serializable by Python's standard JSON encoder without a custom conversion.

For Groq's Whisper models, report the transcription duration as audio_seconds or input_audio_seconds. These models apply Groq's documented 10-second minimum. A missing or zero duration costs zero.

Metadata

Release files for genai-prices 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for genai-prices 0.2.0
File Size Uploaded Provenance Actions
genai_prices-0.2.0.tar.gz 159.0 kB Without provenance Details for genai_prices-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for genai-prices 0.2.0
File Interpreter ABI Platform Actions
genai_prices-0.2.0-py3-none-any.whl Python 3 none any Details for genai_prices-0.2.0-py3-none-any.whl

Total release size: 327.2 kB

Release files / genai_prices-0.2.0.tar.gz

Download URL genai_prices-0.2.0.tar.gz
Size 159.0 kB
Tags Source
SHA-256 checksum
How to use checksums
a0e92059e96492f2ffe55fa708908fe2fc0afe11d111f8051106d52ae8fd9c12
BLAKE2b-256 checksum
How to use checksums
db9395297c8b37f0deec1780d7579e85915fd7fe4dbe0da38cb79bc0fcc16a2a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.1 {"installer":{"name":"uv","version":"0.12.1","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 / genai_prices-0.2.0-py3-none-any.whl

Download URL genai_prices-0.2.0-py3-none-any.whl
Size 168.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
21ede75742043b3489a6cec3ad5722782640b34676563c6c755b52061812e6a3
BLAKE2b-256 checksum
How to use checksums
0e2ac2369565aa7dde5ea33de724acae7cc753f9d19239daea0000779102f4b5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.1 {"installer":{"name":"uv","version":"0.12.1","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 genai-prices 0.2.0

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.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page