1"""Model catalog with a small on-disk cache."""
2
3from __future__ import annotations
4
5import hashlib
6import time
7from dataclasses import dataclass
8from pathlib import Path
9from typing import Any
10
11import httpx
12
13from .utils import atomic_write_json, read_json
14
15CACHE_DIR = Path.home() / ".cache" / "airouter"
16CACHE_TTL = 60 * 60 * 24
17USER_AGENT = "airouter/0.1 (OpenCode Go compatible orchestrator)"
18
19STATIC_MODELS: list[dict[str, Any]] = [
20 {"id": "deepseek-v4.1-flash", "name": "DeepSeek V4.1 Flash", "context": 1_000_000},
21 {"id": "deepseek-v4-pro", "name": "DeepSeek V4 Pro", "context": 1_000_000},
22 {"id": "glm-5.3-flash", "name": "GLM-5.3 Flash", "context": 200_000},
23 {"id": "glm-5.3", "name": "GLM-5.3", "context": 200_000},
24 {"id": "kimi-k2.7-code", "name": "Kimi K2.7 Code", "context": 256_000},
25 {"id": "kimi-k3.1-pro", "name": "Kimi K3.1 Pro", "context": 256_000},
26 {"id": "qwen3.8-flash", "name": "Qwen3.8 Flash", "context": 256_000},
27 {"id": "qwen4-max", "name": "Qwen4 Max", "context": 256_000},
28 {"id": "minimax-m3.1-flash", "name": "MiniMax M3.1 Flash", "context": 512_000},
29 {"id": "gpt-6-luna", "name": "GPT-6 Luna", "context": 272_000},
30 {"id": "claude-haiku-5-5", "name": "Claude Haiku 5.5", "context": 200_000},
31 {"id": "grok-4.7", "name": "Grok 4.7", "context": 200_000},
32]
33
34
35@dataclass
36class ModelInfo:
37 id: str
38 name: str = ""
39 context: int | None = None
40 output: int | None = None
41 tools: bool = True
42 reasoning: bool = False
43 input_price: float | None = None
44 output_price: float | None = None
45 description: str = ""
46
47 @classmethod
48 def from_api(cls, raw: dict[str, Any]) -> ModelInfo:
49 limit = raw.get("limit") or {}
50 capabilities = raw.get("capabilities") or {}
51 cost = ((raw.get("cost") or {}).get("text") or {})
52 input_cost = (cost.get("input") or {}).get("price")
53 output_cost = (cost.get("output") or {}).get("price")
54 return cls(
55 id=str(raw.get("id", "")),
56 name=str(raw.get("name") or raw.get("id") or ""),
57 context=_as_int(limit.get("context")),
58 output=_as_int(limit.get("output")),
59 tools=bool((capabilities.get("tools") or {}).get("supported", True)),
60 reasoning=bool((capabilities.get("reasoning") or {}).get("supported", False)),
61 input_price=_as_float(input_cost),
62 output_price=_as_float(output_cost),
63 description=str(raw.get("description") or ""),
64 )
65
66
67def _as_int(value: Any) -> int | None:
68 try:
69 return int(value)
70 except (TypeError, ValueError):
71 return None
72
73
74def _as_float(value: Any) -> float | None:
75 try:
76 return float(value)
77 except (TypeError, ValueError):
78 return None
79
80
81def _cache_path(base_url: str) -> Path:
82 digest = hashlib.sha256(base_url.encode()).hexdigest()[:12]
83 return CACHE_DIR / f"models-{digest}.json"
84
85
86def fetch_models(
87 base_url: str,
88 *,
89 token: str | None = None,
90 refresh: bool = False,
91 timeout: float = 15,
92) -> list[ModelInfo]:
93 path = _cache_path(base_url)
94 if not refresh:
95 cached = read_json(path)
96 if isinstance(cached, dict) and time.time() - cached.get("fetched_at", 0) < CACHE_TTL:
97 models = [ModelInfo.from_api(item) for item in cached.get("models", [])]
98 if models:
99 return models
100
101 url = base_url.rstrip("/") + "/models"
102 headers = {"User-Agent": USER_AGENT}
103 # OpenCode's model catalog is public; sending a bad/expired token can turn
104 # a public 200 into a 401, so don't attach auth for it.
105 if token and "opencode.ai" not in base_url:
106 headers["Authorization"] = f"Bearer {token}"
107 try:
108 with httpx.Client(timeout=timeout) as client:
109 response = client.get(url, headers=headers)
110 response.raise_for_status()
111 payload = response.json()
112 raw_models = payload.get("data") if isinstance(payload, dict) else None
113 if not isinstance(raw_models, list):
114 raise ValueError("unexpected /models payload")
115 models = [ModelInfo.from_api(item) for item in raw_models if item.get("id")]
116 atomic_write_json(path, {"fetched_at": time.time(), "models": raw_models})
117 if models:
118 return models
119 except Exception:
120 pass
121
122 return [ModelInfo(**item) for item in STATIC_MODELS]
123
124
125def model_line(model: str, catalog: list[ModelInfo]) -> str:
126 for item in catalog:
127 if item.id == model or item.name == model:
128 return item.name
129 return model