Skip to content

copilot_provider

Class info

Re-exported classes

Class Module Description
CopilotProvider tokonomics.model_discovery.copilot_provider.provider GitHub Copilot API provider.
CopilotTokenManager tokonomics.model_discovery.copilot_provider.token_manager Manager for GitHub Copilot API tokens.

🛈 DocStrings

Copilot model info Provider.

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

CopilotTokenManager

Manager for GitHub Copilot API tokens.

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

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

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

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

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

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

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

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

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

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

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

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

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

generate_headers async

generate_headers() -> dict[str, str]

Generate headers for GitHub Copilot API requests.

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

get_token async

get_token() -> str

Get a valid Copilot token, refreshing if needed.

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

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

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

get_token_sync

get_token_sync() -> str

Get a valid Copilot token, refreshing if needed.

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

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

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

is_available

is_available() -> bool

Check whether the token manager is available for use.

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