200 lines
6.8 KiB
Python
200 lines
6.8 KiB
Python
"""Model catalog with a small provider-aware on-disk cache."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import time
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Any
|
|
from urllib.parse import urlsplit
|
|
|
|
import httpx
|
|
|
|
from .utils import atomic_write_json, read_json
|
|
|
|
CACHE_DIR = Path.home() / ".cache" / "airouter"
|
|
CACHE_TTL = 60 * 60 * 24
|
|
USER_AGENT = "airouter/0.1 (OpenCode Go compatible orchestrator)"
|
|
|
|
STATIC_MODELS: list[dict[str, Any]] = [
|
|
{"id": "deepseek-v4.1-flash", "name": "DeepSeek V4.1 Flash", "context": 1_000_000},
|
|
{"id": "deepseek-v4-pro", "name": "DeepSeek V4 Pro", "context": 1_000_000},
|
|
{"id": "glm-5.3-flash", "name": "GLM-5.3 Flash", "context": 200_000},
|
|
{"id": "glm-5.3", "name": "GLM-5.3", "context": 200_000},
|
|
{"id": "kimi-k2.7-code", "name": "Kimi K2.7 Code", "context": 256_000},
|
|
{"id": "kimi-k3.1-pro", "name": "Kimi K3.1 Pro", "context": 256_000},
|
|
{"id": "qwen3.8-flash", "name": "Qwen3.8 Flash", "context": 256_000},
|
|
{"id": "qwen4-max", "name": "Qwen4 Max", "context": 256_000},
|
|
{"id": "minimax-m3.1-flash", "name": "MiniMax M3.1 Flash", "context": 512_000},
|
|
{"id": "gpt-6-luna", "name": "GPT-6 Luna", "context": 272_000},
|
|
{"id": "claude-haiku-5-5", "name": "Claude Haiku 5.5", "context": 200_000},
|
|
{"id": "grok-4.7", "name": "Grok 4.7", "context": 200_000},
|
|
]
|
|
|
|
|
|
@dataclass
|
|
class ModelInfo:
|
|
id: str
|
|
name: str = ""
|
|
context: int | None = None
|
|
output: int | None = None
|
|
tools: bool = True
|
|
reasoning: bool = False
|
|
input_price: float | None = None
|
|
output_price: float | None = None
|
|
description: str = ""
|
|
provider: str = ""
|
|
provider_name: str = ""
|
|
|
|
@classmethod
|
|
def from_api(
|
|
cls,
|
|
raw: dict[str, Any] | str,
|
|
*,
|
|
provider: str = "",
|
|
profile_name: str = "",
|
|
) -> ModelInfo:
|
|
if isinstance(raw, str):
|
|
raw = {"id": raw}
|
|
limit = raw.get("limit") or {}
|
|
capabilities = raw.get("capabilities") or {}
|
|
cost = ((raw.get("cost") or {}).get("text") or {})
|
|
input_cost = (cost.get("input") or {}).get("price")
|
|
output_cost = (cost.get("output") or {}).get("price")
|
|
return cls(
|
|
id=str(raw.get("id") or raw.get("name") or ""),
|
|
name=str(raw.get("name") or raw.get("id") or raw.get("name") or ""),
|
|
context=_as_int(limit.get("context")),
|
|
output=_as_int(limit.get("output")),
|
|
tools=bool((capabilities.get("tools") or {}).get("supported", True)),
|
|
reasoning=bool((capabilities.get("reasoning") or {}).get("supported", False)),
|
|
input_price=_as_float(input_cost),
|
|
output_price=_as_float(output_cost),
|
|
description=str(raw.get("description") or ""),
|
|
provider=provider,
|
|
provider_name=profile_name or provider,
|
|
)
|
|
|
|
|
|
def _as_int(value: Any) -> int | None:
|
|
try:
|
|
return int(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _as_float(value: Any) -> float | None:
|
|
try:
|
|
return float(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _is_opencode_url(base_url: str) -> bool:
|
|
try:
|
|
host = (urlsplit(base_url).hostname or "").lower()
|
|
except ValueError:
|
|
return False
|
|
return host == "opencode.ai" or host.endswith(".opencode.ai")
|
|
|
|
|
|
def _cache_path(base_url: str, provider: str = "") -> Path:
|
|
key = json.dumps([base_url.rstrip("/"), provider], ensure_ascii=False)
|
|
digest = hashlib.sha256(key.encode()).hexdigest()[:12]
|
|
return CACHE_DIR / f"models-{digest}.json"
|
|
|
|
|
|
def model_ref(provider_id: str, model: str) -> str:
|
|
"""Build a display/reference string without duplicating an existing prefix."""
|
|
if not provider_id or model.startswith(provider_id + "/"):
|
|
return model
|
|
return f"{provider_id}/{model}"
|
|
|
|
|
|
def fetch_models(
|
|
base_url: str,
|
|
*,
|
|
token: str | None = None,
|
|
refresh: bool = False,
|
|
timeout: float = 15,
|
|
provider: str = "",
|
|
profile_name: str = "",
|
|
provider_name: str | None = None,
|
|
strict: bool = False,
|
|
) -> list[ModelInfo]:
|
|
if provider_name is not None:
|
|
profile_name = provider_name
|
|
is_opencode = _is_opencode_url(base_url)
|
|
if not provider and is_opencode:
|
|
provider = "opencode"
|
|
if not profile_name and provider == "opencode":
|
|
profile_name = "OpenCode"
|
|
|
|
path = _cache_path(base_url, provider)
|
|
if not refresh:
|
|
cached = read_json(path)
|
|
if isinstance(cached, dict) and time.time() - cached.get("fetched_at", 0) < CACHE_TTL:
|
|
raw_cached = cached.get("models", [])
|
|
if isinstance(raw_cached, list):
|
|
models = [
|
|
ModelInfo.from_api(item, provider=provider, profile_name=profile_name)
|
|
for item in raw_cached
|
|
if isinstance(item, dict) and (item.get("id") or item.get("name"))
|
|
]
|
|
if models:
|
|
return models
|
|
|
|
url = base_url.rstrip("/") + "/models"
|
|
headers = {"User-Agent": USER_AGENT}
|
|
# OpenCode's model catalog is public; sending a bad/expired token can turn
|
|
# a public 200 into a 401, so don't attach auth for it.
|
|
if token and not is_opencode:
|
|
headers["Authorization"] = f"Bearer {token}"
|
|
try:
|
|
with httpx.Client(timeout=timeout) as client:
|
|
response = client.get(url, headers=headers)
|
|
response.raise_for_status()
|
|
payload = response.json()
|
|
if isinstance(payload, dict):
|
|
raw_models = payload.get("data")
|
|
if not isinstance(raw_models, list):
|
|
raw_models = payload.get("models")
|
|
elif isinstance(payload, list):
|
|
raw_models = payload
|
|
else:
|
|
raw_models = None
|
|
if not isinstance(raw_models, list):
|
|
raise ValueError("unexpected /models payload")
|
|
normalized = [
|
|
item if isinstance(item, dict) else {"id": str(item)} for item in raw_models
|
|
]
|
|
models = [
|
|
ModelInfo.from_api(item, provider=provider, profile_name=profile_name)
|
|
for item in normalized
|
|
if item.get("id") or item.get("name")
|
|
]
|
|
atomic_write_json(path, {"fetched_at": time.time(), "models": normalized})
|
|
if models:
|
|
return models
|
|
except Exception:
|
|
if strict:
|
|
raise
|
|
|
|
# STATIC_MODELS describes OpenCode only. Returning it for an unavailable
|
|
# local/custom endpoint would make a failed catalog look successful.
|
|
if is_opencode:
|
|
return [
|
|
ModelInfo.from_api(item, provider=provider, profile_name=profile_name)
|
|
for item in STATIC_MODELS
|
|
]
|
|
return []
|
|
|
|
|
|
def model_line(model: str, catalog: list[ModelInfo]) -> str:
|
|
for item in catalog:
|
|
if item.id == model or item.name == model:
|
|
return item.name
|
|
return model
|