476 lines
19 KiB
Python
476 lines
19 KiB
Python
"""Authenticated model discovery shared by refresh and connection checks."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from dataclasses import dataclass
|
|
from datetime import datetime
|
|
import time
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
from weakref import WeakKeyDictionary
|
|
|
|
import httpx
|
|
|
|
CATALOG_TIMEOUT_SECONDS = 30
|
|
CATALOG_MAX_PAGES = 100
|
|
CATALOG_PAGE_SIZE = 100
|
|
CATALOG_REQUEST_ATTEMPTS = 2
|
|
CATALOG_RETRY_DELAY_SECONDS = 0.2
|
|
MODELS_DEV_CATALOG_URL = "https://models.dev/api.json"
|
|
OPENROUTER_CATALOG_URL = "https://openrouter.ai/api/v1/models"
|
|
AGGREGATOR_CACHE_TTL_SECONDS = 300
|
|
SUPPORTED_PROVIDER_APIS = {
|
|
"openai-completions",
|
|
"openai-responses",
|
|
"anthropic-messages",
|
|
"ollama-generate",
|
|
}
|
|
OFFICIAL_PUBLIC_CATALOG_HOSTS: dict[str, frozenset[str]] = {
|
|
"openrouter": frozenset({"openrouter.ai"}),
|
|
"opencode-go": frozenset({"opencode.ai"}),
|
|
}
|
|
OFFICIAL_PROVIDER_HOSTS: dict[str, frozenset[str]] = {
|
|
"minimax": frozenset({"api.minimaxi.com", "api.minimax.cn", "api.minimax.io"}),
|
|
"openai": frozenset({"api.openai.com"}),
|
|
"anthropic": frozenset({"api.anthropic.com"}),
|
|
"deepseek": frozenset({"api.deepseek.com"}),
|
|
"alibaba": frozenset({"dashscope.aliyuncs.com", "dashscope-intl.aliyuncs.com"}),
|
|
"moonshotai": frozenset({"api.moonshot.ai", "api.moonshot.cn"}),
|
|
"glm": frozenset({"open.bigmodel.cn", "api.z.ai"}),
|
|
"meta": frozenset({"api.meta.ai", "api.llama.com"}),
|
|
"gemini": frozenset({"generativelanguage.googleapis.com"}),
|
|
"grok": frozenset({"api.x.ai"}),
|
|
**OFFICIAL_PUBLIC_CATALOG_HOSTS,
|
|
}
|
|
AGGREGATOR_OPENROUTER_PREFIXES: dict[str, str] = {
|
|
"minimax": "minimax/",
|
|
"openai": "openai/",
|
|
"anthropic": "anthropic/",
|
|
"deepseek": "deepseek/",
|
|
"alibaba": "qwen/",
|
|
"moonshotai": "moonshotai/",
|
|
"glm": "z-ai/",
|
|
"meta": "meta-llama/",
|
|
"gemini": "google/",
|
|
"grok": "x-ai/",
|
|
}
|
|
_AGGREGATOR_CACHE: dict[str, tuple[float, object]] = {}
|
|
_AGGREGATOR_LOOP_LOCKS: WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = WeakKeyDictionary()
|
|
|
|
|
|
class LLMProviderCatalogError(RuntimeError):
|
|
"""A safe, user-facing catalog failure with no upstream response or credentials."""
|
|
|
|
|
|
class LLMProviderCatalogConfigError(LLMProviderCatalogError):
|
|
"""Invalid local catalog configuration or missing required credentials."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ModelCatalog:
|
|
url: str
|
|
models: list[str]
|
|
|
|
|
|
def is_official_public_catalog(provider: str, base_url: str) -> bool:
|
|
provider_key = provider.strip().lower()
|
|
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
|
return host in OFFICIAL_PUBLIC_CATALOG_HOSTS.get(provider_key, frozenset())
|
|
|
|
|
|
def is_official_provider_host(provider: str, base_url: str) -> bool:
|
|
provider_key = provider.strip().lower()
|
|
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
|
if not host:
|
|
return False
|
|
if host in OFFICIAL_PROVIDER_HOSTS.get(provider_key, frozenset()):
|
|
return True
|
|
return provider_key == "alibaba" and (host == "aliyuncs.com" or host.endswith(".aliyuncs.com"))
|
|
|
|
|
|
def catalog_requires_api_key(provider: str, base_url: str, provider_api: str) -> bool:
|
|
provider_key = provider.strip().lower()
|
|
if provider_key == "ollama" or provider_api == "ollama-generate":
|
|
return False
|
|
return not is_official_public_catalog(provider_key, base_url)
|
|
|
|
|
|
def catalog_supports_aggregator_fallback(
|
|
provider: str, base_url: str, provider_api: str
|
|
) -> bool:
|
|
provider_key = provider.strip().lower()
|
|
return (
|
|
provider_key in AGGREGATOR_OPENROUTER_PREFIXES
|
|
and provider_api in SUPPORTED_PROVIDER_APIS
|
|
and provider_api != "ollama-generate"
|
|
and is_official_provider_host(provider_key, base_url)
|
|
)
|
|
|
|
|
|
def can_refresh_catalog_without_api_key(
|
|
provider: str, base_url: str, provider_api: str
|
|
) -> bool:
|
|
return not catalog_requires_api_key(
|
|
provider, base_url, provider_api
|
|
) or catalog_supports_aggregator_fallback(provider, base_url, provider_api)
|
|
|
|
|
|
def clear_aggregator_catalog_cache() -> None:
|
|
_AGGREGATOR_CACHE.clear()
|
|
|
|
|
|
def model_catalog_url(provider: str, base_url: str, provider_api: str) -> str:
|
|
parts = urlsplit(base_url.strip())
|
|
if parts.scheme not in {"http", "https"} or not parts.hostname:
|
|
raise LLMProviderCatalogConfigError("请填写有效的 HTTP(S) 模型基础地址。")
|
|
if parts.username or parts.password or parts.query or parts.fragment:
|
|
raise LLMProviderCatalogConfigError("模型基础地址不能包含账号、密码、查询参数或片段。")
|
|
if provider_api not in SUPPORTED_PROVIDER_APIS:
|
|
raise LLMProviderCatalogConfigError("当前接口协议不支持模型目录查询。")
|
|
path = parts.path.rstrip("/")
|
|
if provider_api == "ollama-generate":
|
|
path = path.removesuffix("/api").removesuffix("/v1") + "/api/tags"
|
|
elif provider == "alibaba" and parts.hostname.endswith(".aliyuncs.com"):
|
|
path = "/api/v1/models"
|
|
else:
|
|
if not path or (provider_api == "anthropic-messages" and path.endswith("/anthropic")):
|
|
path += "/v1"
|
|
path += "/models"
|
|
return urlunsplit((parts.scheme, parts.netloc, path, "", ""))
|
|
|
|
|
|
def catalog_error_message(exc: Exception) -> str:
|
|
if isinstance(exc, LLMProviderCatalogError):
|
|
return str(exc)
|
|
if isinstance(exc, (httpx.TimeoutException, TimeoutError)):
|
|
return "模型目录请求超时,请检查网络后重试。"
|
|
if isinstance(exc, httpx.HTTPStatusError):
|
|
code = exc.response.status_code
|
|
messages = {
|
|
401: "API Key 验证失败,请检查当前供应商的凭证。",
|
|
403: "当前 API Key 无权访问该模型目录,请检查账号权限和服务地域。",
|
|
404: "模型目录接口不存在,请检查基础地址、地域和接口协议。",
|
|
429: "供应商请求限流,请稍后重试。",
|
|
}
|
|
return messages.get(code, f"供应商模型目录返回 HTTP {code},请稍后重试。")
|
|
if isinstance(exc, httpx.RequestError):
|
|
return "无法连接模型目录,请检查基础地址和网络。"
|
|
return "模型目录响应无效,请稍后重试。"
|
|
|
|
|
|
def _model_rows(payload: object) -> tuple[list[dict[str, object]], dict[str, object]]:
|
|
if not isinstance(payload, dict):
|
|
raise LLMProviderCatalogError("供应商返回了无效的模型目录。")
|
|
envelope = payload.get("output", payload)
|
|
if not isinstance(envelope, dict):
|
|
raise LLMProviderCatalogError("供应商返回了无效的模型目录。")
|
|
rows = envelope.get("data", envelope.get("models"))
|
|
if not isinstance(rows, list):
|
|
raise LLMProviderCatalogError("供应商响应中没有模型列表。")
|
|
if any(not isinstance(row, dict) for row in rows):
|
|
raise LLMProviderCatalogError("供应商返回了无效的模型条目。")
|
|
return rows, envelope
|
|
|
|
|
|
def _model_id(row: dict[str, object], provider: str = "") -> str:
|
|
value = row.get("id") or row.get("model") or row.get("name")
|
|
if not isinstance(value, str) or not value.strip():
|
|
raise LLMProviderCatalogError("供应商返回了缺少 ID 的模型条目。")
|
|
normalized = value.strip()
|
|
if provider.strip().lower() == "gemini" and normalized.startswith("models/"):
|
|
normalized = normalized.removeprefix("models/")
|
|
return normalized
|
|
|
|
|
|
def _model_date(row: dict[str, object]) -> float:
|
|
value = row.get("created_at") or row.get("published_time") or row.get("created")
|
|
if isinstance(value, (int, float)):
|
|
return float(value)
|
|
if isinstance(value, str):
|
|
try:
|
|
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
|
except ValueError:
|
|
pass
|
|
return 0
|
|
|
|
|
|
async def _get_catalog_page(
|
|
client: httpx.AsyncClient,
|
|
url: str,
|
|
headers: dict[str, str],
|
|
params: dict[str, str | int],
|
|
) -> object:
|
|
for attempt in range(CATALOG_REQUEST_ATTEMPTS):
|
|
try:
|
|
response = await client.get(url, headers=headers, params=params)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except httpx.HTTPStatusError as exc:
|
|
if attempt or exc.response.status_code not in {502, 503, 504}:
|
|
raise
|
|
except httpx.TransportError:
|
|
if attempt:
|
|
raise
|
|
await asyncio.sleep(CATALOG_RETRY_DELAY_SECONDS)
|
|
raise LLMProviderCatalogError("模型目录请求失败。")
|
|
|
|
|
|
async def fetch_model_catalog(
|
|
provider: str,
|
|
base_url: str,
|
|
provider_api: str,
|
|
api_key: str = "",
|
|
anthropic_version: str = "2023-06-01",
|
|
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
|
|
*,
|
|
include_auth: bool = True,
|
|
) -> ModelCatalog:
|
|
url = model_catalog_url(provider, base_url, provider_api)
|
|
if not api_key and catalog_requires_api_key(provider, base_url, provider_api):
|
|
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
|
headers = {"User-Agent": "Planet/1.0", "Accept": "application/json"}
|
|
if include_auth and api_key:
|
|
if provider_api == "anthropic-messages" and provider not in {
|
|
"opencode-go",
|
|
"openrouter",
|
|
"alibaba",
|
|
"moonshotai",
|
|
}:
|
|
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
|
|
else:
|
|
headers["Authorization"] = f"Bearer {api_key}"
|
|
native_dashscope = provider == "alibaba" and urlsplit(url).hostname.endswith(".aliyuncs.com")
|
|
params: dict[str, str | int] = {}
|
|
if native_dashscope:
|
|
params = {"page_no": 1, "page_size": CATALOG_PAGE_SIZE, "capabilities": "TG"}
|
|
rows_by_id: dict[str, dict[str, object]] = {}
|
|
timeout = max(1, min(timeout_seconds, CATALOG_TIMEOUT_SECONDS))
|
|
# Bound the complete pagination/retry cycle, not just each individual request.
|
|
async with asyncio.timeout(timeout), httpx.AsyncClient(timeout=timeout) as client:
|
|
for page in range(CATALOG_MAX_PAGES):
|
|
payload = await _get_catalog_page(client, url, headers, params)
|
|
rows, envelope = _model_rows(payload)
|
|
previous_count = len(rows_by_id)
|
|
for row in rows:
|
|
rows_by_id[_model_id(row, provider)] = row
|
|
has_more = envelope.get("has_more") is True
|
|
if native_dashscope:
|
|
total = envelope.get("total")
|
|
if not isinstance(total, int) or total < 0:
|
|
raise LLMProviderCatalogError("供应商返回了无效的模型目录分页信息。")
|
|
has_more = len(rows_by_id) < total
|
|
params["page_no"] = page + 2
|
|
elif has_more:
|
|
cursor = envelope.get("last_id")
|
|
if not isinstance(cursor, str) or not cursor or cursor == params.get("after_id"):
|
|
raise LLMProviderCatalogError("供应商返回了无效的模型目录分页信息。")
|
|
params["after_id"] = cursor
|
|
if not has_more:
|
|
models = sorted(
|
|
rows_by_id, key=lambda key: _model_date(rows_by_id[key]), reverse=True
|
|
)
|
|
# An empty Ollama catalog is valid: no models have been installed yet.
|
|
if not models and provider_api != "ollama-generate":
|
|
raise LLMProviderCatalogError("供应商返回了空模型目录。")
|
|
return ModelCatalog(url=url, models=models)
|
|
if len(rows_by_id) == previous_count:
|
|
raise LLMProviderCatalogError("供应商模型目录分页没有进展。")
|
|
raise LLMProviderCatalogError("供应商模型目录分页超过限制。")
|
|
|
|
|
|
def _aggregator_lock() -> asyncio.Lock:
|
|
loop = asyncio.get_running_loop()
|
|
lock = _AGGREGATOR_LOOP_LOCKS.get(loop)
|
|
if lock is None:
|
|
lock = asyncio.Lock()
|
|
_AGGREGATOR_LOOP_LOCKS[loop] = lock
|
|
return lock
|
|
|
|
|
|
async def _fetch_aggregator_json(url: str, timeout_seconds: int) -> object:
|
|
now = time.monotonic()
|
|
cached = _AGGREGATOR_CACHE.get(url)
|
|
if cached is not None and cached[0] > now:
|
|
return cached[1]
|
|
async with _aggregator_lock():
|
|
now = time.monotonic()
|
|
cached = _AGGREGATOR_CACHE.get(url)
|
|
if cached is not None and cached[0] > now:
|
|
return cached[1]
|
|
timeout = max(1, min(timeout_seconds, CATALOG_TIMEOUT_SECONDS))
|
|
headers = {
|
|
"User-Agent": "Planet/1.0",
|
|
"Accept": "application/json",
|
|
"Accept-Encoding": "gzip",
|
|
}
|
|
async with asyncio.timeout(timeout), httpx.AsyncClient(timeout=timeout) as client:
|
|
payload = await _get_catalog_page(client, url, headers, {})
|
|
_AGGREGATOR_CACHE[url] = (time.monotonic() + AGGREGATOR_CACHE_TTL_SECONDS, payload)
|
|
return payload
|
|
|
|
|
|
def _models_dev_candidate_keys(provider: str, base_url: str) -> tuple[str, ...]:
|
|
provider_key = provider.strip().lower()
|
|
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
|
if provider_key == "minimax":
|
|
if host in {"api.minimaxi.com", "api.minimax.cn"}:
|
|
return ("minimax-cn", "minimax")
|
|
return ("minimax", "minimax-cn")
|
|
if provider_key == "alibaba":
|
|
if "intl" in host:
|
|
return ("alibaba", "alibaba-cn")
|
|
return ("alibaba-cn", "alibaba")
|
|
if provider_key == "moonshotai":
|
|
if host.endswith(".cn"):
|
|
return ("moonshotai-cn", "moonshotai")
|
|
return ("moonshotai", "moonshotai-cn")
|
|
fixed: dict[str, tuple[str, ...]] = {
|
|
"glm": ("zhipuai",),
|
|
"meta": ("meta",),
|
|
"gemini": ("google",),
|
|
"grok": ("xai",),
|
|
"openai": ("openai",),
|
|
"anthropic": ("anthropic",),
|
|
"deepseek": ("deepseek",),
|
|
}
|
|
return fixed.get(provider_key, (provider_key,))
|
|
|
|
|
|
def _is_aggregator_chat_model(model_id: str, output_modalities: object = None) -> bool:
|
|
"""Exclude embeddings, image/audio/video generators, and consumer chat aliases."""
|
|
lower = model_id.strip().lower()
|
|
if not lower:
|
|
return False
|
|
if isinstance(output_modalities, list) and output_modalities:
|
|
mods = {str(item).strip().lower() for item in output_modalities if str(item).strip()}
|
|
if "text" not in mods or (mods & {"image", "video", "audio"}):
|
|
return False
|
|
if "embedding" in lower:
|
|
return False
|
|
if lower.startswith(
|
|
(
|
|
"chatgpt-",
|
|
"dall-e",
|
|
"whisper",
|
|
"tts-",
|
|
"gpt-image",
|
|
"gpt-audio",
|
|
"gpt-realtime",
|
|
"grok-imagine",
|
|
"qwen-mt-",
|
|
)
|
|
):
|
|
return False
|
|
if lower == "gpt-chat-latest" or (lower.startswith("gpt-") and lower.endswith("-chat")):
|
|
return False
|
|
if any(token in lower for token in ("-image", "-tts", "-asr", "-live-", "-realtime", "-video")):
|
|
return False
|
|
return True
|
|
|
|
|
|
def _is_general_aggregator_model(model_id: str) -> bool:
|
|
"""Rank general-purpose flagship chat models ahead of vertical or experimental variants."""
|
|
lower = model_id.strip().lower()
|
|
if lower.startswith(("gpt-daybreak-", "deep-research-")):
|
|
return False
|
|
if lower.endswith(("-healthcare", "-legal", "-contributor", "-exp")):
|
|
return False
|
|
return True
|
|
|
|
|
|
def _extract_models_dev_models(
|
|
payload: object, provider: str, base_url: str
|
|
) -> ModelCatalog | None:
|
|
if not isinstance(payload, dict):
|
|
return None
|
|
for key in _models_dev_candidate_keys(provider, base_url):
|
|
entry = payload.get(key)
|
|
if not isinstance(entry, dict):
|
|
continue
|
|
raw_models = entry.get("models")
|
|
if not isinstance(raw_models, dict):
|
|
continue
|
|
candidates: list[tuple[bool, bool, str, str]] = []
|
|
for model_id, meta in raw_models.items():
|
|
if not isinstance(model_id, str) or not model_id.strip() or not isinstance(meta, dict):
|
|
continue
|
|
modalities = meta.get("modalities")
|
|
output_mods = modalities.get("output") if isinstance(modalities, dict) else None
|
|
if not _is_aggregator_chat_model(model_id, output_mods):
|
|
continue
|
|
active = str(meta.get("status") or "").strip().lower() != "deprecated"
|
|
release_date = str(meta.get("release_date") or "")
|
|
candidates.append(
|
|
(active, _is_general_aggregator_model(model_id), release_date, model_id.strip())
|
|
)
|
|
if candidates:
|
|
candidates.sort(key=lambda item: (item[0], item[1], item[2], item[3]), reverse=True)
|
|
return ModelCatalog(
|
|
url=f"{MODELS_DEV_CATALOG_URL}#{key}",
|
|
models=[item[3] for item in candidates],
|
|
)
|
|
return None
|
|
|
|
|
|
def _extract_openrouter_models(payload: object, provider: str) -> ModelCatalog | None:
|
|
provider_key = provider.strip().lower()
|
|
prefix = AGGREGATOR_OPENROUTER_PREFIXES.get(provider_key, "")
|
|
if not prefix:
|
|
return None
|
|
try:
|
|
rows, _ = _model_rows(payload)
|
|
except LLMProviderCatalogError:
|
|
return None
|
|
dated: list[tuple[bool, float, str]] = []
|
|
seen: set[str] = set()
|
|
for row in rows:
|
|
raw_id = row.get("id")
|
|
if not isinstance(raw_id, str) or not raw_id.startswith(prefix):
|
|
continue
|
|
model_id = raw_id[len(prefix) :].strip()
|
|
if not model_id or ":" in model_id or model_id in seen:
|
|
continue
|
|
arch = row.get("architecture")
|
|
output_mods = arch.get("output_modalities") if isinstance(arch, dict) else None
|
|
if not _is_aggregator_chat_model(model_id, output_mods):
|
|
continue
|
|
seen.add(model_id)
|
|
dated.append((_is_general_aggregator_model(model_id), _model_date(row), model_id))
|
|
if not dated:
|
|
return None
|
|
dated.sort(key=lambda item: (item[0], item[1], item[2]), reverse=True)
|
|
return ModelCatalog(
|
|
url=f"{OPENROUTER_CATALOG_URL}#{provider_key}",
|
|
models=[item[2] for item in dated],
|
|
)
|
|
|
|
|
|
async def fetch_aggregator_model_catalog(
|
|
provider: str,
|
|
base_url: str,
|
|
provider_api: str,
|
|
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
|
|
) -> ModelCatalog:
|
|
"""Fetch public model catalog for a keyless official-host provider via aggregators."""
|
|
model_catalog_url(provider, base_url, provider_api)
|
|
if not catalog_supports_aggregator_fallback(provider, base_url, provider_api):
|
|
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
|
|
|
try:
|
|
models_dev_payload = await _fetch_aggregator_json(MODELS_DEV_CATALOG_URL, timeout_seconds)
|
|
catalog = _extract_models_dev_models(models_dev_payload, provider, base_url)
|
|
if catalog is not None and catalog.models:
|
|
return catalog
|
|
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
|
|
pass
|
|
|
|
try:
|
|
openrouter_payload = await _fetch_aggregator_json(OPENROUTER_CATALOG_URL, timeout_seconds)
|
|
catalog = _extract_openrouter_models(openrouter_payload, provider)
|
|
if catalog is not None and catalog.models:
|
|
return catalog
|
|
except (httpx.HTTPError, TimeoutError, LLMProviderCatalogError, ValueError):
|
|
pass
|
|
|
|
raise LLMProviderCatalogError("公共聚合模型目录暂不可用,请稍后重试或配置 API Key。")
|