Skip to content

ModelInfo

🛈 DocStrings

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)

:fa-brands-github: Show source on GitHub