import logging import aiohttp from abc import ABC, abstractmethod from typing import Dict, List, Any from .. import config logger = logging.getLogger("free_api.providers") PROVIDER_PRIORITY = {"kilo": 0, "openrouter": 1, "zen": 2} class Provider(ABC): name: str base_url: str models_path: str = "/models" @abstractmethod def is_available(self) -> bool: ... @abstractmethod def is_free_model(self, model: Dict[str, Any]) -> bool: ... @abstractmethod def get_chat_url(self) -> str: ... @abstractmethod def get_headers(self, model_id: str) -> Dict[str, str]: ... def priority(self) -> int: return PROVIDER_PRIORITY.get(self.name, 99) async def fetch_models(self) -> List[Dict[str, Any]]: url = f"{self.base_url}{self.models_path}" headers = self._fetch_headers() timeout = aiohttp.ClientTimeout(total=config.get_request_timeout()) try: async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers, timeout=timeout) as response: if response.status == 200: data = await response.json() return data.get("data", []) logger.warning("[%s] fetch_models HTTP %d", self.name, response.status) return [] except Exception as e: logger.error("[%s] fetch_models error: %s", self.name, e) return [] def _fetch_headers(self) -> Dict[str, str]: return {} def get_provider_priority(provider_name: str) -> int: return PROVIDER_PRIORITY.get(provider_name, 99)