Skip to content

core

Class info

🛈 DocStrings

Utilities for calculating token costs using LiteLLM pricing data.

calculate_token_cost async

calculate_token_cost(
    model: str,
    input_tokens: int | None,
    output_tokens: int | None,
    *,
    cache_read_tokens: int | None = None,
    cache_write_tokens: int | None = None,
    cache_timeout: int = _CACHE_TIMEOUT,
) -> TokenCosts | None

Calculate detailed costs for token usage based on model pricing.

Combines input and output token counts with their respective costs to calculate the breakdown of costs. If a token count is None, it will be treated as 0 tokens.

Parameters:

Name Type Description Default
model str

Name of the model used (e.g. "gpt-4", "openai:gpt-3.5-turbo")

required
input_tokens int | None

Number of tokens in the prompt/input, or None. Includes the cache read and cache write tokens (as pydantic-ai counts them).

required
output_tokens int | None

Number of tokens in the completion/output, or None

required
cache_read_tokens int | None

Input tokens read from the prompt cache, billed at the model's cache read price (the input price if it has none)

None
cache_write_tokens int | None

Input tokens written to the prompt cache, billed at the model's cache creation price (the input price if it has none)

None
cache_timeout int

Number of seconds to keep prices in cache (default: 24 hours)

_CACHE_TIMEOUT

Returns:

Type Description
TokenCosts | None

TokenCosts | None: Detailed cost breakdown if pricing data available. input_cost includes the cache read and write costs.

Source code in src/tokonomics/core.py
async def calculate_token_cost(
    model: str,
    input_tokens: int | None,
    output_tokens: int | None,
    *,
    cache_read_tokens: int | None = None,
    cache_write_tokens: int | None = None,
    cache_timeout: int = _CACHE_TIMEOUT,
) -> TokenCosts | None:
    """Calculate detailed costs for token usage based on model pricing.

    Combines input and output token counts with their respective costs to
    calculate the breakdown of costs. If a token count is None, it will
    be treated as 0 tokens.

    Args:
        model: Name of the model used (e.g. "gpt-4", "openai:gpt-3.5-turbo")
        input_tokens: Number of tokens in the prompt/input, or None. Includes the
            cache read and cache write tokens (as pydantic-ai counts them).
        output_tokens: Number of tokens in the completion/output, or None
        cache_read_tokens: Input tokens read from the prompt cache, billed at the
            model's cache read price (the input price if it has none)
        cache_write_tokens: Input tokens written to the prompt cache, billed at the
            model's cache creation price (the input price if it has none)
        cache_timeout: Number of seconds to keep prices in cache (default: 24 hours)

    Returns:
        TokenCosts | None: Detailed cost breakdown if pricing data available.
            ``input_cost`` includes the cache read and write costs.
    """
    costs = await get_model_costs(model, cache_timeout=cache_timeout)
    if not costs:
        logger.debug("No costs found for model %r", model)
        return None

    input_count = input_tokens or 0
    output_count = output_tokens or 0
    read_count = cache_read_tokens or 0
    write_count = cache_write_tokens or 0
    prices = _tier_prices(costs, input_count)
    input_price = prices["input_cost_per_token"]
    uncached = max(input_count - read_count - write_count, 0)
    input_cost = (
        uncached * input_price
        + read_count * prices.get("cache_read_input_token_cost", input_price)
        + write_count * prices.get("cache_creation_input_token_cost", input_price)
    )
    output_cost = output_count * prices["output_cost_per_token"]

    token_costs = TokenCosts(input_cost=input_cost, output_cost=output_cost)

    logger.debug(
        "Cost calculation - prompt: $%.6f, completion: $%.6f, total: $%.6f",
        token_costs.input_cost,
        token_costs.output_cost,
        token_costs.total_cost,
    )
    return token_costs

get_available_models async

get_available_models(*, cache_timeout: int = _CACHE_TIMEOUT) -> list[str]

Get a list of all available model names from LiteLLM pricing data.

Parameters:

