| """Loads models.json and resolves client model names to target lists.""" |
| from __future__ import annotations |
|
|
| import json |
| import logging |
| import os |
| import urllib.request |
| from pathlib import Path |
| from typing import Dict, List, Optional, Tuple |
|
|
| from cryptography.fernet import Fernet |
|
|
| logger = logging.getLogger("router.config") |
|
|
|
|
| def _fetch_models(url: str, aes_key: str) -> dict: |
| """Download + Fernet-decrypt models.json from a URL (e.g. a raw gist). |
| |
| The gist stores the encrypted token (Fernet.encrypt output), NOT raw JSON. |
| We fetch the bytes, decrypt with AES_KEY, then parse to a dict. |
| """ |
| logger.info("fetching models.json from %s", url[:60]) |
| req = urllib.request.Request(url, headers={"User-Agent": "router"}) |
| with urllib.request.urlopen(req, timeout=30) as r: |
| token = r.read() |
| plaintext = Fernet(aes_key.encode()).decrypt(token).decode("utf-8") |
| return json.loads(plaintext) |
|
|
|
|
| class ModelConfig: |
| def __init__(self, data_dir: Path): |
| self.models: Dict[str, dict] = {} |
| self._lookup: Dict[str, str] = {} |
| self._load(data_dir / "models.json") |
|
|
| def _load(self, path: Path) -> None: |
| |
| |
| |
| url = os.environ.get("MODELS_URL", "").strip() |
| aes_key = os.environ.get("AES_KEY", "").strip() |
| if url and aes_key: |
| raw = _fetch_models(url, aes_key) |
| else: |
| raw = json.loads(path.read_text(encoding="utf-8")) |
| self.models = raw |
| for name in raw: |
| self._lookup[name.lower()] = name |
|
|
| def resolve(self, requested: Optional[str]) -> Tuple[Optional[str], Optional[List[dict]]]: |
| """Map a client model name to (exact_name, targets). Returns (None, None) if unknown.""" |
| exact = self._lookup.get((requested or "").strip().lower()) |
| if exact is None: |
| return None, None |
| return exact, self.models[exact].get("targets", []) |
|
|
| def list_models(self) -> List[dict]: |
| out = [] |
| for name, cfg in self.models.items(): |
| out.append({ |
| "id": name, |
| "object": "model", |
| "targets": len(cfg.get("targets", [])), |
| }) |
| return out |
|
|
| def total_targets(self) -> int: |
| return sum(len(c.get("targets", [])) for c in self.models.values()) |
|
|