Skip to content

model_discovery

Class info

Re-exported classes

Class Module Description
CometProvider tokonomics.model_discovery.comet_provider.provider Comet API provider.
CopilotProvider tokonomics.model_discovery.copilot_provider.provider GitHub Copilot API provider.
DeepSeekProvider tokonomics.model_discovery.deepseek_provider.provider DeepSeek API provider.
GeminiProvider tokonomics.model_discovery.gemini_provider.provider Google Gemini API provider.
GitHubProvider tokonomics.model_discovery.github_provider.provider GitHub AI models API provider.
GroqProvider tokonomics.model_discovery.groq_provider.provider Groq API provider.
MistralProvider tokonomics.model_discovery.mistral_provider.provider Mistral AI API provider.
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.
ModelsDevProvider tokonomics.model_discovery.modelsdev_provider.provider Models.dev API provider - aggregates models from all providers.
NovitaProvider tokonomics.model_discovery.novita_provider.provider Novita AI API provider.
OllamaProvider tokonomics.model_discovery.ollama_provider.provider Ollama local API provider.
OpenRouterProvider tokonomics.model_discovery.openrouter_provider.provider OpenRouter API provider.
RequestyProvider tokonomics.model_discovery.requesty_provider.provider Requesty API provider.
VercelGatewayProvider tokonomics.model_discovery.vercel_gateway_provider.provider Vercel AI Gateway provider.
XAIProvider tokonomics.model_discovery.xai_provider.provider xAI API provider.

🛈 DocStrings

Model discovery package.

CometProvider

Bases: ModelProvider

Comet API provider.

Source code in src/tokonomics/model_discovery/comet_provider/provider.py
class CometProvider(ModelProvider):
    """Comet API provider."""

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

        self.base_url = "https://api.cometapi.com/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 Comet API response into ModelInfo."""
        # Comet gives every model the same placeholder ``created`` (2021-07-20), which
        # says nothing about when a model came out: treat it as unknown
        created_at = None
        if (created_timestamp := data.get("created")) and created_timestamp != COMET_PLACEHOLDER:
            with contextlib.suppress(ValueError, TypeError, OverflowError):
                created_at = datetime.fromtimestamp(created_timestamp)

        return ModelInfo(
            id=str(data["id"]),
            name=str(data.get("id")),  # Use id as name since no separate name field
            provider="comet",
            owned_by=str(data.get("owned_by")) if data.get("owned_by") else None,
            is_embedding="embedding" in str(data.get("id", "")).lower(),
            created_at=created_at,
            metadata={
                "object": data.get("object"),
                "root": data.get("root"),
                "parent": data.get("parent"),
                "permissions": data.get("permission", []),
            },
        )

is_available

is_available() -> bool

Check whether the provider is available for use.

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

CopilotProvider

Bases: ModelProvider

GitHub Copilot API provider.

Source code in src/tokonomics/model_discovery/copilot_provider/provider.py
class CopilotProvider(ModelProvider):
    """GitHub Copilot API provider."""

    def __init__(self) -> None:
        super().__init__()
        self._token_manager = token_manager
        self.base_url = self._token_manager._api_endpoint
        self.params = {}

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

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

        # Extract context window, input and output tokens
        context_window = limits.get("max_context_window_tokens")
        _max_input_tokens = limits.get("max_input_tokens")
        max_output_tokens = limits.get("max_output_tokens")

        # Determine modalities
        input_modalities: set[Modality] = {"text"}
        output_modalities: set[Modality] = {"text"}

        # Add vision capability if supported
        if capabilities.get("supports", {}).get("vision"):
            input_modalities.add("image")

        # Extract model family and version info
        model_family = capabilities.get("family", "")
        model_version = data.get("version", "")

        policy = data.get("policy") or {}
        # Create description
        description = ""
        if model_family:
            description += f"Model family: {model_family}\n"
        if model_version:
            description += f"Version: {model_version}\n"
        if vendor := data.get("vendor"):
            description += f"Vendor: {vendor}\n"

        # Add capabilities to description
        supports = capabilities.get("supports", {})
        support_features = []
        if supports.get("tool_calls"):
            support_features.append("tool calls")
        if supports.get("parallel_tool_calls"):
            support_features.append("parallel tool calls")
        if supports.get("vision"):
            support_features.append("vision")
        if supports.get("streaming"):
            support_features.append("streaming")

        if support_features:
            description += f"Supports: {', '.join(support_features)}"

        return ModelInfo(
            id=str(data["id"]),
            name=str(data.get("name", data["id"])),
            provider="copilot",
            description=description.strip() or None,
            context_window=context_window,
            max_output_tokens=max_output_tokens,
            is_deprecated=not _offered(data),
            owned_by=data.get("vendor"),
            input_modalities=input_modalities,
            output_modalities=output_modalities,
            metadata={"policy_state": policy.get("state")} if isinstance(policy, dict) else {},
        )

    async def get_models(self) -> list[ModelInfo]:
        """Override the standard get_models to use Copilot's specific endpoint."""
        import anyenv

        try:
            headers = await self._token_manager.generate_headers()
            # The token response names the account's API endpoint (Business/Enterprise).
            self.base_url = self._token_manager._api_endpoint
            url = f"{self.base_url}/models"
            response = await anyenv.get(url, headers=headers, timeout=30)
            data = response.json()
            if not isinstance(data, dict) or "data" not in data:
                msg = f"Invalid response format from Copilot API: {data}"
                raise RuntimeError(msg)  # noqa: TRY301
            models = []
            for model in data["data"]:
                if not _offered(model):  # Not in the model picker, or disabled for the account
                    continue
                capabilities = model.get("capabilities", {})
                if (
                    capabilities.get("type") != "chat"
                    or not capabilities.get("supports", {}).get("tool_calls", False)
                    or model["id"] in COPILOT_EXCLUDED_MODELS
                ):
                    continue

                models.append(self._parse_model(model))
        except Exception as e:
            msg = f"Failed to fetch models from Copilot: {e}"
            logger.exception(msg)
            raise RuntimeError(msg) from e
        else:
            return models