Name Type Description Default
cache_timeout int

Number of seconds to keep data in cache (default: 24 hours)

_CACHE_TIMEOUT

Returns:

Type Description
list[str]

list[str]: List of available model names, sorted alphabetically

Source code in src/tokonomics/core.py
async def get_available_models(
    *,
    cache_timeout: int = _CACHE_TIMEOUT,
) -> list[str]:
    """Get a list of all available model names from LiteLLM pricing data.

    Args:
        cache_timeout: Number of seconds to keep data in cache (default: 24 hours)

    Returns:
        list[str]: List of available model names, sorted alphabetically
    """
    try:
        table = await _get_table(cache_timeout)
    except Exception as e:
        error_msg = "Failed to get available models"
        logger.exception(error_msg)
        raise ValueError(error_msg) from e
    return sorted(table.models)

get_model_capabilities async

get_model_capabilities(
    model: str, *, cache_timeout: int = _CACHE_TIMEOUT
) -> ModelCapabilities | None

Get capabilities information for a model from LiteLLM data.

Parameters:

Name Type Description Default
model str

Name of the model to look up capabilities for

required
cache_timeout int

Number of seconds to keep data in cache (default: 24 hours)

_CACHE_TIMEOUT

Returns:

Type Description
ModelCapabilities | None

ModelCapabilities | None: Model's capabilities if found, None otherwise

Raises:

Type Description
ValueError

If there's an error fetching the capabilities data

Source code in src/tokonomics/core.py
async def get_model_capabilities(
    model: str,
    *,
    cache_timeout: int = _CACHE_TIMEOUT,
) -> ModelCapabilities | None:
    """Get capabilities information for a model from LiteLLM data.

    Args:
        model: Name of the model to look up capabilities for
        cache_timeout: Number of seconds to keep data in cache (default: 24 hours)

    Returns:
        ModelCapabilities | None: Model's capabilities if found, None otherwise

    Raises:
        ValueError: If there's an error fetching the capabilities data
    """
    try:
        table = await _get_table(cache_timeout)
    except Exception as e:
        error_msg = f"Failed to get model capabilities for {model}: {e}"
        logger.exception(error_msg)
        raise ValueError(error_msg) from e
    info = _find_entry(table, model)
    return _parse_capabilities(info) if info is not None else None

get_model_costs async

get_model_costs(model: str, *, cache_timeout: int = _CACHE_TIMEOUT) -> ModelCosts | None

Get cost information for a model from LiteLLM pricing data.

The LiteLLM table is downloaded once and kept for cache_timeout seconds; lookups of unknown models don't download it again.

Parameters:

Name Type Description Default
model str

Name of the model to look up costs for

required
cache_timeout int

Number of seconds to keep prices in cache (default: 24 hours)

_CACHE_TIMEOUT

Returns:

Type Description
ModelCosts | None

ModelCosts | None: Model's cost information if found, None otherwise

Source code in src/tokonomics/core.py
async def get_model_costs(
    model: str,
    *,
    cache_timeout: int = _CACHE_TIMEOUT,
) -> ModelCosts | None:
    """Get cost information for a model from LiteLLM pricing data.

    The LiteLLM table is downloaded once and kept for ``cache_timeout`` seconds; lookups
    of unknown models don't download it again.

    Args:
        model: Name of the model to look up costs for
        cache_timeout: Number of seconds to keep prices in cache (default: 24 hours)

    Returns:
        ModelCosts | None: Model's cost information if found, None otherwise
    """
    try:
        table = await _get_table(cache_timeout)
    except Exception as e:  # noqa: BLE001
        logger.debug("Failed to get model costs for %r: %s", model, e)
        return None
    info = _find_entry(table, model)
    return _parse_costs(info) if info is not None else None

reset_cache

reset_cache() -> None

Clear all cached pricing and limit data.

Source code in src/tokonomics/core.py
def reset_cache() -> None:
    """Clear all cached pricing and limit data."""
    global _table
    with _lock:
        _table = None