Skip to content

CopilotProvider

Base classes

Name Children Inherits
ModelProvider
tokonomics.model_discovery.base
Base class for model providers.

⋔ Inheritance diagram

graph TD
  3956095401["provider.CopilotProvider"]
  271169313["base.ModelProvider"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  271169313 --> 3956095401
  925645236 --> 271169313
  2751680898 --> 925645236

🛈 DocStrings

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()

:fa-brands-github: Show source on GitHub