get_models async

get_models() -> list[ModelInfo]

Override the standard get_models to use Copilot's specific endpoint.

Source code in src/tokonomics/model_discovery/copilot_provider/provider.py
async def get_models(self) -> list[ModelInfo]:
    """Override the standard get_models to use Copilot's specific endpoint."""
    import anyenv

    try:
        headers = await self._token_manager.generate_headers()
        # The token response names the account's API endpoint (Business/Enterprise).
        self.base_url = self._token_manager._api_endpoint
        url = f"{self.base_url}/models"
        response = await anyenv.get(url, headers=headers, timeout=30)
        data = response.json()
        if not isinstance(data, dict) or "data" not in data:
            msg = f"Invalid response format from Copilot API: {data}"
            raise RuntimeError(msg)  # noqa: TRY301
        models = []
        for model in data["data"]:
            if not _offered(model):  # Not in the model picker, or disabled for the account
                continue
            capabilities = model.get("capabilities", {})
            if (
                capabilities.get("type") != "chat"
                or not capabilities.get("supports", {}).get("tool_calls", False)
                or model["id"] in COPILOT_EXCLUDED_MODELS
            ):
                continue

            models.append(self._parse_model(model))
    except Exception as e:
        msg = f"Failed to fetch models from Copilot: {e}"
        logger.exception(msg)
        raise RuntimeError(msg) from e
    else:
        return models

is_available

is_available() -> bool

Check whether the provider is available for use.

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

DeepSeekProvider

Bases: ModelProvider

DeepSeek API provider.

Source code in src/tokonomics/model_discovery/deepseek_provider/provider.py
class DeepSeekProvider(ModelProvider):
    """DeepSeek API provider."""

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

        self.base_url = "https://api.deepseek.com/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 DeepSeek API response into ModelInfo."""
        return ModelInfo(
            id=str(data["id"]),
            name=str(data.get("name", data["id"])),
            provider="deepseek",
            owned_by=str(data.get("owned_by")),
            description=str(data.get("description")) if "description" in data else None,
            context_window=(int(data["context_window"]) if "context_window" in data else None),
        )

is_available

is_available() -> bool

Check whether the provider is available for use.

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

GeminiProvider

Bases: ModelProvider

Google Gemini API provider.

Source code in src/tokonomics/model_discovery/gemini_provider/provider.py
class GeminiProvider(ModelProvider):
    """Google Gemini API provider."""

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

        self.base_url = "https://generativelanguage.googleapis.com/v1beta"
        self.params = {"key": self.api_key}
        self.headers = {}

    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 Gemini API response into ModelInfo."""
        model_id = str(data.get("name", ""))
        if model_id.startswith("models/"):
            model_id = model_id[7:]  # Remove 'models/' prefix

        display_name = str(data.get("displayName", model_id))

        # Check for embedding model indicators
        is_embedding = False
        model_id_lower = model_id.lower()
        display_name_lower = display_name.lower()
        description = data.get("description", "").lower()

        # Check name/ID for embedding indicators
        if "embed" in model_id_lower or "embed" in display_name_lower:
            is_embedding = True

        # Check generation methods for embedding indicators
        generation_methods = data.get("supportedGenerationMethods", [])
        if any(method in ("embedContent", "embedText") for method in generation_methods):
            is_embedding = True

        # Check output token limit (embedding models typically output only 1 token)
        if data.get("outputTokenLimit") == 1:
            is_embedding = True

        # Check description for embedding indicators
        if "distributed representation" in description:
            is_embedding = True

        # Determine input/output modalities
        input_modalities: set[Modality] = {"text"}
        output_modalities: set[Modality] = {"text"}

        if "vision" in display_name_lower or "multimodal" in description:
            input_modalities.add("image")

        # Check for image generation capabilities
        if "image generation" in display_name_lower or "imagen" in model_id_lower:
            output_modalities.add("image")

        if "predict" in generation_methods and "imagen" in model_id_lower:
            output_modalities.add("image")

        return ModelInfo(
            id=model_id,
            name=display_name,
            provider="gemini",
            description=data.get("description"),
            owned_by="Google",
            context_window=data.get("inputTokenLimit"),
            max_output_tokens=data.get("outputTokenLimit"),
            input_modalities=input_modalities,
            output_modalities=output_modalities,
            is_embedding=is_embedding,
        )

    async def get_models(self) -> list[ModelInfo]:
        """Override the base method to handle Gemini's unique API structure."""
        import anyenv
        from anyenv import HttpError, get_json

        url = f"{self.base_url}/models"

        try:
            # One connection for all pages.
            async with anyenv.http_session(cache=True, cache_ttl=MODELS_CACHE_TTL):
                data = await get_json(
                    url,
                    headers=self.headers,
                    params=self.params,
                    cache=True,
                    cache_ttl=MODELS_CACHE_TTL,
                    return_type=dict,
                )

                if "models" not in data:
                    msg = "Invalid response format from Gemini API"
                    raise RuntimeError(msg)

                # Get all pages if nextPageToken is present
                models = data["models"]
                next_page_token = data.get("nextPageToken")

                while next_page_token:
                    page_params = self.params.copy()
                    page_params["pageToken"] = next_page_token

                    next_data = await get_json(
                        url,
                        headers=self.headers,
                        params=page_params,
                        cache=True,
                        cache_ttl=MODELS_CACHE_TTL,
                        return_type=dict,
                    )

                    if "models" in next_data:
                        models.extend(next_data["models"])

                    next_page_token = next_data.get("nextPageToken")

                return [self._parse_model(item) for item in models]

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

get_models async

get_models() -> list[ModelInfo]

Override the base method to handle Gemini's unique API structure.

