Download app/providers.py from simonu5/TriChat: direct link, hf CLI and curl.
- Browser
- Download file 3.94 kB
-
https://huggingface.co/spaces/simonu5/TriChat/resolve/main/app/providers.py
- Command line
-
hf download hf://spaces/simonu5/TriChat/app/providers.py
-
curl -L -o providers.py https://huggingface.co/spaces/simonu5/TriChat/resolve/main/app/providers.py
3.94 kB
| """模型提供商:在前端「🤖 模型」面板裡新增,數量不限,存在 Turso。 | |
| 每個提供商 = 一個 OpenAI 相容端點 + key + 你挑選的模型清單。 | |
| 只用你手動選的模型,不自動切換、不預設模型。 | |
| key 可以直接填,也可以填 ${VAR} 從 Space Secrets 讀。 | |
| """ | |
| import json | |
| import os | |
| import re | |
| import uuid | |
| import httpx | |
| from . import db as store | |
| SEP = "::" # 選定模型的格式:提供商id::模型id | |
| MASK = "••••" | |
| _VAR = re.compile(r"^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$") | |
| def _resolve_key(k: str) -> str: | |
| m = _VAR.match((k or "").strip()) | |
| return os.environ.get(m.group(1), "") if m else (k or "") | |
| def _mask(k: str) -> str: | |
| if not k: | |
| return "" | |
| if _VAR.match(k.strip()): | |
| return k # ${VAR} 不是秘密,照原樣顯示 | |
| return MASK + k[-4:] | |
| async def _stored() -> list[dict]: | |
| raw = await store.get_setting("providers") | |
| try: | |
| data = json.loads(raw) if raw else [] | |
| except json.JSONDecodeError: | |
| data = [] | |
| return data if isinstance(data, list) else [] | |
| async def get_all() -> list[dict]: | |
| """所有提供商(含真實 key)。""" | |
| return [p for p in await _stored() if isinstance(p, dict)] | |
| async def public() -> dict: | |
| ps = [{**p, "api_key": _mask(p.get("api_key", ""))} for p in await get_all()] | |
| return {"providers": ps, | |
| "selected": await store.get_setting("model") or ""} | |
| async def save(providers: list[dict], selected: str | None): | |
| old = {p.get("id"): p for p in await _stored()} | |
| out = [] | |
| for p in providers: | |
| pid = p.get("id") or uuid.uuid4().hex[:8] | |
| key = (p.get("api_key") or "").strip() | |
| if key.startswith(MASK): # 沒改 key → 沿用舊的 | |
| key = old.get(pid, {}).get("api_key", "") | |
| models = p.get("models") or [] | |
| if isinstance(models, str): | |
| models = models.split(",") | |
| out.append({"id": pid, "name": (p.get("name") or "未命名").strip()[:60], | |
| "base_url": (p.get("base_url") or "").strip().rstrip("/"), | |
| "api_key": key, "models": [m.strip() for m in models if m.strip()], | |
| "available": [str(m) for m in (p.get("available") or [])][:5000], # 上次拉取的完整清單 | |
| "enabled": bool(p.get("enabled", True))}) | |
| await store.set_setting("providers", json.dumps(out, ensure_ascii=False)) | |
| if selected is not None: | |
| await store.set_setting("model", selected) | |
| async def resolve(selected: str | None = None) -> tuple[dict, str] | None: | |
| """找出要用的 (提供商, 模型):對話自己的選擇優先,其次是全域選擇。找不到就回 None,不會自己挑。""" | |
| for sel in (selected, await store.get_setting("model")): | |
| if sel and SEP in sel: | |
| pid, model = sel.split(SEP, 1) | |
| for p in await get_all(): | |
| if p.get("id") == pid and p.get("enabled", True) and model in (p.get("models") or []): | |
| return p, model | |
| return None | |
| def key_of(p: dict) -> str: | |
| return _resolve_key(p.get("api_key", "")) | |
| async def label() -> str: | |
| r = await resolve() | |
| return f"{r[0]['name']} · {r[1]}" if r else "尚未選擇模型" | |
| async def list_models(base_url: str, api_key: str, pid: str | None = None) -> list[str]: | |
| if api_key.startswith(MASK) and pid: | |
| api_key = next((p.get("api_key", "") for p in await get_all() if p.get("id") == pid), "") | |
| async with httpx.AsyncClient(timeout=30) as c: | |
| r = await c.get(base_url.rstrip("/") + "/models", | |
| headers={"Authorization": f"Bearer {_resolve_key(api_key)}"}) | |
| r.raise_for_status() | |
| data = r.json() | |
| items = data.get("data", data) if isinstance(data, dict) else data | |
| ids = [str(m.get("id")) for m in items if isinstance(m, dict) and m.get("id")] | |
| return sorted({i.removeprefix("models/") for i in ids}) | |