Skip to content

tokonomics

Class info

Re-exported classes

Class Module Description
CopilotTokenManager tokonomics.model_discovery.copilot_provider.token_manager Manager for GitHub Copilot API tokens.
GroqProvider tokonomics.model_discovery.groq_provider.provider Groq API provider.
MistralProvider tokonomics.model_discovery.mistral_provider.provider Mistral AI API provider.
ModelCostTier tokonomics.toko_types Prices that apply to a request above a prompt size (LiteLLM's *_above_<N>k_tokens).
ModelCosts tokonomics.toko_types Cost information for a model.
ModelInfo tokonomics.model_discovery.model_info Unified model information from various providers.
ModelPricing tokonomics.model_discovery.model_info Pricing information for a model.
ModelProvider tokonomics.model_discovery.base Base class for model providers.
OpenRouterProvider tokonomics.model_discovery.openrouter_provider.provider OpenRouter API provider.
TokenCosts tokonomics.toko_types Detailed breakdown of token costs.
Usage tokonomics.pydanticai_cost Protocol matching pydantic-ai's Usage object structure.

🛈 DocStrings

Tokonomics: main package.

Calcuate costs for LLM Usage based on token count.

CopilotTokenManager

Manager for GitHub Copilot API tokens.

Source code in src/tokonomics/model_discovery/copilot_provider/token_manager.py
class CopilotTokenManager:
    """Manager for GitHub Copilot API tokens."""

    def __init__(self) -> None:
        self._github_oauth_token = os.environ.get("GITHUB_COPILOT_API_KEY")
        self._copilot_token = None
        self._token_expires_at = datetime.now()
        # Guards the token state and the per-loop locks; never held across an await.
        self._token_lock = threading.Lock()
        self._async_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = (
            weakref.WeakKeyDictionary()
        )
        self._api_endpoint = "https://api.githubcopilot.com"

    def _needs_refresh(self) -> bool:
        return self._copilot_token is None or datetime.now() > self._token_expires_at - DELTA

    def _refresh_lock(self) -> asyncio.Lock:
        """Return the asyncio lock for the running loop (one per loop, created lazily)."""
        loop = asyncio.get_running_loop()
        with self._token_lock:
            lock = self._async_locks.get(loop)
            if lock is None:
                lock = self._async_locks[loop] = asyncio.Lock()
            return lock

    async def get_token(self) -> str:
        """Get a valid Copilot token, refreshing if needed."""
        import anyenv

        if not self._needs_refresh():
            assert self._copilot_token
            return self._copilot_token
        # An asyncio lock, not the thread lock: holding a threading.Lock across the
        # await would block the whole event loop when a second coroutine waits on it.
        async with self._refresh_lock():
            if self._needs_refresh():
                if not self._github_oauth_token:
                    msg = "GitHub OAuth token not found in GITHUB_COPILOT_API_KEY env var"
                    raise RuntimeError(msg)

                try:
                    logger.debug("Fetching fresh GitHub Copilot token")
                    data = await anyenv.get_json(
                        BASE_URL,
                        headers=get_token_headers(self._github_oauth_token),
                        return_type=dict,
                    )
                except Exception as e:
                    logger.exception("Failed to refresh GitHub Copilot token")
                    if not self._copilot_token:
                        msg = "Failed to obtain GitHub Copilot token"
                        raise RuntimeError(msg) from e
                else:
                    with self._token_lock:
                        self.handle_token_response(data)
            assert self._copilot_token, "Copilot token is missing"
            return self._copilot_token

    def get_token_sync(self) -> str:
        """Get a valid Copilot token, refreshing if needed."""
        import anyenv

        with self._token_lock:
            # If token is missing or expires in less than buffer time, refresh it
            if self._needs_refresh():
                if not self._github_oauth_token:
                    msg = "GitHub OAuth token not found in GITHUB_COPILOT_API_KEY env var"
                    raise RuntimeError(msg)

                try:
                    logger.debug("Fetching fresh GitHub Copilot token")
                    data = anyenv.get_json_sync(
                        BASE_URL,
                        headers=get_token_headers(self._github_oauth_token),
                        return_type=dict,
                    )
                except Exception as e:
                    logger.exception("Failed to refresh GitHub Copilot token")
                    if not self._copilot_token:
                        msg = "Failed to obtain GitHub Copilot token"
                        raise RuntimeError(msg) from e
                else:
                    self.handle_token_response(data)
            assert self._copilot_token, "Copilot token is missing"
            return self._copilot_token

    def handle_token_response(self, data: dict[str, Any]) -> None:
        self._copilot_token = data.get("token")
        if not self._copilot_token:
            msg = "No token found in response from Copilot API"
            raise RuntimeError(msg)
        if expires_at := data.get("expires_at"):
            self._token_expires_at = datetime.fromtimestamp(expires_at)
        else:
            # Default expiry: 25 minutes if not specified
            self._token_expires_at = datetime.now() + timedelta(minutes=25)
        if "api" in (endpoints := data.get("endpoints", {})):
            self._api_endpoint = endpoints["api"]
        expires_at = self._token_expires_at.isoformat()
        logger.debug("Copilot token refreshed, valid until: %s", expires_at)

    def is_available(self) -> bool:
        """Check whether the token manager is available for use."""
        return bool(self._github_oauth_token)

    async def generate_headers(self) -> dict[str, str]:
        """Generate headers for GitHub Copilot API requests."""
        return {
            "Authorization": f"Bearer {await self.get_token()}",
            "User-Agent": USER_AGENT,
            "Editor-Version": EDITOR_VERSION,
            "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,
            "Copilot-Integration-Id": COPILOT_INTEGRATION_ID,
            "Openai-Intent": "conversation-edits",
            "X-Initiator": "user",
        }

generate_headers async

generate_headers() -> dict[str, str]

Generate headers for GitHub Copilot API requests.

Source code in src/tokonomics/model_discovery/copilot_provider/token_manager.py
async def generate_headers(self) -> dict[str, str]:
    """Generate headers for GitHub Copilot API requests."""
    return {
        "Authorization": f"Bearer {await self.get_token()}",
        "User-Agent": USER_AGENT,
        "Editor-Version": EDITOR_VERSION,
        "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,
        "Copilot-Integration-Id": COPILOT_INTEGRATION_ID,
        "Openai-Intent": "conversation-edits",
        "X-Initiator": "user",
    }

get_token async

get_token() -> str

Get a valid Copilot token, refreshing if needed.

Source code in src/tokonomics/model_discovery/copilot_provider/token_manager.py
async def get_token(self) -> str:
    """Get a valid Copilot token, refreshing if needed."""
    import anyenv

    if not self._needs_refresh():
        assert self._copilot_token
        return self._copilot_token
    # An asyncio lock, not the thread lock: holding a threading.Lock across the
    # await would block the whole event loop when a second coroutine waits on it.
    async with self._refresh_lock():
        if self._needs_refresh():
            if not self._github_oauth_token:
                msg = "GitHub OAuth token not found in GITHUB_COPILOT_API_KEY env var"
                raise RuntimeError(msg)

            try:
                logger.debug("Fetching fresh GitHub Copilot token")
                data = await anyenv.get_json(
                    BASE_URL,
                    headers=get_token_headers(self._github_oauth_token),
                    return_type=dict,
                )
            except Exception as e:
                logger.exception("Failed to refresh GitHub Copilot token")
                if not self._copilot_token:
                    msg = "Failed to obtain GitHub Copilot token"
                    raise RuntimeError(msg) from e
            else:
                with self._token_lock:
                    self.handle_token_response(data)
        assert self._copilot_token, "Copilot token is missing"
        return self._copilot_token

get_token_sync

get_token_sync() -> str

Get a valid Copilot token, refreshing if needed.

Source code in src/tokonomics/model_discovery/copilot_provider/token_manager.py
def get_token_sync(self) -> str:
    """Get a valid Copilot token, refreshing if needed."""
    import anyenv

    with self._token_lock:
        # If token is missing or expires in less than buffer time, refresh it
        if self._needs_refresh():
            if not self._github_oauth_token:
                msg = "GitHub OAuth token not found in GITHUB_COPILOT_API_KEY env var"
                raise RuntimeError(msg)

            try:
                logger.debug("Fetching fresh GitHub Copilot token")
                data = anyenv.get_json_sync(
                    BASE_URL,
                    headers=get_token_headers(self._github_oauth_token),
                    return_type=dict,
                )
            except Exception as e:
                logger.exception("Failed to refresh GitHub Copilot token")
                if not self._copilot_token:
                    msg = "Failed to obtain GitHub Copilot token"
                    raise RuntimeError(msg) from e
            else:
                self.handle_token_response(data)
        assert self._copilot_token, "Copilot token is missing"
        return self._copilot_token

is_available

is_available() -> bool

Check whether the token manager is available for use.

Source code in src/tokonomics/model_discovery/copilot_provider/token_manager.py
def is_available(self) -> bool:
    """Check whether the token manager is available for use."""
    return bool(self._github_oauth_token)

GroqProvider

Bases: ModelProvider

Groq API provider.

Source code in src/tokonomics/model_discovery/groq_provider/provider.py
class GroqProvider(ModelProvider):
    """Groq API provider."""

    def __init__(self, api_key: str | None = None):
        super().__init__()
        self.api_key = api_key or os.environ.get("GROQ_API_KEY")
        if not self.api_key:
            msg = "Groq API key not found in parameters or GROQ_API_KEY env var"
            raise RuntimeError(msg)

        self.base_url = "https://api.groq.com/openai/v1"
        self.headers = {"Authorization": f"Bearer {self.api_key}"}
        self.params = {}

    def is_available(self) -> bool:
        """Check whether the provider is available for use."""
        return bool(self.api_key)

    def _parse_model(self, data: dict[str, Any]) -> ModelInfo:
        """Parse Groq API response into ModelInfo."""
        return ModelInfo(
            id=str(data["id"]),
            name=str(data.get("name", data["id"])),
            provider="groq",
            owned_by=str(data["owned_by"]),
            context_window=int(data["context_window"]),
            is_deprecated=not data.get("active", False),
        )

is_available

is_available() -> bool

Check whether the provider is available for use.

Source code in src/tokonomics/model_discovery/groq_provider/provider.py
def is_available(self) -> bool:
    """Check whether the provider is available for use."""
    return bool(self.api_key)

MistralProvider

Bases: ModelProvider

Mistral AI API provider.

Source code in src/tokonomics/model_discovery/mistral_provider/provider.py
class MistralProvider(ModelProvider):
    """Mistral AI API provider."""

    def __init__(self, api_key: str | None = None):
        super().__init__()
        self.api_key = api_key or os.environ.get("MISTRAL_API_KEY")
        if not self.api_key:
            msg = "Mistral API key not found in parameters or MISTRAL_API_KEY env var"
            raise RuntimeError(msg)

        self.base_url = "https://api.mistral.ai/v1"
        self.headers = {"Authorization": f"Bearer {self.api_key}"}
        self.params = {}

    def is_available(self) -> bool:
        """Check whether the provider is available for use."""
        return bool(self.api_key)

    def _parse_model(self, data: dict[str, Any]) -> ModelInfo:
        """Parse Mistral API response into ModelInfo."""
        # Extract capabilities
        capabilities = data.get("capabilities", {})

        # Determine if model is an embedding model
        is_embedding = False
        model_id = str(data["id"]).lower()
        model_name = str(data.get("name", data["id"])).lower()

        if (
            "embed" in model_id
            or "embed" in model_name
            or (
                not capabilities.get("completion_chat", True)
                and not capabilities.get("function_calling", True)
            )
        ):
            is_embedding = True

        # Determine input/output modalities
        input_modalities: set[Modality] = {"text"}
        if capabilities.get("vision"):
            input_modalities.add("image")
        if capabilities.get("ocr"):
            input_modalities.add("file")
        if capabilities.get("audio"):
            input_modalities.add("audio")

        return ModelInfo(
            id=str(data["id"]),
            name=str(data.get("name", data["id"])),
            provider="mistral",
            owned_by=str(data.get("owned_by")),
            description=str(data.get("description")),
            context_window=int(data.get("max_context_length", 0)),
            is_deprecated=bool(data.get("deprecation")),
            is_embedding=is_embedding,
            input_modalities=input_modalities,
        )

is_available

is_available() -> bool

Check whether the provider is available for use.

Source code in src/tokonomics/model_discovery/mistral_provider/provider.py
def is_available(self) -> bool:
    """Check whether the provider is available for use."""
    return bool(self.api_key)

ModelCostTier

Bases: TypedDict

Prices that apply to a request above a prompt size (LiteLLM's *_above_<N>k_tokens).

Source code in src/tokonomics/toko_types.py
class ModelCostTier(TypedDict, total=False):
    """Prices that apply to a request above a prompt size (LiteLLM's ``*_above_<N>k_tokens``)."""

    input_cost_per_token: Decimal
    output_cost_per_token: Decimal
    cache_read_input_token_cost: Decimal
    cache_creation_input_token_cost: Decimal

ModelCosts

Bases: TypedDict

Cost information for a model.

Source code in src/tokonomics/toko_types.py
class ModelCosts(TypedDict):
    """Cost information for a model."""

    input_cost_per_token: Decimal
    output_cost_per_token: Decimal
    cache_read_input_token_cost: NotRequired[Decimal]
    """Price of an input token read from the prompt cache."""
    cache_creation_input_token_cost: NotRequired[Decimal]
    """Price of an input token written to the prompt cache."""
    tiers: NotRequired[dict[int, ModelCostTier]]
    """Prompt-size threshold (tokens) -> prices for requests with more input tokens."""

cache_creation_input_token_cost instance-attribute

cache_creation_input_token_cost: NotRequired[Decimal]

Price of an input token written to the prompt cache.

cache_read_input_token_cost instance-attribute

cache_read_input_token_cost: NotRequired[Decimal]

Price of an input token read from the prompt cache.

tiers instance-attribute

tiers: NotRequired[dict[int, ModelCostTier]]

Prompt-size threshold (tokens) -> prices for requests with more input tokens.

ModelInfo dataclass

Unified model information from various providers.

Source code in src/tokonomics/model_discovery/model_info.py
@dataclass
class ModelInfo:
    """Unified model information from various providers."""

    id: str
    """Unique identifier for the model."""
    name: str
    """Display name of the model."""
    provider: str = ""
    """Service provider name (e.g. OpenAI, Anthropic)."""
    description: str | None = None
    """Detailed description of the model's capabilities."""
    pricing: ModelPricing | None = None
    """Pricing information for using the model."""
    owned_by: str | None = None
    """Organization that owns/created the model."""
    context_window: int | None = None
    """Maximum number of tokens that can be processed in one request."""
    is_deprecated: bool = False
    """Whether this model version is deprecated."""
    is_embedding: bool = False
    """Whether this model is primarily used for creating embeddings."""
    max_output_tokens: int | None = None
    """Maximum number of tokens the model can generate in a response."""
    input_modalities: set[Modality] = field(default_factory=lambda: {"text"})
    """Supported input modalities (text, image, audio, video, etc.)."""
    output_modalities: set[Modality] = field(default_factory=lambda: {"text"})
    """Supported output modalities (text, image, audio, video, etc.)."""
    is_free: bool = False
    """Whether this model is free to use."""
    created_at: datetime | None = None
    """Timestamp when the model was created/released."""
    metadata: dict[str, Any] = field(default_factory=dict)
    """Provider-specific metadata that doesn't fit in standard fields."""
    id_override: str | None = None
    """Optional override for the model ID used in API calls.

    When set, this value is used instead of the auto-generated pydantic_ai_id.
    Useful for agents like Claude Code that need simple IDs (e.g., 'opus', 'sonnet').
    """

    @property
    def pydantic_ai_id(self) -> str:
        """Unique pydantic-ai style identifier for the model.

        Returns id_override if set, otherwise returns '{provider}:{id}'.
        """
        if self.id_override is not None:
            return self.id_override
        if self.provider:
            return f"{self.provider}:{self.id}"
        return self.id

    @property
    def litellm_id(self) -> str:
        """Unique litellm style identifier for the model."""
        return f"{self.provider}/{self.id}"

    @property
    def pydantic_ai_variants(self) -> dict[str, dict[str, Any]]:
        """Thinking level variants as pydantic-ai ModelSettings.

        Returns a dict mapping variant name (e.g., 'high', 'max') to
        provider-specific model settings for that thinking level.

        Only populated for models that support reasoning/thinking
        (based on metadata from models.dev).

        Returns:
            Dict mapping variant name to ModelSettings dict.
            Empty dict if model doesn't support reasoning variants.
        """
        from tokonomics.model_discovery.variants import get_pydantic_ai_variants

        supports_reasoning = self.metadata.get("reasoning", False)
        return get_pydantic_ai_variants(self.provider, self.id, supports_reasoning)

    @property
    def iconify_icon(self) -> str | None:  # noqa: PLR0911
        """Iconify icon for the model."""
        name = self.name.lower()
        if name.startswith("mistral"):
            return "logos:mistral-ai"
        if name.startswith("openai"):
            return "logos:openai"
        if name.startswith("claude"):
            return "logos:anthropic"
        if name.startswith("perplexity"):
            return "logos:perplexity"
        if name.startswith("hugging"):
            return "logos:hugging-face"
        if name.startswith("deepseek"):
            return "arcticons:deepseek"

        return None

    def format(self) -> str:
        """Format model information as a human-readable string.

        Returns:
            str: Formatted model information
        """
        lines: list[str] = []

        # Basic info
        lines.append(f"Model: {self.name}")
        lines.append(f"Provider: {self.provider}")
        lines.append(f"ID: {self.id}")

        # Optional fields
        if self.owned_by:
            lines.append(f"Owned by: {self.owned_by}")

        if self.context_window:
            lines.append(f"Context window: {self.context_window:,} tokens")

        if self.max_output_tokens:
            lines.append(f"Max output tokens: {self.max_output_tokens:,}")

        if self.pricing:
            if self.pricing.prompt is not None:
                lines.append(f"Prompt cost: ${self.pricing.prompt:.6f}/token")
            if self.pricing.completion is not None:
                lines.append(f"Completion cost: ${self.pricing.completion:.6f}/token")
            if self.pricing.image is not None and self.pricing.image > 0:
                lines.append(f"Image cost: ${self.pricing.image:.6f}/image")
            if self.pricing.request is not None and self.pricing.request > 0:
                lines.append(f"Request cost: ${self.pricing.request:.6f}/request")
            if self.pricing.web_search is not None and self.pricing.web_search > 0:
                lines.append(f"Web search cost: ${self.pricing.web_search:.6f}")
            if self.pricing.internal_reasoning is not None and self.pricing.internal_reasoning > 0:
                lines.append(f"Internal reasoning cost: ${self.pricing.internal_reasoning:.6f}")

        if self.input_modalities and self.input_modalities != {"text"}:
            lines.append(f"Input modalities: {', '.join(self.input_modalities)}")

        if self.output_modalities and self.output_modalities != {"text"}:
            lines.append(f"Output modalities: {', '.join(self.output_modalities)}")

        if self.description:
            lines.append("\nDescription:")
            lines.append(self.description)

        if self.is_deprecated:
            lines.append("\n⚠️ This model is deprecated")

        if self.created_at:
            lines.append(f"Created: {self.created_at.strftime('%Y-%m-%d')}")

        # Add any relevant metadata
        if self.metadata and any(self.metadata.values()):
            lines.append("\nAdditional Information:")
            for key, value in self.metadata.items():
                if key == "supported_parameters" and value:
                    lines.append(f"- Supported parameters: {', '.join(str(v) for v in value)}")
                elif key == "hugging_face_id" and value:
                    lines.append(f"- HuggingFace ID: {value}")
                elif key == "tokenizer" and value:
                    lines.append(f"- Tokenizer: {value}")
                elif key == "is_moderated" and value:
                    lines.append(f"- Moderated: {value}")
                elif isinstance(value, list | set) and value:
                    vals = ", ".join(str(v) for v in value)
                    lines.append(f"- {key.replace('_', ' ').title()}: {vals}")
                elif value:
                    lines.append(f"- {key.replace('_', ' ').title()}: {value}")

        return "\n".join(lines)

context_window class-attribute instance-attribute

context_window: int | None = None

Maximum number of tokens that can be processed in one request.

created_at class-attribute instance-attribute

created_at: datetime | None = None

Timestamp when the model was created/released.

description class-attribute instance-attribute

description: str | None = None

Detailed description of the model's capabilities.

iconify_icon property

iconify_icon: str | None

Iconify icon for the model.

id instance-attribute

id: str

Unique identifier for the model.

id_override class-attribute instance-attribute

id_override: str | None = None

Optional override for the model ID used in API calls.

When set, this value is used instead of the auto-generated pydantic_ai_id. Useful for agents like Claude Code that need simple IDs (e.g., 'opus', 'sonnet').

input_modalities class-attribute instance-attribute

input_modalities: set[Modality] = field(default_factory=lambda: {'text'})

Supported input modalities (text, image, audio, video, etc.).

is_deprecated class-attribute instance-attribute

is_deprecated: bool = False

Whether this model version is deprecated.

is_embedding class-attribute instance-attribute

is_embedding: bool = False

Whether this model is primarily used for creating embeddings.

is_free class-attribute instance-attribute

is_free: bool = False

Whether this model is free to use.

litellm_id property

litellm_id: str

Unique litellm style identifier for the model.

max_output_tokens class-attribute instance-attribute

max_output_tokens: int | None = None

Maximum number of tokens the model can generate in a response.

metadata class-attribute instance-attribute

metadata: dict[str, Any] = field(default_factory=dict)

Provider-specific metadata that doesn't fit in standard fields.

name instance-attribute

name: str

Display name of the model.

output_modalities class-attribute instance-attribute

output_modalities: set[Modality] = field(default_factory=lambda: {'text'})

Supported output modalities (text, image, audio, video, etc.).

owned_by class-attribute instance-attribute

owned_by: str | None = None

Organization that owns/created the model.

pricing class-attribute instance-attribute

pricing: ModelPricing | None = None

Pricing information for using the model.

provider class-attribute instance-attribute

provider: str = ''

Service provider name (e.g. OpenAI, Anthropic).

pydantic_ai_id property

pydantic_ai_id: str

Unique pydantic-ai style identifier for the model.

Returns id_override if set, otherwise returns '{provider}:{id}'.

pydantic_ai_variants property

pydantic_ai_variants: dict[str, dict[str, Any]]

Thinking level variants as pydantic-ai ModelSettings.

Returns a dict mapping variant name (e.g., 'high', 'max') to provider-specific model settings for that thinking level.

Only populated for models that support reasoning/thinking (based on metadata from models.dev).

Returns:

Type Description
dict[str, dict[str, Any]]

Dict mapping variant name to ModelSettings dict.

dict[str, dict[str, Any]]

Empty dict if model doesn't support reasoning variants.

format

format() -> str

Format model information as a human-readable string.

Returns:

Name Type Description
str str

Formatted model information

Source code in src/tokonomics/model_discovery/model_info.py
def format(self) -> str:
    """Format model information as a human-readable string.

    Returns:
        str: Formatted model information
    """
    lines: list[str] = []

    # Basic info
    lines.append(f"Model: {self.name}")
    lines.append(f"Provider: {self.provider}")
    lines.append(f"ID: {self.id}")

    # Optional fields
    if self.owned_by:
        lines.append(f"Owned by: {self.owned_by}")

    if self.context_window:
        lines.append(f"Context window: {self.context_window:,} tokens")

    if self.max_output_tokens:
        lines.append(f"Max output tokens: {self.max_output_tokens:,}")

    if self.pricing:
        if self.pricing.prompt is not None:
            lines.append(f"Prompt cost: ${self.pricing.prompt:.6f}/token")
        if self.pricing.completion is not None:
            lines.append(f"Completion cost: ${self.pricing.completion:.6f}/token")
        if self.pricing.image is not None and self.pricing.image > 0:
            lines.append(f"Image cost: ${self.pricing.image:.6f}/image")
        if self.pricing.request is not None and self.pricing.request > 0:
            lines.append(f"Request cost: ${self.pricing.request:.6f}/request")
        if self.pricing.web_search is not None and self.pricing.web_search > 0:
            lines.append(f"Web search cost: ${self.pricing.web_search:.6f}")
        if self.pricing.internal_reasoning is not None and self.pricing.internal_reasoning > 0:
            lines.append(f"Internal reasoning cost: ${self.pricing.internal_reasoning:.6f}")

    if self.input_modalities and self.input_modalities != {"text"}:
        lines.append(f"Input modalities: {', '.join(self.input_modalities)}")

    if self.output_modalities and self.output_modalities != {"text"}:
        lines.append(f"Output modalities: {', '.join(self.output_modalities)}")

    if self.description:
        lines.append("\nDescription:")
        lines.append(self.description)

    if self.is_deprecated:
        lines.append("\n⚠️ This model is deprecated")

    if self.created_at:
        lines.append(f"Created: {self.created_at.strftime('%Y-%m-%d')}")

    # Add any relevant metadata
    if self.metadata and any(self.metadata.values()):
        lines.append("\nAdditional Information:")
        for key, value in self.metadata.items():
            if key == "supported_parameters" and value:
                lines.append(f"- Supported parameters: {', '.join(str(v) for v in value)}")
            elif key == "hugging_face_id" and value:
                lines.append(f"- HuggingFace ID: {value}")
            elif key == "tokenizer" and value:
                lines.append(f"- Tokenizer: {value}")
            elif key == "is_moderated" and value:
                lines.append(f"- Moderated: {value}")
            elif isinstance(value, list | set) and value:
                vals = ", ".join(str(v) for v in value)
                lines.append(f"- {key.replace('_', ' ').title()}: {vals}")
            elif value:
                lines.append(f"- {key.replace('_', ' ').title()}: {value}")

    return "\n".join(lines)

ModelPricing dataclass

Pricing information for a model.

Source code in src/tokonomics/model_discovery/model_info.py
@dataclass
class ModelPricing:
    """Pricing information for a model."""

    prompt: float | None = None
    """Cost per token for prompt inputs."""
    completion: float | None = None
    """Cost per token for completion outputs."""
    image: float | None = None
    """Cost per image for input processing."""
    request: float | None = None
    """Cost per request."""
    input_cache_read: float | None = None
    """Cost for reading from input cache."""
    input_cache_write: float | None = None
    """Cost for writing to input cache."""
    web_search: float | None = None
    """Cost for web search functionality."""
    internal_reasoning: float | None = None
    """Cost for internal reasoning functionality."""

completion class-attribute instance-attribute

completion: float | None = None

Cost per token for completion outputs.

image class-attribute instance-attribute

image: float | None = None

Cost per image for input processing.

input_cache_read class-attribute instance-attribute

input_cache_read: float | None = None

Cost for reading from input cache.

input_cache_write class-attribute instance-attribute

input_cache_write: float | None = None

Cost for writing to input cache.

internal_reasoning class-attribute instance-attribute

internal_reasoning: float | None = None

Cost for internal reasoning functionality.

prompt class-attribute instance-attribute

prompt: float | None = None

Cost per token for prompt inputs.

request class-attribute instance-attribute

request: float | None = None

Cost per request.

web_search: float | None = None

Cost for web search functionality.

ModelProvider

Bases: ABC

Base class for model providers.

Source code in src/tokonomics/model_discovery/base.py
class ModelProvider(ABC):
    """Base class for model providers."""

    models_cache_ttl: float = MODELS_CACHE_TTL
    """Seconds discovery reuses this provider's parsed model list in memory."""

    def __init__(self) -> None:
        self.base_url: str
        self.headers: dict[str, str] = {}
        self.params: dict[str, Any] = {}

    @abstractmethod
    def is_available(self) -> bool:
        """Check whether the provider is available for use."""

    @abstractmethod
    def _parse_model(self, data: dict[str, Any]) -> ModelInfo:
        """Parse provider-specific API response into ModelInfo."""

    async def get_models(self) -> list[ModelInfo]:
        """Fetch available models from the provider asynchronously."""
        from anyenv import HttpError, get_json

        try:
            data = await get_json(
                f"{self.base_url}/models",
                headers=self.headers,
                params=self.params,
                cache=True,
                cache_ttl=MODELS_CACHE_TTL,
                return_type=dict,
            )

            if not isinstance(data, dict) or "data" not in data:
                msg = f"Invalid response format from {self.__class__.__name__}"
                raise RuntimeError(msg)

            return [self._parse_model(item) for item in data["data"]]

        except HttpError as e:
            msg = f"Failed to fetch models from {self.__class__.__name__}: {e}"
            raise RuntimeError(msg) from e

models_cache_ttl class-attribute instance-attribute

models_cache_ttl: float = MODELS_CACHE_TTL

Seconds discovery reuses this provider's parsed model list in memory.

get_models async

get_models() -> list[ModelInfo]

Fetch available models from the provider asynchronously.

Source code in src/tokonomics/model_discovery/base.py
async def get_models(self) -> list[ModelInfo]:
    """Fetch available models from the provider asynchronously."""
    from anyenv import HttpError, get_json

    try:
        data = await get_json(
            f"{self.base_url}/models",
            headers=self.headers,
            params=self.params,
            cache=True,
            cache_ttl=MODELS_CACHE_TTL,
            return_type=dict,
        )

        if not isinstance(data, dict) or "data" not in data:
            msg = f"Invalid response format from {self.__class__.__name__}"
            raise RuntimeError(msg)

        return [self._parse_model(item) for item in data["data"]]

    except HttpError as e:
        msg = f"Failed to fetch models from {self.__class__.__name__}: {e}"
        raise RuntimeError(msg) from e

is_available abstractmethod

is_available() -> bool

Check whether the provider is available for use.

Source code in src/tokonomics/model_discovery/base.py
@abstractmethod
def is_available(self) -> bool:
    """Check whether the provider is available for use."""

OpenRouterProvider

Bases: ModelProvider

OpenRouter API provider.

Source code in src/tokonomics/model_discovery/openrouter_provider/provider.py
class OpenRouterProvider(ModelProvider):
    """OpenRouter API provider."""

    def __init__(self, api_key: str | None = None) -> None:
        super().__init__()
        self.api_key = api_key or os.environ.get("OPENROUTER_API_KEY")
        self.base_url = "https://openrouter.ai/api/v1"
        self.headers = {"HTTP-Referer": "https://github.com/phi-ai"}

        if self.api_key:
            self.headers["Authorization"] = f"Bearer {self.api_key}"

        self.params = {}

    def is_available(self) -> bool:
        """Check whether the provider is available for use."""
        return bool(self.api_key)

    def _parse_model(self, data: dict[str, Any]) -> ModelInfo:
        """Parse OpenRouter API response into ModelInfo."""
        pricing = ModelPricing(
            prompt=float(data["pricing"]["prompt"]),
            completion=float(data["pricing"]["completion"]),
            image=float(data["pricing"].get("image", 0)) if "image" in data["pricing"] else None,
            request=float(data["pricing"].get("request", 0))
            if "request" in data["pricing"]
            else None,
            input_cache_read=float(data["pricing"].get("input_cache_read", 0))
            if "input_cache_read" in data["pricing"]
            else None,
            input_cache_write=float(data["pricing"].get("input_cache_write", 0))
            if "input_cache_write" in data["pricing"]
            else None,
            web_search=float(data["pricing"].get("web_search", 0))
            if "web_search" in data["pricing"]
            else None,
            internal_reasoning=float(data["pricing"].get("internal_reasoning", 0))
            if "internal_reasoning" in data["pricing"]
            else None,
        )
        model_id = str(data["id"])
        is_free = model_id.endswith(":free")

        # Extract modalities if available
        input_modalities: set[Modality] = {"text"}
        output_modalities: set[Modality] = {"text"}

        if architecture := data.get("architecture"):
            if input_mods := architecture.get("input_modalities"):
                input_modalities = {cast(Modality, m) for m in input_mods}
            if output_mods := architecture.get("output_modalities"):
                output_modalities = {cast(Modality, m) for m in output_mods}

        # Parse context length and created timestamp
        context_window = data.get("context_length")
        created_at = None
        if created_timestamp := data.get("created"):
            with contextlib.suppress(ValueError, TypeError, OverflowError):
                created_at = datetime.fromtimestamp(created_timestamp)

        # Extract additional fields
        hugging_face_id = data.get("hugging_face_id")

        # Check for top_provider info
        is_moderated = False
        if top_provider := data.get("top_provider"):
            is_moderated = top_provider.get("is_moderated", False)

        # Get supported parameters if available
        supported_parameters = data.get("supported_parameters", [])

        # Prepare metadata dictionary for OpenRouter-specific fields
        metadata = {
            "hugging_face_id": hugging_face_id,
            "is_moderated": is_moderated,
            "supported_parameters": supported_parameters,
        }

        # Add per_request_limits if available
        if per_request_limits := data.get("per_request_limits"):
            metadata["per_request_limits"] = per_request_limits

        # Add tokenizer info if available
        if (architecture := data.get("architecture")) and (
            tokenizer := architecture.get("tokenizer")
        ):
            metadata["tokenizer"] = tokenizer

        return ModelInfo(
            id=str(data["id"]),
            name=str(data["name"]),
            provider="openrouter",
            description=str(data.get("description")),
            pricing=pricing,
            is_free=is_free,
            context_window=context_window,
            input_modalities=input_modalities,
            output_modalities=output_modalities,
            owned_by=hugging_face_id,  # Use hugging_face_id as the owner when available
            created_at=created_at,
            metadata=metadata,
        )

is_available

is_available() -> bool

Check whether the provider is available for use.

Source code in src/tokonomics/model_discovery/openrouter_provider/provider.py
def is_available(self) -> bool:
    """Check whether the provider is available for use."""
    return bool(self.api_key)

TokenCosts dataclass

Detailed breakdown of token costs.

Source code in src/tokonomics/toko_types.py
@dataclass(frozen=True, slots=True)
class TokenCosts:
    """Detailed breakdown of token costs."""

    input_cost: Decimal
    """Cost for prompt tokens"""
    output_cost: Decimal
    """Cost for completion tokens"""

    @property
    def total_cost(self) -> Decimal:
        """Calculate total cost as sum of input and output costs."""
        return self.input_cost + self.output_cost

input_cost instance-attribute

input_cost: Decimal

Cost for prompt tokens

output_cost instance-attribute

output_cost: Decimal

Cost for completion tokens

total_cost property

total_cost: Decimal

Calculate total cost as sum of input and output costs.

Usage

Bases: Protocol

Protocol matching pydantic-ai's Usage object structure.

Source code in src/tokonomics/pydanticai_cost.py
@runtime_checkable
class Usage(Protocol):
    """Protocol matching pydantic-ai's Usage object structure."""

    input_tokens: int
    """Number of tokens in the request/prompt"""
    output_tokens: int
    """Number of tokens in the response/completion"""

    @property
    def total_tokens(self) -> int:
        """Total number of tokens used."""
        ...

input_tokens instance-attribute

input_tokens: int

Number of tokens in the request/prompt

output_tokens instance-attribute

output_tokens: int

Number of tokens in the response/completion

total_tokens property

total_tokens: int

Total number of tokens used.

calculate_pydantic_cost async

calculate_pydantic_cost(model: str, usage: None, *, cache_timeout: int = 86400) -> None
calculate_pydantic_cost(
    model: str, usage: Usage, *, cache_timeout: int = 86400
) -> TokenCosts | None
calculate_pydantic_cost(
    model: str, usage: Usage | None, *, cache_timeout: int = 86400
) -> TokenCosts | None

Calculate costs from a pydantic-ai Usage object.

Parameters:

Name Type Description Default
model str

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

required
usage Usage | None

Token usage information from pydantic-ai

required
cache_timeout int

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

86400

Returns:

Type Description
TokenCosts | None

TokenCosts | None: Detailed cost breakdown if pricing data available

Source code in src/tokonomics/pydanticai_cost.py
async def calculate_pydantic_cost(
    model: str,
    usage: Usage | None,
    *,
    cache_timeout: int = 86400,
) -> TokenCosts | None:
    """Calculate costs from a pydantic-ai Usage object.

    Args:
        model: Name of the model used (e.g. "gpt-4", "openai:gpt-3.5-turbo")
        usage: Token usage information from pydantic-ai
        cache_timeout: Number of seconds to keep prices in cache (default: 24 hours)

    Returns:
        TokenCosts | None: Detailed cost breakdown if pricing data available
    """
    if not usage:
        logger.debug("No usage information provided")
        return None

    return await calculate_token_cost(
        model=model,
        input_tokens=usage.input_tokens,
        output_tokens=usage.output_tokens,
        # Not part of the Protocol: older pydantic-ai versions and other usage objects.
        cache_read_tokens=getattr(usage, "cache_read_tokens", 0),
        cache_write_tokens=getattr(usage, "cache_write_tokens", 0),
        cache_timeout=cache_timeout,
    )

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

count_tokens

count_tokens(text: str | Sequence[str], model: str | None = None) -> int

Count total number of tokens in text(s) with fallback strategies.

Uses following fallback order: 1. tiktoken (if available) 2. transformers (if available) 3. rough approximation

Parameters:

Name Type Description Default
text str | Sequence[str]

Single text or sequence of texts to count tokens for

required
model str | None

Optional model name for tiktoken (ignored in fallbacks)

None

Returns:

Type Description
int

Total token count for all provided text(s)

Source code in src/tokonomics/token_count.py
def count_tokens(text: str | Sequence[str], model: str | None = None) -> int:
    """Count total number of tokens in text(s) with fallback strategies.

    Uses following fallback order:
    1. tiktoken (if available)
    2. transformers (if available)
    3. rough approximation

    Args:
        text: Single text or sequence of texts to count tokens for
        model: Optional model name for tiktoken (ignored in fallbacks)

    Returns:
        Total token count for all provided text(s)
    """
    # Try tiktoken first
    if has_library("tiktoken"):
        import tiktoken  # pyright: ignore[reportMissingImports]

        try:
            encoding = tiktoken.encoding_for_model(model or "gpt-3.5-turbo")
        except KeyError:
            encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")

        if isinstance(text, str):
            return len(encoding.encode(text))

        return sum(len(encoding.encode(t)) for t in text)

    # Try transformers as fallback
    if has_library("transformers"):
        tokenizer = _transformers_tokenizer()

        if isinstance(text, str):
            return len(tokenizer.encode(text))

        return sum(len(tokenizer.encode(t)) for t in text)

    # Last resort: rough approximation
    if isinstance(text, str):
        return len(text.split()) + len(text) // 4

    return sum(len(t.split()) + len(t) // 4 for t in text)

get_all_models async

get_all_models(
    *,
    providers: Sequence[ProviderType | Literal["models.dev"]] | None = None,
    include_deprecated: bool = False,
    max_age: timedelta | None = None,
) -> list[ModelInfo]

Fetch models from selected providers in parallel.

Parameters:

Name Type Description Default
providers Sequence[ProviderType | Literal['models.dev']] | None

Sequence of provider names to use. Defaults to available providers. Use "models.dev" to fetch all models from the models.dev aggregator.

None
include_deprecated bool

Whether to include deprecated models. Defaults to False.

False
max_age timedelta | None

Only include models released within this duration (by their created_at; models without one are always included). A filter on the models' age, not a cache age: the model lists are cached for MODELS_CACHE_TTL whatever it is.

None

Returns:

Type Description
list[ModelInfo]

list[ModelInfo]: Combined list of models from all providers.

Source code in src/tokonomics/model_discovery/__init__.py
async def get_all_models(
    *,
    providers: Sequence[ProviderType | Literal["models.dev"]] | None = None,
    include_deprecated: bool = False,
    max_age: timedelta | None = None,
) -> list[ModelInfo]:
    """Fetch models from selected providers in parallel.

    Args:
        providers: Sequence of provider names to use. Defaults to available providers.
                   Use "models.dev" to fetch all models from the models.dev aggregator.
        include_deprecated: Whether to include deprecated models. Defaults to False.
        max_age: Only include models released within this duration (by their
                 ``created_at``; models without one are always included). A filter on
                 the models' age, not a cache age: the model lists are cached for
                 ``MODELS_CACHE_TTL`` whatever it is.

    Returns:
        list[ModelInfo]: Combined list of models from all providers.
    """
    if providers is not None:
        selected_providers: list[ProviderType | Literal["models.dev"]] = list(providers)
    else:
        # Only use available providers when no specific providers are requested.
        # Probes may block (socket connect, `gh auth token`): run them in threads, at once.
        names = list(_PROVIDER_MAP)
        available = await asyncio.gather(
            *(asyncio.to_thread(_is_available, _PROVIDER_MAP[name]) for name in names)
        )
        selected_providers = [n for n, ok in zip(names, available, strict=True) if ok]
    all_models: list[ModelInfo] = []

    async def fetch_provider_models(
        provider_name: ProviderType | Literal["models.dev"],
    ) -> list[ModelInfo] | None:
        """Fetch models from a single provider."""
        try:
            provider = (
                ModelsDevProvider()
                if provider_name == "models.dev"
                else _PROVIDER_MAP[provider_name]()
            )
            if (models := get_cached(provider_name, provider)) is None:
                models = await provider.get_models()
                store(provider_name, provider, models)
            if not include_deprecated:
                models = [model for model in models if not model.is_deprecated]
            models = [model for model in models if not model.is_embedding]
            if max_age is not None:
                cutoff = datetime.now() - max_age
                models = [m for m in models if m.created_at is None or m.created_at >= cutoff]
        except Exception as e:  # noqa: BLE001
            logger.warning("Failed to fetch models from %s: %s", provider_name, str(e))
            return None
        else:
            return models

    # Fetch models from all providers in parallel
    results = await asyncio.gather(
        *(fetch_provider_models(provider) for provider in selected_providers),
        return_exceptions=False,
    )

    # Combine results, filtering out None values from failed providers
    for provider_models in results:
        if provider_models:
            all_models.extend(provider_models)

    successful_providers = {model.provider for model in all_models}
    logger.info(
        "Fetched %d models from %d providers: %s",
        len(all_models),
        len(successful_providers),
        ", ".join(sorted(successful_providers)),
    )
    return all_models

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