Source code in src/tokonomics/model_discovery/gemini_provider/provider.py
async def get_models(self) -> list[ModelInfo]:
    """Override the base method to handle Gemini's unique API structure."""
    import anyenv
    from anyenv import HttpError, get_json

    url = f"{self.base_url}/models"

    try:
        # One connection for all pages.
        async with anyenv.http_session(cache=True, cache_ttl=MODELS_CACHE_TTL):
            data = await get_json(
                url,
                headers=self.headers,
                params=self.params,
                cache=True,
                cache_ttl=MODELS_CACHE_TTL,
                return_type=dict,
            )

            if "models" not in data:
                msg = "Invalid response format from Gemini API"
                raise RuntimeError(msg)

            # Get all pages if nextPageToken is present
            models = data["models"]
            next_page_token = data.get("nextPageToken")

            while next_page_token:
                page_params = self.params.copy()
                page_params["pageToken"] = next_page_token

                next_data = await get_json(
                    url,
                    headers=self.headers,
                    params=page_params,
                    cache=True,
                    cache_ttl=MODELS_CACHE_TTL,
                    return_type=dict,
                )

                if "models" in next_data:
                    models.extend(next_data["models"])

                next_page_token = next_data.get("nextPageToken")

            return [self._parse_model(item) for item in models]

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

is_available

is_available() -> bool

Check whether the provider is available for use.

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

GitHubProvider

Bases: ModelProvider

GitHub AI models API provider.

Source code in src/tokonomics/model_discovery/github_provider/provider.py
class GitHubProvider(ModelProvider):
    """GitHub AI models API provider."""

    def __init__(self, token: str | None = None):
        super().__init__()
        self.token = token or os.environ.get("GITHUB_TOKEN")
        if not self.token:
            self.token = get_token_from_gh_cli()

        if not self.token:
            msg = "GitHub token not found in parameters, GITHUB_TOKEN env var, or gh CLI"
            raise RuntimeError(msg)

        self.base_url = "https://api.catalog.azureml.ms"
        self.models_url = f"{self.base_url}/asset-gallery/v1.0/models"
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.token}",
        }

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

    async def _fetch_models(self, is_free: bool) -> list[ModelInfo]:
        """Fetch models with specific freePlayground value."""
        from anyenv import post

        params = {
            "filters": [
                {
                    "field": "freePlayground",
                    "values": ["true" if is_free else "false"],
                    "operator": "eq",
                },
                {"field": "labels", "values": ["latest"], "operator": "eq"},
            ],
            "order": [{"field": "displayName", "direction": "asc"}],
        }

        try:
            response = await post(
                self.models_url,
                json=params,
                headers=self.headers,
                cache=True,
                cache_ttl=MODELS_CACHE_TTL,
            )
            data = response.json()
            if not isinstance(data, dict) or "summaries" not in data:
                msg = "Invalid response format from GitHub Models API"
                raise RuntimeError(msg)  # noqa: TRY301

            # Inject is_free into each model's data
            summaries = []
            for item in data["summaries"]:
                item_with_free = item.copy()  # Make a copy to not modify the original
                item_with_free["is_free"] = is_free
                summaries.append(item_with_free)

            return [self._parse_model(item) for item in summaries]
        except Exception as e:
            msg = f"Failed to fetch models from GitHub: {e}"
            logger.exception(msg)
            raise RuntimeError(msg) from e

    def _parse_model(self, data: dict[str, Any]) -> ModelInfo:
        """Parse GitHub models API response into ModelInfo."""
        inference_task = ""
        if data.get("task"):
            inference_task = data["task"]
        elif data.get("inferenceTasks") and isinstance(data["inferenceTasks"], list):
            inference_task = data["inferenceTasks"][0] if data["inferenceTasks"] else ""

        # Combine summary and task information for description
        description = data.get("summary", "")
        if inference_task:
            description = (
                f"{description}\nTask: {inference_task}"
                if description
                else f"Task: {inference_task}"
            )

        # Extract context window and output tokens
        context_window = None
        max_output_tokens = None
        limits = data.get("modelLimits")
        if isinstance(limits, dict) and isinstance(limits.get("textLimits"), dict):
            text_limits = limits["textLimits"]
            context_window = text_limits.get("inputContextWindow")
            max_output_tokens = text_limits.get("maxOutputTokens")

        input_modalities: set[Modality] = {"text"}
        output_modalities: set[Modality] = {"text"}
        if isinstance(limits, dict):
            if limits.get("supportedInputModalities"):
                input_modalities = set(limits["supportedInputModalities"])
            if limits.get("supportedOutputModalities"):
                output_modalities = set(limits["supportedOutputModalities"])

        # Use name as ID as it's more consistent with other providers
        model_id = data.get("name", "")
        model_name = data.get("friendly_name", "") or data.get("displayName", "") or model_id

        return ModelInfo(
            id=model_id,
            name=model_name,
            provider="github",
            description=description,
            owned_by=data.get("publisher", "GitHub"),
            context_window=context_window,
            max_output_tokens=max_output_tokens,
            input_modalities=input_modalities,
            output_modalities=output_modalities,
            is_free=data.get("is_free", True),
        )

    async def get_models(self) -> list[ModelInfo]:
        """Get both free and paid models through separate API calls."""
        import anyenv

        # One client for both requests (the helpers inside pick the session up).
        async with anyenv.http_session(cache=True, cache_ttl=MODELS_CACHE_TTL):
            free_models, paid_models = await asyncio.gather(
                self._fetch_models(is_free=True), self._fetch_models(is_free=False)
            )
        return free_models + paid_models

get_models async

get_models() -> list[ModelInfo]

Get both free and paid models through separate API calls.

Source code in src/tokonomics/model_discovery/github_provider/provider.py
async def get_models(self) -> list[ModelInfo]:
    """Get both free and paid models through separate API calls."""
    import anyenv

    # One client for both requests (the helpers inside pick the session up).
    async with anyenv.http_session(cache=True, cache_ttl=MODELS_CACHE_TTL):
        free_models, paid_models = await asyncio.gather(
            self._fetch_models(is_free=True), self._fetch_models(is_free=False)
        )
    return free_models + paid_models

is_available

is_available() -> bool

Check whether the provider is available for use.

Source code in src/tokonomics/model_discovery/github_provider/provider.py
def is_available(self) -> bool:
    """Check whether the provider is available for use."""
    return bool(self.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)

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."""

NovitaProvider

Bases: ModelProvider

Novita AI API provider.

Source code in src/tokonomics/model_discovery/novita_provider/provider.py
class NovitaProvider(ModelProvider):
    """Novita AI API provider."""

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

        self.base_url = "https://api.novita.ai/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 Novita API response into ModelInfo."""
        # Convert pricing from per million tokens to per token
        pricing = ModelPricing(
            prompt=float(data["input_token_price_per_m"]) / 1_000_000
            if data.get("input_token_price_per_m")
            else None,
            completion=float(data["output_token_price_per_m"]) / 1_000_000
            if data.get("output_token_price_per_m")
            else None,
        )

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

        # Build metadata for additional fields
        metadata = {}
        if "object" in data:
            metadata["object_type"] = data["object"]

        return ModelInfo(
            id=str(data["id"]),
            name=str(data.get("title", data["id"])),
            provider="novita",
            description=str(data.get("description")) if data.get("description") else None,
            context_window=int(data["context_size"]) if data.get("context_size") else None,
            pricing=pricing,
            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/novita_provider/provider.py
def is_available(self) -> bool:
    """Check whether the provider is available for use."""
    return bool(self.api_key)

OllamaProvider

Bases: ModelProvider

Ollama local API provider.

Source code in src/tokonomics/model_discovery/ollama_provider/provider.py
class OllamaProvider(ModelProvider):
    """Ollama local API provider."""

    models_cache_ttl = 60
    """A model pulled with ``ollama pull`` shows up within a minute."""

    def __init__(self, base_url: str = "http://localhost:11434") -> None:
        super().__init__()
        self.base_url = base_url
        self.headers = {}
        self.params = {}

    def is_available(self) -> bool:
        """Check whether Ollama is running and available."""
        try:
            # Extract host and port from base_url
            host_port = self.base_url.split("://")[1] if "://" in self.base_url else self.base_url

            if ":" in host_port:
                host, port_str = host_port.split(":", 1)
                port = int(port_str.split("/")[0])  # Handle paths after port
            else:
                host = host_port
                port = 11434  # Default Ollama port

            # Try to connect to the Ollama server
            with socket.create_connection((host, port), timeout=2):
                return True
        except ValueError, OSError:
            return False

    async def get_models(self) -> list[ModelInfo]:
        """Fetch available models from Ollama using the /api/tags endpoint."""
        import anyenv
        from anyenv import HttpError, get_json

        try:
            # Not HTTP-cached: the list changes with every ollama pull / rm.
            data = await get_json(
                f"{self.base_url}/api/tags",
                headers=self.headers,
                params=self.params,
                cache=False,
                return_type=dict,
            )

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

            # One client for all /api/show requests (cached, as _fetch_model asks).
            async with anyenv.http_session(cache=True, cache_ttl=MODELS_CACHE_TTL):
                models = list(await asyncio.gather(*(self._fetch_model(i) for i in data["models"])))
        except HttpError as e:
            msg = f"Failed to fetch models from {self.__class__.__name__}: {e}"
            raise RuntimeError(msg) from e
        else:
            return models

    async def _fetch_model(self, item: dict[str, Any]) -> ModelInfo:
        """Parse one listed model with its /api/show details (basic info if that fails)."""
        from anyenv import HttpError, post_json

        try:
            detail_data = await post_json(
                f"{self.base_url}/api/show",
                json_data={"name": item["name"]},
                headers=self.headers,
                cache=True,
                cache_ttl=MODELS_CACHE_TTL,
                return_type=dict,
            )
        except HttpError:
            return self._parse_model(item)
        return self._parse_model(item, detail_data)

    def _parse_model(
        self, data: dict[str, Any], detail_data: dict[str, Any] | None = None
    ) -> ModelInfo:
        """Parse Ollama API response into ModelInfo."""
        name = str(data["name"])

        # Extract model details from basic info
        details = data.get("details", {})
        family = details.get("family", "")
        parameter_size = details.get("parameter_size", "")
        quantization = details.get("quantization_level", "")

        # Extract additional info from detailed response if available
        context_window = None
        exact_param_count = None
        model_parameters = {}

        if detail_data:
            model_info = detail_data.get("model_info", {})

            # Get actual context window from model_info
            for key, value in model_info.items():
                if key.endswith(".context_length"):
                    context_window = int(value)
                    break

            # Get exact parameter count
            exact_param_count = model_info.get("general.parameter_count")

            # Parse model parameters (temperature, top_k, etc.)
            params_str = detail_data.get("parameters", "")
            if params_str:
                for line in params_str.strip().split("\n"):
                    if line.strip():
                        parts = line.strip().split(None, 1)
                        if len(parts) == 2:  # noqa: PLR2004
                            param_name, param_value = parts
                            # Convert numeric values
                            try:
                                if "." in param_value.strip('"'):
                                    model_parameters[param_name] = float(param_value.strip('"'))
                                elif param_value.strip('"').isdigit():
                                    model_parameters[param_name] = int(param_value.strip('"'))
                                else:
                                    model_parameters[param_name] = param_value.strip('"')
                            except ValueError:
                                model_parameters[param_name] = param_value.strip('"')

        # Fallback to estimation if no detailed context window found
        if not context_window:
            context_window = self._estimate_context_window(parameter_size, data.get("size", 0))

        # Build description from available details
        description_parts = []
        if family:
            description_parts.append(f"Family: {family}")
        if parameter_size:
            description_parts.append(f"Parameters: {parameter_size}")
        if exact_param_count and exact_param_count != parameter_size:
            description_parts.append(f"Exact count: {exact_param_count:,}")
        if quantization:
            description_parts.append(f"Quantization: {quantization}")

        description = " | ".join(description_parts) if description_parts else None

        # Determine modalities based on family
        input_modalities: set[Modality] = {"text"}
        output_modalities: set[Modality] = {"text"}

        if (family and "llava" in family.lower()) or (
            family
            and any(vision in family.lower() for vision in ["vision", "visual", "multimodal"])
        ):
            input_modalities.add("image")

        # Build comprehensive metadata
        metadata = {
            "size_bytes": data.get("size", 0),
            "digest": data.get("digest"),
            "modified_at": data.get("modified_at"),
            "format": details.get("format"),
            "families": details.get("families", []),
            "quantization_level": quantization,
            "parameter_size": parameter_size,
            "parent_model": details.get("parent_model"),
        }

        # Add detailed info if available
        if detail_data:
            metadata.update({
                "exact_parameter_count": exact_param_count,
                "model_parameters": model_parameters,
                "has_template": bool(detail_data.get("template")),
                "license_type": "Apache License 2.0"
                if "Apache License" in detail_data.get("license", "")
                else None,
            })

            # Add model architecture details from model_info
            if model_info := detail_data.get("model_info", {}):
                arch_info = {}
                for key, value in model_info.items():
                    if any(key.startswith(prefix) for prefix in ["general.", f"{family}."]):
                        clean_key = key.split(".", 1)[1] if "." in key else key
                        arch_info[clean_key] = value
                if arch_info:
                    metadata["architecture"] = arch_info

        return ModelInfo(
            id=name,
            name=name,
            provider="ollama",
            description=description,
            pricing=ModelPricing(),  # Local models are free
            owned_by=family if family else None,
            context_window=context_window,
            is_free=True,  # Local Ollama models are free to use
            input_modalities=input_modalities,
            output_modalities=output_modalities,
            metadata=metadata,
        )

    def _estimate_context_window(self, parameter_size: str, size_bytes: int) -> int | None:
        """Estimate context window based on parameter size and model family."""
        if not parameter_size:
            return None

        param_size_lower = parameter_size.lower()

        # Common context windows for different model sizes
        if (
            "1b" in param_size_lower
            or "1.1b" in param_size_lower
            or "3b" in param_size_lower
            or "7b" in param_size_lower
            or "8b" in param_size_lower
        ):
            return 8192
        if (
            "13b" in param_size_lower
            or "14b" in param_size_lower
            or "30b" in param_size_lower
            or "34b" in param_size_lower
            or "70b" in param_size_lower
        ):
            return 4096
        if "405b" in param_size_lower:
            return 8192

        # Default fallback
        return 4096

models_cache_ttl class-attribute instance-attribute

models_cache_ttl = 60

A model pulled with ollama pull shows up within a minute.

get_models async

get_models() -> list[ModelInfo]

Fetch available models from Ollama using the /api/tags endpoint.

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

    try:
        # Not HTTP-cached: the list changes with every ollama pull / rm.
        data = await get_json(
            f"{self.base_url}/api/tags",
            headers=self.headers,
            params=self.params,
            cache=False,
            return_type=dict,
        )

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

        # One client for all /api/show requests (cached, as _fetch_model asks).
        async with anyenv.http_session(cache=True, cache_ttl=MODELS_CACHE_TTL):
            models = list(await asyncio.gather(*(self._fetch_model(i) for i in data["models"])))
    except HttpError as e:
        msg = f"Failed to fetch models from {self.__class__.__name__}: {e}"
        raise RuntimeError(msg) from e
    else:
        return models

is_available

is_available() -> bool

Check whether Ollama is running and available.

Source code in src/tokonomics/model_discovery/ollama_provider/provider.py
def is_available(self) -> bool:
    """Check whether Ollama is running and available."""
    try:
        # Extract host and port from base_url
        host_port = self.base_url.split("://")[1] if "://" in self.base_url else self.base_url

        if ":" in host_port:
            host, port_str = host_port.split(":", 1)
            port = int(port_str.split("/")[0])  # Handle paths after port
        else:
            host = host_port
            port = 11434  # Default Ollama port

        # Try to connect to the Ollama server
        with socket.create_connection((host, port), timeout=2):
            return True
    except ValueError, OSError:
        return False

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)

RequestyProvider

Bases: ModelProvider

Requesty API provider.

Source code in src/tokonomics/model_discovery/requesty_provider/provider.py
class RequestyProvider(ModelProvider):
    """Requesty API provider."""

    def __init__(self, api_key: str | None = None) -> None:
        super().__init__()
        self.api_key = api_key or os.environ.get("REQUESTY_API_KEY")

        self.base_url = "https://router.requesty.ai/v1"
        self.headers = {}
        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 Requesty API response into ModelInfo."""
        # Determine input modalities based on capabilities
        input_modalities: set[Modality] = {"text"}
        if data.get("supports_vision"):
            input_modalities.add("image")

        # Create pricing information
        pricing = ModelPricing(
            prompt=float(data["input_price"]) if data.get("input_price") else None,
            completion=float(data["output_price"]) if data.get("output_price") else None,
            input_cache_read=float(data["cached_price"]) if data.get("cached_price") else None,
            input_cache_write=float(data["caching_price"]) if data.get("caching_price") else None,
        )

        # Build metadata for additional capabilities
        metadata = {}
        if "supports_caching" in data:
            metadata["supports_caching"] = data["supports_caching"]
        if "supports_computer_use" in data:
            metadata["supports_computer_use"] = data["supports_computer_use"]
        if "supports_reasoning" in data:
            metadata["supports_reasoning"] = data["supports_reasoning"]

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

        return ModelInfo(
            id=str(data["id"]),
            name=str(data["id"]),  # Requesty uses id as the model name
            provider="requesty",
            description=str(data.get("description")) if data.get("description") else None,
            pricing=pricing,
            owned_by=str(data.get("owned_by")) if data.get("owned_by") else None,
            context_window=int(data["context_window"]) if data.get("context_window") else None,
            max_output_tokens=int(data["max_output_tokens"])
            if data.get("max_output_tokens")
            else None,
            input_modalities=input_modalities,
            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/requesty_provider/provider.py
def is_available(self) -> bool:
    """Check whether the provider is available for use."""
    return bool(self.api_key)

VercelGatewayProvider

Bases: ModelProvider

Vercel AI Gateway provider.

Source code in src/tokonomics/model_discovery/vercel_gateway_provider/provider.py
class VercelGatewayProvider(ModelProvider):
    """Vercel AI Gateway provider."""

    def __init__(
        self,
        api_key: str | None = None,
        base_url: str | None = None,
        headers: dict[str, str] | None = None,
    ):
        super().__init__()
        self.api_key = api_key or os.environ.get("AI_GATEWAY_API_KEY")
        if not self.api_key:
            msg = "Vercel Gateway API key not found in parameters or AI_GATEWAY_API_KEY env var"
            raise RuntimeError(msg)

        self.base_url = base_url or "https://ai-gateway.vercel.sh/v1/ai"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "ai-gateway-protocol-version": "0.0.1",
            "ai-gateway-auth-method": "api-key",
            "Content-Type": "application/json",
            **(headers or {}),
        }
        self.params = {}

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

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

        url = f"{self.base_url}/config"

        try:
            data: dict[str, Any] = await get_json(
                url,
                headers=self.headers,
                params=self.params,
                cache=True,
                cache_ttl=MODELS_CACHE_TTL,
                return_type=dict,
            )

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

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

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

    def _parse_model(self, data: dict[str, Any]) -> ModelInfo:
        """Parse Vercel Gateway API response into ModelInfo."""
        # Extract basic model information
        model_id = str(data["id"])
        name = str(data.get("name", model_id))
        description = data.get("description")

        # Extract specification details
        spec = data.get("specification", {})
        provider_name = spec.get("provider", "vercel-gateway")

        # Determine model type and modalities
        model_type = data.get("modelType")
        is_embedding = model_type == "embedding"

        # Set modalities based on model type
        input_modalities: set[Modality] = {"text"}
        output_modalities: set[Modality] = {"text"}

        if model_type == "image":
            output_modalities.add("image")
        elif "vision" in name.lower() or "gpt-4o" in model_id.lower():
            input_modalities.add("image")

        # Parse pricing information
        pricing = None
        if pricing_data := data.get("pricing"):
            pricing = ModelPricing(
                prompt=self._parse_price(pricing_data.get("input")),
                completion=self._parse_price(pricing_data.get("output")),
                input_cache_read=self._parse_price(pricing_data.get("cachedInputTokens")),
                input_cache_write=self._parse_price(pricing_data.get("cacheCreationInputTokens")),
            )

        # Build metadata dictionary
        metadata = {
            "gateway_provider": provider_name,
            "specification_version": spec.get("specificationVersion"),
            "model_type": model_type,
        }

        # Add any additional fields not covered by standard ModelInfo
        excluded_keys = {
            "id",
            "name",
            "description",
            "pricing",
            "specification",
            "modelType",
        }
        metadata.update({
            key: value
            for key, value in data.items()
            if key not in excluded_keys and value is not None
        })

        return ModelInfo(
            id=model_id,
            name=name,
            provider="vercel-gateway",
            description=description,
            pricing=pricing,
            is_embedding=is_embedding,
            input_modalities=input_modalities,
            output_modalities=output_modalities,
            is_free=pricing is None or (pricing.prompt == 0 and pricing.completion == 0),
            metadata=metadata,
        )

    def _parse_price(self, price_str: str | None) -> float | None:
        """Parse price string to float."""
        if not price_str:
            return None
        try:
            return float(price_str)
        except ValueError, TypeError:
            return None

get_models async

get_models() -> list[ModelInfo]

Fetch available models from the Vercel Gateway.

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

    url = f"{self.base_url}/config"

    try:
        data: dict[str, Any] = await get_json(
            url,
            headers=self.headers,
            params=self.params,
            cache=True,
            cache_ttl=MODELS_CACHE_TTL,
            return_type=dict,
        )

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

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

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

is_available

is_available() -> bool

Check whether the provider is available for use.

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

XAIProvider

Bases: ModelProvider

xAI API provider.

Source code in src/tokonomics/model_discovery/xai_provider/provider.py
class XAIProvider(ModelProvider):
    """xAI API provider."""

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

        self.base_url = "https://api.x.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 xAI API response into ModelInfo."""
        # Extract basic info
        model_id = str(data["id"])
        name = str(data.get("name", model_id))
        owned_by = str(data.get("owned_by"))

        # Parse modalities
        input_modalities: set[Modality] = set()
        output_modalities: set[Modality] = set()

        for modality in data.get("input_modalities", []):
            if modality in {"text", "image", "audio", "video"}:
                input_modalities.add(modality)

        for modality in data.get("output_modalities", []):
            if modality in {"text", "image", "audio", "video"}:
                output_modalities.add(modality)

        # Set defaults if empty
        if not input_modalities:
            input_modalities = {"text"}
        if not output_modalities:
            output_modalities = {"text"}

        # Token prices are USD cents per 100M tokens (12500 = $1.25/M): / 1e10 for $/token.
        # The unit of search_price is unverified (0 for all models so far): kept as is.
        pricing = None
        if any(
            key in data
            for key in [
                "prompt_text_token_price",
                "completion_text_token_price",
                "prompt_image_token_price",
                "search_price",
            ]
        ):
            pricing = ModelPricing(
                prompt=data.get("prompt_text_token_price", 0) / _PRICE_SCALE
                if "prompt_text_token_price" in data
                else None,
                completion=data.get("completion_text_token_price", 0) / _PRICE_SCALE
                if "completion_text_token_price" in data
                else None,
                image=data.get("prompt_image_token_price", 0) / _PRICE_SCALE
                if "prompt_image_token_price" in data
                else None,
                input_cache_read=data.get("cached_prompt_text_token_price", 0) / _PRICE_SCALE
                if "cached_prompt_text_token_price" in data
                else None,
                web_search=data.get("search_price", 0) / 1_000_000
                if "search_price" in data
                else None,
            )

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

        # Build metadata
        metadata = {}
        if "fingerprint" in data:
            metadata["fingerprint"] = data["fingerprint"]
        if "version" in data:
            metadata["version"] = data["version"]
        if data.get("aliases"):
            metadata["aliases"] = data["aliases"]

        return ModelInfo(
            id=model_id,
            name=name,
            provider="xai",
            owned_by=owned_by,
            pricing=pricing,
            input_modalities=input_modalities,
            output_modalities=output_modalities,
            created_at=created_at,
            metadata=metadata,
        )

    async def get_models(self) -> list[ModelInfo]:
        """Override the base method to handle xAI's unique API structure."""
        from anyenv import HttpError, get_json

        url = f"{self.base_url}/language-models"

        try:
            data = await get_json(
                url,
                headers=self.headers,
                params=self.params,
                cache=True,
                cache_ttl=MODELS_CACHE_TTL,
                return_type=dict,
            )

            if "models" not in data:
                msg = "Invalid response format from xAI API"
                raise RuntimeError(msg)

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

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

get_models async

get_models() -> list[ModelInfo]

Override the base method to handle xAI's unique API structure.

Source code in src/tokonomics/model_discovery/xai_provider/provider.py
async def get_models(self) -> list[ModelInfo]:
    """Override the base method to handle xAI's unique API structure."""
    from anyenv import HttpError, get_json

    url = f"{self.base_url}/language-models"

    try:
        data = await get_json(
            url,
            headers=self.headers,
            params=self.params,
            cache=True,
            cache_ttl=MODELS_CACHE_TTL,
            return_type=dict,
        )

        if "models" not in data:
            msg = "Invalid response format from xAI API"
            raise RuntimeError(msg)

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

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

is_available

is_available() -> bool

Check whether the provider is available for use.

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

clear_models_cache

clear_models_cache() -> None

Drop the parsed model lists, so the next discovery parses again.

Source code in src/tokonomics/model_discovery/cache.py
def clear_models_cache() -> None:
    """Drop the parsed model lists, so the next discovery parses again."""
    _parsed.clear()

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_all_models_sync

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

Fetch models from selected providers in parallel using threads.

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
max_workers int | None

Maximum number of worker threads. Defaults to min(32, os.cpu_count() * 5)

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
def get_all_models_sync(
    *,
    providers: Sequence[ProviderType | Literal["models.dev"]] | None = None,
    max_workers: int | None = None,
    include_deprecated: bool = False,
    max_age: timedelta | None = None,
) -> list[ModelInfo]:
    """Fetch models from selected providers in parallel using threads.

    Args:
        providers: Sequence of provider names to use. Defaults to available providers.
                   Use "models.dev" to fetch all models from the models.dev aggregator.
        max_workers: Maximum number of worker threads.
                     Defaults to min(32, os.cpu_count() * 5)
        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.
    """
    import concurrent.futures

    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
        selected_providers = [n for n, cls in _PROVIDER_MAP.items() if _is_available(cls)]
    all_models: list[ModelInfo] = []

    def fetch_provider_models(
        provider_name: ProviderType | Literal["models.dev"],
    ) -> list[ModelInfo] | None:
        """Fetch models from a single provider."""
        import anyenv

        try:
            provider = (
                ModelsDevProvider()
                if provider_name == "models.dev"
                else _PROVIDER_MAP[provider_name]()
            )
            if (models := get_cached(provider_name, provider)) is None:
                models = anyenv.run_sync(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

    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        # Submit all tasks and collect results as they complete
        fut = {executor.submit(fetch_provider_models, p): p for p in selected_providers}
        for future in concurrent.futures.as_completed(fut):
            provider_models = future.result()
            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_pydantic_ai_variants

get_pydantic_ai_variants(
    provider: str, model_id: str, supports_reasoning_flag: bool
) -> dict[str, dict[str, Any]]

Generate thinking level variants based on provider and model capabilities.

Parameters:

Name Type Description Default
provider str

Provider name (e.g., "anthropic", "openai", "google")

required
model_id str

Model identifier

required
supports_reasoning_flag bool

Whether the model supports reasoning/thinking (from models.dev metadata)

required

Returns:

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

Dict mapping variant name to pydantic-ai ModelSettings.

dict[str, dict[str, Any]]

Empty dict if model doesn't support reasoning.

Source code in src/tokonomics/model_discovery/variants.py
def get_pydantic_ai_variants(
    provider: str,
    model_id: str,
    supports_reasoning_flag: bool,
) -> dict[str, dict[str, Any]]:
    """Generate thinking level variants based on provider and model capabilities.

    Args:
        provider: Provider name (e.g., "anthropic", "openai", "google")
        model_id: Model identifier
        supports_reasoning_flag: Whether the model supports reasoning/thinking
            (from models.dev metadata)

    Returns:
        Dict mapping variant name to pydantic-ai ModelSettings.
        Empty dict if model doesn't support reasoning.
    """
    if not supports_reasoning_flag:
        return {}

    levels = get_reasoning_levels(provider, model_id)
    if not levels:
        return {}

    return {level: get_reasoning_settings(provider, model_id, level) for level in levels}

get_reasoning_levels

get_reasoning_levels(provider: str, model_id: str) -> list[str]

Get available reasoning levels for a model.

Parameters:

Name Type Description Default
provider str

Provider name (e.g., "anthropic", "openai", "google")

required
model_id str

Model identifier

required

Returns:

Type Description
list[str]

List of available level names, empty if reasoning not supported.

Source code in src/tokonomics/model_discovery/variants.py
def get_reasoning_levels(provider: str, model_id: str) -> list[str]:  # noqa: PLR0911
    """Get available reasoning levels for a model.

    Args:
        provider: Provider name (e.g., "anthropic", "openai", "google")
        model_id: Model identifier

    Returns:
        List of available level names, empty if reasoning not supported.
    """
    if not supports_reasoning(provider, model_id):
        return []

    model_id_lower = model_id.lower()

    # Anthropic models (native or via Bedrock)
    if provider == "anthropic":
        return ["off", "high", "max"]

    # AWS Bedrock with Anthropic models
    if provider in ("bedrock", "amazon-bedrock"):
        if "anthropic" in model_id_lower or "claude" in model_id_lower:
            return ["off", "high", "max"]
        return []

    # OpenAI models
    if provider in ("openai", "azure"):
        levels = ["off", "low", "medium", "high"]
        if "gpt-5" in model_id_lower:
            levels.insert(1, "minimal")  # after "off"
        return levels

    # Google models
    if provider in ("google", "google-gla", "google-vertex"):
        if "2.5" in model_id_lower or "2-5" in model_id_lower:
            return ["off", "high", "max"]
        return ["off", "low", "high"]

    return []

get_reasoning_settings

get_reasoning_settings(provider: str, model_id: str, level: str) -> dict[str, Any]

Get pydantic-ai ModelSettings for a reasoning level.

Parameters:

Name Type Description Default
provider str

Provider name (e.g., "anthropic", "openai", "google")

required
model_id str

Model identifier

required
level str

Reasoning level (e.g., "high", "max", "low", "medium")

required

Returns:

Type Description
dict[str, Any]

Dict of pydantic-ai ModelSettings for the specified level.

Raises:

Type Description
ValueError

If level is not valid for this provider/model.

Source code in src/tokonomics/model_discovery/variants.py
def get_reasoning_settings(provider: str, model_id: str, level: str) -> dict[str, Any]:  # noqa: PLR0911
    """Get pydantic-ai ModelSettings for a reasoning level.

    Args:
        provider: Provider name (e.g., "anthropic", "openai", "google")
        model_id: Model identifier
        level: Reasoning level (e.g., "high", "max", "low", "medium")

    Returns:
        Dict of pydantic-ai ModelSettings for the specified level.

    Raises:
        ValueError: If level is not valid for this provider/model.
    """
    available = get_reasoning_levels(provider, model_id)
    if not available:
        msg = f"Model {provider}:{model_id} does not support configurable reasoning"
        raise ValueError(msg)

    if level not in available:
        msg = f"Invalid level '{level}' for {provider}:{model_id}. Available: {available}"
        raise ValueError(msg)

    model_id_lower = model_id.lower()

    # Anthropic models (native or via Bedrock)
    if provider == "anthropic":
        if level == "off":
            return {"anthropic_thinking": {"type": "disabled"}}
        budgets = {"high": 16000, "max": 31999}
        return {"anthropic_thinking": {"type": "enabled", "budget_tokens": budgets[level]}}

    # AWS Bedrock with Anthropic models
    if provider in ("bedrock", "amazon-bedrock") and (
        "anthropic" in model_id_lower or "claude" in model_id_lower
    ):
        if level == "off":
            return {"anthropic_thinking": {"type": "disabled"}}
        budgets = {"high": 16000, "max": 31999}
        return {"anthropic_thinking": {"type": "enabled", "budget_tokens": budgets[level]}}

    # OpenAI models
    if provider in ("openai", "azure"):
        if level == "off":
            return {}  # No reasoning settings = disabled
        return {
            "openai_reasoning_effort": level,
            "openai_reasoning_summary": "auto",
        }

    # Google models
    if provider in ("google", "google-gla", "google-vertex"):
        if level == "off":
            return {"google_thinking_config": {"include_thoughts": False}}
        if "2.5" in model_id_lower or "2-5" in model_id_lower:
            budgets = {"high": 16000, "max": 24576}
            return {
                "google_thinking_config": {
                    "include_thoughts": True,
                    "thinking_budget": budgets[level],
                }
            }
        # Gemini 3+ just enables thinking, level doesn't map to budget
        return {"google_thinking_config": {"include_thoughts": True}}

    # Should not reach here if supports_reasoning is correct
    msg = f"No settings implementation for {provider}:{model_id}"
    raise ValueError(msg)

supports_reasoning

supports_reasoning(provider: str, model_id: str) -> bool

Check if a model supports configurable reasoning/thinking levels.

Parameters:

Name Type Description Default
provider str

Provider name (e.g., "anthropic", "openai", "google")

required
model_id str

Model identifier

required

Returns:

Type Description
bool

True if the model supports configurable reasoning levels.

Source code in src/tokonomics/model_discovery/variants.py
def supports_reasoning(provider: str, model_id: str) -> bool:
    """Check if a model supports configurable reasoning/thinking levels.

    Args:
        provider: Provider name (e.g., "anthropic", "openai", "google")
        model_id: Model identifier

    Returns:
        True if the model supports configurable reasoning levels.
    """
    model_id_lower = model_id.lower()

    # Models with reasoning capability but no configurable variants
    if any(x in model_id_lower for x in ("deepseek", "minimax", "glm", "mistral")):
        return False

    # OpenAI o1-mini doesn't support reasoning effort
    if provider == "openai" and model_id_lower == "o1-mini":
        return False

    # Supported providers (pydantic-ai and models.dev provider names)
    supported_providers = {
        "anthropic",
        "openai",
        "azure",
        "google",
        "google-gla",
        "google-vertex",
        "bedrock",
        "amazon-bedrock",
    }

    return provider in supported_providers