Spaces:
Sleeping
Sleeping
Deploy: Stack A (NIM brain + Maverick judge + Sarvam voice). D-019.
Browse files- .env.example +20 -0
- backend/admin.py +138 -0
- backend/config.py +11 -0
- backend/llm_health.py +65 -4
- backend/providers/groq_llm.py +107 -0
- backend/providers/nvidia_nim_llm.py +143 -11
- backend/providers/openrouter_llm.py +115 -0
- frontend/public/admin/llm-control.html +278 -29
.env.example
CHANGED
|
@@ -13,6 +13,26 @@ VOYAGE_API_KEY=pa-your_voyage_key_here
|
|
| 13 |
# Free tier: 40 req/min, no daily cap, no card. Get a key at https://build.nvidia.com.
|
| 14 |
NVIDIA_NIM_API_KEY=nvapi-your_nim_key_here
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# Hugging Face β used by tools/upload_*.py for Space + dataset sync
|
| 17 |
HF_TOKEN=hf_your_token_here
|
| 18 |
|
|
|
|
| 13 |
# Free tier: 40 req/min, no daily cap, no card. Get a key at https://build.nvidia.com.
|
| 14 |
NVIDIA_NIM_API_KEY=nvapi-your_nim_key_here
|
| 15 |
|
| 16 |
+
# ---------------------------------------------------------------------------
|
| 17 |
+
# CROSS-PROVIDER FALLBACKS (optional but recommended)
|
| 18 |
+
# ---------------------------------------------------------------------------
|
| 19 |
+
# Last-resort entries appended to BRAIN_CHAIN + FAST_BRAIN_CHAIN + JUDGE_CHAIN
|
| 20 |
+
# so the brain + judge survive a FULL NIM outage (regional ingress brownout,
|
| 21 |
+
# pool-wide 5xx, DNS, etc.). NIM remains primary β these only get hit after
|
| 22 |
+
# every NIM candidate in the chain has failed. Both keys are optional: if
|
| 23 |
+
# unset the corresponding fallback is simply skipped and the chain continues.
|
| 24 |
+
|
| 25 |
+
# OpenRouter β aggregates dozens of free + paid OSS models behind one API.
|
| 26 |
+
# Free-tier model 'openai/gpt-oss-120b' is the cross-provider fallback used
|
| 27 |
+
# in BRAIN_CHAIN + JUDGE_CHAIN. Get a key at https://openrouter.ai/keys
|
| 28 |
+
OPENROUTER_API_KEY=sk-or-your_openrouter_key_here
|
| 29 |
+
|
| 30 |
+
# Groq β LPU inference, lowest TTFT of any free-tier 70B option.
|
| 31 |
+
# 'llama-3.3-70b-versatile' is the cross-provider fallback used at the bottom
|
| 32 |
+
# of BRAIN_CHAIN + FAST_BRAIN_CHAIN + JUDGE_CHAIN. Get a key at
|
| 33 |
+
# https://console.groq.com/keys
|
| 34 |
+
GROQ_API_KEY=gsk_your_groq_key_here
|
| 35 |
+
|
| 36 |
# Hugging Face β used by tools/upload_*.py for Space + dataset sync
|
| 37 |
HF_TOKEN=hf_your_token_here
|
| 38 |
|
backend/admin.py
CHANGED
|
@@ -24,6 +24,7 @@ from __future__ import annotations
|
|
| 24 |
import asyncio
|
| 25 |
import json
|
| 26 |
import os
|
|
|
|
| 27 |
from pathlib import Path
|
| 28 |
from typing import Optional
|
| 29 |
|
|
@@ -35,6 +36,11 @@ from backend import llm_health
|
|
| 35 |
router = APIRouter()
|
| 36 |
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
def _ip_allowed(client_ip: str) -> bool:
|
| 39 |
"""Allowlist check. Empty/unset allowlist => deny everyone."""
|
| 40 |
allowed = os.environ.get("ADMIN_IP_ALLOWLIST", "").strip()
|
|
@@ -130,3 +136,135 @@ async def admin_chain_set(
|
|
| 130 |
override_path.write_text(json.dumps(state, indent=2) + "\n")
|
| 131 |
|
| 132 |
return {"ok": True, "role": body.role, "new_chain": body.order}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
import asyncio
|
| 25 |
import json
|
| 26 |
import os
|
| 27 |
+
from collections import deque
|
| 28 |
from pathlib import Path
|
| 29 |
from typing import Optional
|
| 30 |
|
|
|
|
| 36 |
router = APIRouter()
|
| 37 |
|
| 38 |
|
| 39 |
+
# Cap how many tail lines of data/llm_usage.jsonl we hold in memory while
|
| 40 |
+
# computing per-role stats. 1000 lines @ ~150B each = ~150 KB peak β bounded.
|
| 41 |
+
USAGE_TAIL_LINES = 1000
|
| 42 |
+
|
| 43 |
+
|
| 44 |
def _ip_allowed(client_ip: str) -> bool:
|
| 45 |
"""Allowlist check. Empty/unset allowlist => deny everyone."""
|
| 46 |
allowed = os.environ.get("ADMIN_IP_ALLOWLIST", "").strip()
|
|
|
|
| 136 |
override_path.write_text(json.dumps(state, indent=2) + "\n")
|
| 137 |
|
| 138 |
return {"ok": True, "role": body.role, "new_chain": body.order}
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ---------------------------------------------------------------------------
|
| 142 |
+
# /api/admin/usage β per-role usage stats + next-best-recommended
|
| 143 |
+
# ---------------------------------------------------------------------------
|
| 144 |
+
|
| 145 |
+
def _tail_jsonl(path: Path, n: int) -> list[dict]:
|
| 146 |
+
"""Read the last `n` lines of a JSONL file, returning parsed dicts.
|
| 147 |
+
|
| 148 |
+
Bad lines are skipped silently. Returns [] when the file doesn't exist β
|
| 149 |
+
backward-compatible behavior so the endpoint stays alive before any usage
|
| 150 |
+
has been logged.
|
| 151 |
+
"""
|
| 152 |
+
if not path.exists():
|
| 153 |
+
return []
|
| 154 |
+
try:
|
| 155 |
+
# File is bounded by the 1 MB rotation cap in nvidia_nim_llm._append_usage,
|
| 156 |
+
# so reading the whole thing and slicing tail is fine; deque keeps memory
|
| 157 |
+
# bounded even when no rotation has happened yet.
|
| 158 |
+
with path.open("r", encoding="utf-8", errors="replace") as f:
|
| 159 |
+
tail = deque(f, maxlen=n)
|
| 160 |
+
out: list[dict] = []
|
| 161 |
+
for line in tail:
|
| 162 |
+
line = line.strip()
|
| 163 |
+
if not line:
|
| 164 |
+
continue
|
| 165 |
+
try:
|
| 166 |
+
out.append(json.loads(line))
|
| 167 |
+
except Exception:
|
| 168 |
+
continue # skip malformed line, keep going
|
| 169 |
+
return out
|
| 170 |
+
except Exception:
|
| 171 |
+
return []
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _stat_block_for_role(rows: list[dict], role: str, chain: list[str],
|
| 175 |
+
health_state: dict) -> dict:
|
| 176 |
+
"""Compute the per-role JSON payload (see endpoint docstring for shape)."""
|
| 177 |
+
role_rows = [r for r in rows if r.get("role") == role]
|
| 178 |
+
total = len(role_rows)
|
| 179 |
+
success_count = sum(1 for r in role_rows if r.get("success") is True)
|
| 180 |
+
success_rate = (success_count / total) if total else 0.0
|
| 181 |
+
|
| 182 |
+
# Group by served_model (skip rows with no served_model β those are total
|
| 183 |
+
# failures already captured in the role-level success_rate).
|
| 184 |
+
by_model: dict[str, dict] = {}
|
| 185 |
+
for r in role_rows:
|
| 186 |
+
m = r.get("served_model")
|
| 187 |
+
if not m:
|
| 188 |
+
continue
|
| 189 |
+
bucket = by_model.setdefault(m, {"calls": 0, "latency_sum": 0,
|
| 190 |
+
"success_count": 0})
|
| 191 |
+
bucket["calls"] += 1
|
| 192 |
+
try:
|
| 193 |
+
bucket["latency_sum"] += int(r.get("latency_ms") or 0)
|
| 194 |
+
except Exception:
|
| 195 |
+
pass
|
| 196 |
+
if r.get("success") is True:
|
| 197 |
+
bucket["success_count"] += 1
|
| 198 |
+
|
| 199 |
+
by_model_list = []
|
| 200 |
+
total_served = sum(b["calls"] for b in by_model.values()) or 1
|
| 201 |
+
for m, b in by_model.items():
|
| 202 |
+
avg_lat = int(b["latency_sum"] / b["calls"]) if b["calls"] else 0
|
| 203 |
+
m_success = (b["success_count"] / b["calls"]) if b["calls"] else 0.0
|
| 204 |
+
by_model_list.append({
|
| 205 |
+
"model": m,
|
| 206 |
+
"calls": b["calls"],
|
| 207 |
+
"share": round(b["calls"] / total_served, 4) if total_served else 0.0,
|
| 208 |
+
"avg_latency_ms": avg_lat,
|
| 209 |
+
"success_rate": round(m_success, 4),
|
| 210 |
+
})
|
| 211 |
+
by_model_list.sort(key=lambda x: -x["calls"])
|
| 212 |
+
|
| 213 |
+
primary_model = chain[0] if chain else None
|
| 214 |
+
|
| 215 |
+
# next_best_recommended: highest-position model in the chain (after the
|
| 216 |
+
# primary) whose llm_health status is 'healthy'. If none are healthy,
|
| 217 |
+
# fall back to chain[1] with next_best_is_unverified=true so the UI can
|
| 218 |
+
# flag the recommendation as unproven.
|
| 219 |
+
next_best = None
|
| 220 |
+
next_best_unverified = False
|
| 221 |
+
for m in chain[1:]:
|
| 222 |
+
h = health_state.get(m)
|
| 223 |
+
status = getattr(h, "status", None) if h else None
|
| 224 |
+
if status == "healthy":
|
| 225 |
+
next_best = m
|
| 226 |
+
break
|
| 227 |
+
if next_best is None:
|
| 228 |
+
next_best = chain[1] if len(chain) > 1 else None
|
| 229 |
+
next_best_unverified = next_best is not None
|
| 230 |
+
|
| 231 |
+
return {
|
| 232 |
+
"total_calls_24h": total,
|
| 233 |
+
"success_rate": round(success_rate, 4),
|
| 234 |
+
"by_model": by_model_list,
|
| 235 |
+
"primary_model": primary_model,
|
| 236 |
+
"next_best_recommended": next_best,
|
| 237 |
+
"next_best_is_unverified": next_best_unverified,
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@router.get("/api/admin/usage")
|
| 242 |
+
async def admin_usage(
|
| 243 |
+
request: Request,
|
| 244 |
+
x_admin_password: Optional[str] = Header(default=None, alias="X-Admin-Password"),
|
| 245 |
+
):
|
| 246 |
+
"""Per-role usage stats over the last USAGE_TAIL_LINES log entries.
|
| 247 |
+
|
| 248 |
+
Backward-compatible: if data/llm_usage.jsonl doesn't exist yet, returns
|
| 249 |
+
zero-stat blocks with primary_model = current chain[0]. The frontend can
|
| 250 |
+
render an empty-state without any extra branching.
|
| 251 |
+
"""
|
| 252 |
+
_check_admin(request, x_admin_password)
|
| 253 |
+
|
| 254 |
+
# Live (post-override) chains β read attributes off the module so any
|
| 255 |
+
# admin reorder applied in the current process is reflected immediately.
|
| 256 |
+
from backend.providers import nvidia_nim_llm as nim
|
| 257 |
+
chains = {
|
| 258 |
+
"brain": list(getattr(nim, "BRAIN_CHAIN", [])),
|
| 259 |
+
"fast_brain": list(getattr(nim, "FAST_BRAIN_CHAIN", [])),
|
| 260 |
+
"judge": list(getattr(nim, "JUDGE_CHAIN", [])),
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
usage_path = Path(__file__).resolve().parent.parent / "data" / "llm_usage.jsonl"
|
| 264 |
+
rows = _tail_jsonl(usage_path, USAGE_TAIL_LINES)
|
| 265 |
+
health_state = llm_health.load() # {model: ModelHealth} dict
|
| 266 |
+
|
| 267 |
+
return {
|
| 268 |
+
role: _stat_block_for_role(rows, role, chains[role], health_state)
|
| 269 |
+
for role in ("brain", "fast_brain", "judge")
|
| 270 |
+
}
|
backend/config.py
CHANGED
|
@@ -27,6 +27,17 @@ class Settings:
|
|
| 27 |
# 2026-05-14 in favor of single-provider consolidation β see D-019).
|
| 28 |
NVIDIA_NIM_API_KEY: str = os.environ.get("NVIDIA_NIM_API_KEY", "")
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
# Sarvam endpoints (voice STT/TTS + Indic translation only β not brain anymore)
|
| 31 |
SARVAM_BASE_URL: str = "https://api.sarvam.ai"
|
| 32 |
SARVAM_STT_PATH: str = "/speech-to-text"
|
|
|
|
| 27 |
# 2026-05-14 in favor of single-provider consolidation β see D-019).
|
| 28 |
NVIDIA_NIM_API_KEY: str = os.environ.get("NVIDIA_NIM_API_KEY", "")
|
| 29 |
|
| 30 |
+
# CROSS-PROVIDER FALLBACKS β last-resort entries appended to BRAIN_CHAIN +
|
| 31 |
+
# FAST_BRAIN_CHAIN + JUDGE_CHAIN so the brain + judge survive a full NIM
|
| 32 |
+
# outage (regional ingress brownout, full-pool 5xx, etc.). NIM remains
|
| 33 |
+
# the PRIMARY provider β these only get hit after every NIM candidate in
|
| 34 |
+
# the chain has failed. Both keys are optional: if unset the fallback is
|
| 35 |
+
# simply skipped by NimChainLLM and the chain continues.
|
| 36 |
+
# OPENROUTER_API_KEY β https://openrouter.ai/keys (free-tier OSS models)
|
| 37 |
+
# GROQ_API_KEY β https://console.groq.com/keys (LPU inference, lowest TTFT)
|
| 38 |
+
OPENROUTER_API_KEY: str = os.environ.get("OPENROUTER_API_KEY", "")
|
| 39 |
+
GROQ_API_KEY: str = os.environ.get("GROQ_API_KEY", "")
|
| 40 |
+
|
| 41 |
# Sarvam endpoints (voice STT/TTS + Indic translation only β not brain anymore)
|
| 42 |
SARVAM_BASE_URL: str = "https://api.sarvam.ai"
|
| 43 |
SARVAM_STT_PATH: str = "/speech-to-text"
|
backend/llm_health.py
CHANGED
|
@@ -39,7 +39,48 @@ PROBE_INTERVAL_SEC = 300 # ping each model every 5 min
|
|
| 39 |
PROBE_TIMEOUT_SEC = 12 # per-probe HTTP timeout
|
| 40 |
DOWN_AFTER_CONSECUTIVE_FAILS = 3 # 3 fails in a row = mark down
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
NIM_BASE = "https://integrate.api.nvidia.com/v1/chat/completions"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
@dataclass
|
|
@@ -93,14 +134,34 @@ def save(state: dict[str, ModelHealth]) -> None:
|
|
| 93 |
|
| 94 |
|
| 95 |
async def probe_one(client: httpx.AsyncClient, model: str, api_key: str) -> tuple[bool, str, Optional[int]]:
|
| 96 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
t0 = time.time()
|
| 98 |
try:
|
| 99 |
r = await client.post(
|
| 100 |
-
|
| 101 |
-
headers=
|
| 102 |
json={
|
| 103 |
-
"model":
|
| 104 |
"messages": [{"role": "user", "content": "Reply with exactly: ok"}],
|
| 105 |
"max_tokens": 5,
|
| 106 |
"temperature": 0.0,
|
|
|
|
| 39 |
PROBE_TIMEOUT_SEC = 12 # per-probe HTTP timeout
|
| 40 |
DOWN_AFTER_CONSECUTIVE_FAILS = 3 # 3 fails in a row = mark down
|
| 41 |
|
| 42 |
+
# Per-provider endpoints + env-var names. The chain entries embed the
|
| 43 |
+
# provider via a prefix ('openrouter:<id>' / 'groq:<id>'); unprefixed entries
|
| 44 |
+
# fall through to NIM. Keep these dicts in sync with the providers in
|
| 45 |
+
# backend/providers/{openrouter_llm,groq_llm,nvidia_nim_llm}.py.
|
| 46 |
NIM_BASE = "https://integrate.api.nvidia.com/v1/chat/completions"
|
| 47 |
+
OPENROUTER_BASE = "https://openrouter.ai/api/v1/chat/completions"
|
| 48 |
+
GROQ_BASE = "https://api.groq.com/openai/v1/chat/completions"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _base_url_for(model_id: str) -> str:
|
| 52 |
+
if model_id.startswith("openrouter:"):
|
| 53 |
+
return OPENROUTER_BASE
|
| 54 |
+
if model_id.startswith("groq:"):
|
| 55 |
+
return GROQ_BASE
|
| 56 |
+
return NIM_BASE
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _api_key_for(model_id: str) -> str:
|
| 60 |
+
if model_id.startswith("openrouter:"):
|
| 61 |
+
return os.environ.get("OPENROUTER_API_KEY", "")
|
| 62 |
+
if model_id.startswith("groq:"):
|
| 63 |
+
return os.environ.get("GROQ_API_KEY", "")
|
| 64 |
+
return os.environ.get("NVIDIA_NIM_API_KEY", "")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _model_id_for(model_id: str) -> str:
|
| 68 |
+
"""Strip the provider prefix before sending to the upstream API."""
|
| 69 |
+
if model_id.startswith("openrouter:"):
|
| 70 |
+
return model_id[len("openrouter:"):]
|
| 71 |
+
if model_id.startswith("groq:"):
|
| 72 |
+
return model_id[len("groq:"):]
|
| 73 |
+
return model_id
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _headers_for(model_id: str, api_key: str) -> dict[str, str]:
|
| 77 |
+
"""OpenRouter needs HTTP-Referer + X-Title to avoid being treated as
|
| 78 |
+
anonymous traffic. NIM + Groq just need Bearer + Content-Type."""
|
| 79 |
+
h = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
|
| 80 |
+
if model_id.startswith("openrouter:"):
|
| 81 |
+
h["HTTP-Referer"] = "https://huggingface.co/spaces/rohitsar567/InsuranceBot"
|
| 82 |
+
h["X-Title"] = "Insurance Bot"
|
| 83 |
+
return h
|
| 84 |
|
| 85 |
|
| 86 |
@dataclass
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
async def probe_one(client: httpx.AsyncClient, model: str, api_key: str) -> tuple[bool, str, Optional[int]]:
|
| 137 |
+
"""Probe a single chain entry (NIM or cross-provider).
|
| 138 |
+
|
| 139 |
+
`model` is the chain entry exactly as it appears in BRAIN_CHAIN etc., so
|
| 140 |
+
it may carry a provider prefix (`openrouter:` / `groq:`). The resolvers
|
| 141 |
+
pick the right base URL, headers, and stripped model id. `api_key` here
|
| 142 |
+
is intentionally ignored β we always pick the right key for the model's
|
| 143 |
+
provider via `_api_key_for()`, so a missing prefix-specific key skips
|
| 144 |
+
that probe with a clear error rather than spuriously using the NIM key.
|
| 145 |
+
Returns (ok, error_msg, latency_ms).
|
| 146 |
+
"""
|
| 147 |
+
url = _base_url_for(model)
|
| 148 |
+
upstream_model = _model_id_for(model)
|
| 149 |
+
provider_key = _api_key_for(model)
|
| 150 |
+
headers = _headers_for(model, provider_key)
|
| 151 |
+
|
| 152 |
+
if not provider_key:
|
| 153 |
+
# No key configured for this provider β treat as benign-skip. The
|
| 154 |
+
# background loop will keep probing; once the user sets the key the
|
| 155 |
+
# next tick will succeed.
|
| 156 |
+
return False, "no_api_key", None
|
| 157 |
+
|
| 158 |
t0 = time.time()
|
| 159 |
try:
|
| 160 |
r = await client.post(
|
| 161 |
+
url,
|
| 162 |
+
headers=headers,
|
| 163 |
json={
|
| 164 |
+
"model": upstream_model,
|
| 165 |
"messages": [{"role": "user", "content": "Reply with exactly: ok"}],
|
| 166 |
"max_tokens": 5,
|
| 167 |
"temperature": 0.0,
|
backend/providers/groq_llm.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Groq β cross-provider fallback brain/judge running on LPU hardware.
|
| 2 |
+
|
| 3 |
+
Groq exposes an OpenAI-compatible chat completions endpoint at
|
| 4 |
+
POST https://api.groq.com/openai/v1/chat/completions.
|
| 5 |
+
|
| 6 |
+
Why include this as the last fallback?
|
| 7 |
+
- Groq runs on custom LPU silicon (Language Processing Unit) β bone-fast
|
| 8 |
+
inference (often the lowest TTFT of any free-tier provider). On
|
| 9 |
+
llama-3.3-70b-versatile we typically see sub-second token streaming.
|
| 10 |
+
- Different provider, different DNS, different upstream pool from NIM
|
| 11 |
+
and OpenRouter β so its presence at the bottom of BRAIN_CHAIN +
|
| 12 |
+
JUDGE_CHAIN guarantees the reasoning stack survives a simultaneous
|
| 13 |
+
NIM + OpenRouter regional outage.
|
| 14 |
+
|
| 15 |
+
Drop-in behaviour matches `NvidiaNimLLM`:
|
| 16 |
+
- Bearer auth + OpenAI request shape
|
| 17 |
+
- 4 attempts with exponential backoff on 429 / 5xx
|
| 18 |
+
- Returns `LLMResult` with `text` + `model` populated
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import asyncio
|
| 24 |
+
from typing import Optional
|
| 25 |
+
|
| 26 |
+
import httpx
|
| 27 |
+
|
| 28 |
+
from backend.config import settings
|
| 29 |
+
from backend.providers.base import ChatMessage, LLMProvider, LLMResult
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 33 |
+
|
| 34 |
+
# Default model: llama-3.3-70b-versatile β Meta's Llama 3.3 70B Instruct,
|
| 35 |
+
# served on Groq's LPU at the lowest TTFT of any free-tier 70B option.
|
| 36 |
+
# Sane choice as a last-resort cross-provider fallback.
|
| 37 |
+
DEFAULT_MODEL = "llama-3.3-70b-versatile"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class GroqLLM(LLMProvider):
|
| 41 |
+
name = "groq"
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
model: str = DEFAULT_MODEL,
|
| 46 |
+
api_key: Optional[str] = None,
|
| 47 |
+
timeout: float = 120.0,
|
| 48 |
+
):
|
| 49 |
+
self.api_key = api_key or getattr(settings, "GROQ_API_KEY", "")
|
| 50 |
+
self.model = model
|
| 51 |
+
self.timeout = timeout
|
| 52 |
+
if not self.api_key:
|
| 53 |
+
raise RuntimeError(
|
| 54 |
+
"GROQ_API_KEY not set. Get a key at https://console.groq.com/keys "
|
| 55 |
+
"and add GROQ_API_KEY=gsk_... to .env"
|
| 56 |
+
)
|
| 57 |
+
self.name = f"groq::{model.split('/')[-1]}"
|
| 58 |
+
|
| 59 |
+
async def chat(
|
| 60 |
+
self,
|
| 61 |
+
messages: list[ChatMessage],
|
| 62 |
+
temperature: float = 0.2,
|
| 63 |
+
max_tokens: int = 1024,
|
| 64 |
+
response_format: Optional[dict] = None,
|
| 65 |
+
) -> LLMResult:
|
| 66 |
+
body: dict = {
|
| 67 |
+
"model": self.model,
|
| 68 |
+
"messages": [{"role": m.role, "content": m.content} for m in messages],
|
| 69 |
+
"temperature": temperature,
|
| 70 |
+
"max_tokens": max_tokens,
|
| 71 |
+
}
|
| 72 |
+
if response_format:
|
| 73 |
+
body["response_format"] = response_format
|
| 74 |
+
|
| 75 |
+
headers = {
|
| 76 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 77 |
+
"Content-Type": "application/json",
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 81 |
+
attempts = 4
|
| 82 |
+
delay = 1.0
|
| 83 |
+
for attempt in range(attempts):
|
| 84 |
+
resp = await client.post(GROQ_URL, headers=headers, json=body)
|
| 85 |
+
if resp.status_code == 429 or (500 <= resp.status_code < 600):
|
| 86 |
+
if attempt == attempts - 1:
|
| 87 |
+
resp.raise_for_status()
|
| 88 |
+
ra = resp.headers.get("Retry-After")
|
| 89 |
+
wait = float(ra) if ra and ra.replace(".", "").isdigit() else delay
|
| 90 |
+
await asyncio.sleep(wait)
|
| 91 |
+
delay *= 2
|
| 92 |
+
continue
|
| 93 |
+
resp.raise_for_status()
|
| 94 |
+
break
|
| 95 |
+
payload = resp.json()
|
| 96 |
+
|
| 97 |
+
choice = payload["choices"][0]
|
| 98 |
+
msg = choice.get("message", {}) or {}
|
| 99 |
+
text = msg.get("content") or msg.get("reasoning_content") or ""
|
| 100 |
+
usage = payload.get("usage", {})
|
| 101 |
+
return LLMResult(
|
| 102 |
+
text=text,
|
| 103 |
+
model=payload.get("model", self.model),
|
| 104 |
+
prompt_tokens=usage.get("prompt_tokens"),
|
| 105 |
+
completion_tokens=usage.get("completion_tokens"),
|
| 106 |
+
raw=payload,
|
| 107 |
+
)
|
backend/providers/nvidia_nim_llm.py
CHANGED
|
@@ -30,12 +30,53 @@ Everything else (brain, judge, eval grader) runs through this module.
|
|
| 30 |
from __future__ import annotations
|
| 31 |
|
| 32 |
import asyncio
|
|
|
|
|
|
|
|
|
|
| 33 |
from typing import Optional
|
| 34 |
|
| 35 |
import httpx
|
| 36 |
|
| 37 |
from backend.config import settings
|
| 38 |
from backend.providers.base import ChatMessage, LLMProvider, LLMResult
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
|
| 41 |
NVIDIA_NIM_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
|
@@ -164,17 +205,29 @@ BRAIN_CHAIN = [
|
|
| 164 |
"meta/llama-3.3-70b-instruct",
|
| 165 |
# 6th fallback: DeepSeek-V4-Pro (back when NIM's pool recovers)
|
| 166 |
"deepseek-ai/deepseek-v4-pro",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
]
|
| 168 |
|
| 169 |
# Same chain for fast brain β Qwen 80B is already fast (~2s); no need for a
|
| 170 |
# separate "small + faster" model since the candidate chain already has
|
| 171 |
-
# Nemotron Nano further down.
|
|
|
|
|
|
|
| 172 |
FAST_BRAIN_CHAIN = [
|
| 173 |
"qwen/qwen3-next-80b-a3b-instruct",
|
| 174 |
"nvidia/nemotron-3-nano-30b-a3b", # 1.6s response per Reddit benchmark
|
| 175 |
"openai/gpt-oss-120b",
|
| 176 |
"qwen/qwen3.5-122b-a10b",
|
| 177 |
"deepseek-ai/deepseek-v4-flash",
|
|
|
|
|
|
|
|
|
|
| 178 |
]
|
| 179 |
|
| 180 |
# Judge chain β non-Qwen, non-DeepSeek (different family from brain primary)
|
|
@@ -189,6 +242,13 @@ JUDGE_CHAIN = [
|
|
| 189 |
"minimaxai/minimax-m2.5",
|
| 190 |
# 4th fallback: Meta Llama-4 Maverick (was the original judge β back if NIM Llama pool recovers)
|
| 191 |
"meta/llama-4-maverick-17b-128e-instruct",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
]
|
| 193 |
|
| 194 |
|
|
@@ -203,15 +263,53 @@ class NimChainLLM(LLMProvider):
|
|
| 203 |
which model in the chain produced the output.
|
| 204 |
"""
|
| 205 |
def __init__(self, chain: list[str], api_key: Optional[str] = None,
|
| 206 |
-
timeout: float = 30.0, per_model_attempts: int = 1
|
|
|
|
| 207 |
if not chain:
|
| 208 |
raise ValueError("chain must have at least one model")
|
| 209 |
self.chain = chain
|
| 210 |
self.api_key = api_key or getattr(settings, "NVIDIA_NIM_API_KEY", "")
|
| 211 |
self.timeout = timeout
|
| 212 |
self.per_model_attempts = per_model_attempts
|
|
|
|
| 213 |
self.model = chain[0]
|
| 214 |
-
self.name = f"nim-chain::{chain[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
async def chat(
|
| 217 |
self,
|
|
@@ -229,15 +327,29 @@ class NimChainLLM(LLMProvider):
|
|
| 229 |
except Exception:
|
| 230 |
chain_to_try = self.chain # health monitor failure must never block calls
|
| 231 |
|
|
|
|
|
|
|
|
|
|
| 232 |
last_err: Optional[Exception] = None
|
| 233 |
for model in chain_to_try:
|
| 234 |
try:
|
| 235 |
-
worker =
|
| 236 |
result = await worker.chat(messages=messages, temperature=temperature,
|
| 237 |
max_tokens=max_tokens, response_format=response_format)
|
| 238 |
-
# Successful response β record which model answered + return
|
|
|
|
|
|
|
| 239 |
self.model = model
|
| 240 |
-
self.name = f"nim-chain::{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
return result
|
| 242 |
except (httpx.TimeoutException, httpx.HTTPStatusError,
|
| 243 |
httpx.ConnectError, httpx.NetworkError, asyncio.TimeoutError) as e:
|
|
@@ -258,11 +370,20 @@ class NimChainLLM(LLMProvider):
|
|
| 258 |
if model in chain_to_try:
|
| 259 |
continue # already tried this turn
|
| 260 |
try:
|
| 261 |
-
worker =
|
| 262 |
result = await worker.chat(messages=messages, temperature=temperature,
|
| 263 |
max_tokens=max_tokens, response_format=response_format)
|
| 264 |
self.model = model
|
| 265 |
-
self.name = f"nim-chain::{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
return result
|
| 267 |
except Exception as e:
|
| 268 |
last_err = e
|
|
@@ -270,6 +391,17 @@ class NimChainLLM(LLMProvider):
|
|
| 270 |
except Exception:
|
| 271 |
pass
|
| 272 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
raise RuntimeError(
|
| 274 |
f"NimChainLLM exhausted all {len(self.chain)} candidates. Last error: "
|
| 275 |
f"{type(last_err).__name__}: {str(last_err)[:120]}"
|
|
@@ -279,13 +411,13 @@ class NimChainLLM(LLMProvider):
|
|
| 279 |
def get_brain_llm() -> NimChainLLM:
|
| 280 |
"""Heavy brain β multi-model NIM chain with automatic fallback.
|
| 281 |
Primary: Qwen 3-Next 80B. See BRAIN_CHAIN for fallback order."""
|
| 282 |
-
return NimChainLLM(chain=BRAIN_CHAIN, timeout=30.0)
|
| 283 |
|
| 284 |
|
| 285 |
def get_fast_brain_llm() -> NimChainLLM:
|
| 286 |
"""Fast brain β multi-model NIM chain optimized for low TTFT.
|
| 287 |
Primary: Qwen 3-Next 80B. See FAST_BRAIN_CHAIN for fallback order."""
|
| 288 |
-
return NimChainLLM(chain=FAST_BRAIN_CHAIN, timeout=20.0)
|
| 289 |
|
| 290 |
|
| 291 |
def get_judge_llm(language: str = "en") -> NimChainLLM:
|
|
@@ -296,4 +428,4 @@ def get_judge_llm(language: str = "en") -> NimChainLLM:
|
|
| 296 |
fallbacks (GPT-OSS, Kimi, MiniMax, Llama-4 Maverick) when the primary
|
| 297 |
pool is congested. `language` arg kept for call-site compatibility.
|
| 298 |
"""
|
| 299 |
-
return NimChainLLM(chain=JUDGE_CHAIN, timeout=30.0)
|
|
|
|
| 30 |
from __future__ import annotations
|
| 31 |
|
| 32 |
import asyncio
|
| 33 |
+
import json
|
| 34 |
+
import time
|
| 35 |
+
from pathlib import Path
|
| 36 |
from typing import Optional
|
| 37 |
|
| 38 |
import httpx
|
| 39 |
|
| 40 |
from backend.config import settings
|
| 41 |
from backend.providers.base import ChatMessage, LLMProvider, LLMResult
|
| 42 |
+
from backend.providers.openrouter_llm import OpenRouterLLM
|
| 43 |
+
from backend.providers.groq_llm import GroqLLM
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Usage log β append-only JSONL with cheap 1 MB rotation. Consumed by
|
| 47 |
+
# GET /api/admin/usage for the admin control panel. Path is two parents up
|
| 48 |
+
# from this file (backend/providers/nvidia_nim_llm.py β repo root / data).
|
| 49 |
+
_USAGE_LOG_PATH = Path(__file__).resolve().parent.parent.parent / "data" / "llm_usage.jsonl"
|
| 50 |
+
_USAGE_LOG_MAX_BYTES = 1_000_000 # 1 MB cap β rotate to .bak when exceeded
|
| 51 |
+
_usage_lock = asyncio.Lock()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _now_iso_z() -> str:
|
| 55 |
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
async def _append_usage(record: dict) -> None:
|
| 59 |
+
"""Append one JSONL record to data/llm_usage.jsonl with 1 MB rotation.
|
| 60 |
+
|
| 61 |
+
Best-effort: never raises. Usage logging must NEVER break a chat call.
|
| 62 |
+
Rotation: if file is >1 MB, rename to ``llm_usage.jsonl.bak`` (overwriting
|
| 63 |
+
any existing ``.bak``) and start fresh.
|
| 64 |
+
"""
|
| 65 |
+
try:
|
| 66 |
+
async with _usage_lock:
|
| 67 |
+
_USAGE_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
try:
|
| 69 |
+
if _USAGE_LOG_PATH.exists() and _USAGE_LOG_PATH.stat().st_size > _USAGE_LOG_MAX_BYTES:
|
| 70 |
+
bak = _USAGE_LOG_PATH.with_suffix(_USAGE_LOG_PATH.suffix + ".bak")
|
| 71 |
+
_USAGE_LOG_PATH.replace(bak)
|
| 72 |
+
except Exception:
|
| 73 |
+
pass # rotation failure is non-fatal
|
| 74 |
+
line = json.dumps(record, ensure_ascii=False) + "\n"
|
| 75 |
+
with _USAGE_LOG_PATH.open("a", encoding="utf-8") as f:
|
| 76 |
+
f.write(line)
|
| 77 |
+
except Exception:
|
| 78 |
+
# Logging is best-effort β silently swallow.
|
| 79 |
+
pass
|
| 80 |
|
| 81 |
|
| 82 |
NVIDIA_NIM_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
|
|
|
| 205 |
"meta/llama-3.3-70b-instruct",
|
| 206 |
# 6th fallback: DeepSeek-V4-Pro (back when NIM's pool recovers)
|
| 207 |
"deepseek-ai/deepseek-v4-pro",
|
| 208 |
+
# CROSS-PROVIDER FALLBACKS β only reached when the entire NIM block above
|
| 209 |
+
# has failed (regional outage / DNS / ingress brownout). These hit a
|
| 210 |
+
# completely different provider so the brain survives a full NIM down.
|
| 211 |
+
# 7th fallback: OpenRouter GPT-OSS 120B (different provider, MIT weights)
|
| 212 |
+
"openrouter:openai/gpt-oss-120b",
|
| 213 |
+
# 8th fallback: Groq Llama-3.3 70B (different provider, LPU inference)
|
| 214 |
+
"groq:llama-3.3-70b-versatile",
|
| 215 |
]
|
| 216 |
|
| 217 |
# Same chain for fast brain β Qwen 80B is already fast (~2s); no need for a
|
| 218 |
# separate "small + faster" model since the candidate chain already has
|
| 219 |
+
# Nemotron Nano further down. Last entry is Groq because its LPU inference
|
| 220 |
+
# is the lowest-TTFT free-tier option, so a fast-brain fall-through to it is
|
| 221 |
+
# still acceptable from a latency-budget standpoint.
|
| 222 |
FAST_BRAIN_CHAIN = [
|
| 223 |
"qwen/qwen3-next-80b-a3b-instruct",
|
| 224 |
"nvidia/nemotron-3-nano-30b-a3b", # 1.6s response per Reddit benchmark
|
| 225 |
"openai/gpt-oss-120b",
|
| 226 |
"qwen/qwen3.5-122b-a10b",
|
| 227 |
"deepseek-ai/deepseek-v4-flash",
|
| 228 |
+
# CROSS-PROVIDER FALLBACK β Groq Llama-3.3 70B (LPU, lowest TTFT of all
|
| 229 |
+
# free-tier options; OK for a fast-brain call when NIM is down).
|
| 230 |
+
"groq:llama-3.3-70b-versatile",
|
| 231 |
]
|
| 232 |
|
| 233 |
# Judge chain β non-Qwen, non-DeepSeek (different family from brain primary)
|
|
|
|
| 242 |
"minimaxai/minimax-m2.5",
|
| 243 |
# 4th fallback: Meta Llama-4 Maverick (was the original judge β back if NIM Llama pool recovers)
|
| 244 |
"meta/llama-4-maverick-17b-128e-instruct",
|
| 245 |
+
# CROSS-PROVIDER FALLBACKS β reached only when every NIM judge candidate
|
| 246 |
+
# above has failed. Critical for keeping faithfulness Gate 4 + Hinglish
|
| 247 |
+
# drift judge alive through a full NIM outage.
|
| 248 |
+
# 5th fallback: OpenRouter GPT-OSS 120B (different provider, MIT weights)
|
| 249 |
+
"openrouter:openai/gpt-oss-120b",
|
| 250 |
+
# 6th fallback: Groq Llama-3.3 70B (different provider, LPU inference)
|
| 251 |
+
"groq:llama-3.3-70b-versatile",
|
| 252 |
]
|
| 253 |
|
| 254 |
|
|
|
|
| 263 |
which model in the chain produced the output.
|
| 264 |
"""
|
| 265 |
def __init__(self, chain: list[str], api_key: Optional[str] = None,
|
| 266 |
+
timeout: float = 30.0, per_model_attempts: int = 1,
|
| 267 |
+
role: str = "unknown"):
|
| 268 |
if not chain:
|
| 269 |
raise ValueError("chain must have at least one model")
|
| 270 |
self.chain = chain
|
| 271 |
self.api_key = api_key or getattr(settings, "NVIDIA_NIM_API_KEY", "")
|
| 272 |
self.timeout = timeout
|
| 273 |
self.per_model_attempts = per_model_attempts
|
| 274 |
+
self.role = role # 'brain' | 'fast_brain' | 'judge' | 'unknown' β flows into usage log
|
| 275 |
self.model = chain[0]
|
| 276 |
+
self.name = f"nim-chain::{self._short_id(chain[0])}"
|
| 277 |
+
|
| 278 |
+
@staticmethod
|
| 279 |
+
def _short_id(model_id: str) -> str:
|
| 280 |
+
"""Build the audit-log suffix used in `self.name`.
|
| 281 |
+
|
| 282 |
+
Preserves the provider prefix (`openrouter:` / `groq:`) so logs make
|
| 283 |
+
it obvious which provider answered after a cross-provider fall-
|
| 284 |
+
through. Examples:
|
| 285 |
+
- 'qwen/qwen3-next-80b-a3b-instruct' -> 'qwen3-next-80b-a3b-instruct'
|
| 286 |
+
- 'openrouter:openai/gpt-oss-120b' -> 'openrouter:gpt-oss-120b'
|
| 287 |
+
- 'groq:llama-3.3-70b-versatile' -> 'groq:llama-3.3-70b-versatile'
|
| 288 |
+
"""
|
| 289 |
+
if ":" in model_id:
|
| 290 |
+
prefix, rest = model_id.split(":", 1)
|
| 291 |
+
return f"{prefix}:{rest.split('/')[-1]}"
|
| 292 |
+
return model_id.split("/")[-1]
|
| 293 |
+
|
| 294 |
+
def _get_worker_for(self, model_id: str, timeout: float) -> LLMProvider:
|
| 295 |
+
"""Dispatch a chain entry to the right provider client.
|
| 296 |
+
|
| 297 |
+
Recognised prefixes:
|
| 298 |
+
- 'openrouter:<model>' -> OpenRouterLLM
|
| 299 |
+
- 'groq:<model>' -> GroqLLM
|
| 300 |
+
- <anything else> -> NvidiaNimLLM (existing default)
|
| 301 |
+
"""
|
| 302 |
+
if model_id.startswith("openrouter:"):
|
| 303 |
+
return OpenRouterLLM(
|
| 304 |
+
model=model_id[len("openrouter:"):],
|
| 305 |
+
timeout=timeout,
|
| 306 |
+
)
|
| 307 |
+
if model_id.startswith("groq:"):
|
| 308 |
+
return GroqLLM(
|
| 309 |
+
model=model_id[len("groq:"):],
|
| 310 |
+
timeout=timeout,
|
| 311 |
+
)
|
| 312 |
+
return NvidiaNimLLM(model=model_id, api_key=self.api_key, timeout=timeout)
|
| 313 |
|
| 314 |
async def chat(
|
| 315 |
self,
|
|
|
|
| 327 |
except Exception:
|
| 328 |
chain_to_try = self.chain # health monitor failure must never block calls
|
| 329 |
|
| 330 |
+
chain_primary = self.chain[0] if self.chain else None
|
| 331 |
+
call_t0 = time.time()
|
| 332 |
+
|
| 333 |
last_err: Optional[Exception] = None
|
| 334 |
for model in chain_to_try:
|
| 335 |
try:
|
| 336 |
+
worker = self._get_worker_for(model, self.timeout)
|
| 337 |
result = await worker.chat(messages=messages, temperature=temperature,
|
| 338 |
max_tokens=max_tokens, response_format=response_format)
|
| 339 |
+
# Successful response β record which model answered + return.
|
| 340 |
+
# `self.name` preserves any provider prefix so audit logs make
|
| 341 |
+
# cross-provider fall-throughs (groq:/openrouter:) obvious.
|
| 342 |
self.model = model
|
| 343 |
+
self.name = f"nim-chain::{self._short_id(model)}"
|
| 344 |
+
latency_ms = int((time.time() - call_t0) * 1000)
|
| 345 |
+
await _append_usage({
|
| 346 |
+
"ts": _now_iso_z(),
|
| 347 |
+
"role": self.role,
|
| 348 |
+
"chain_primary": chain_primary,
|
| 349 |
+
"served_model": model,
|
| 350 |
+
"latency_ms": latency_ms,
|
| 351 |
+
"success": True,
|
| 352 |
+
})
|
| 353 |
return result
|
| 354 |
except (httpx.TimeoutException, httpx.HTTPStatusError,
|
| 355 |
httpx.ConnectError, httpx.NetworkError, asyncio.TimeoutError) as e:
|
|
|
|
| 370 |
if model in chain_to_try:
|
| 371 |
continue # already tried this turn
|
| 372 |
try:
|
| 373 |
+
worker = self._get_worker_for(model, self.timeout)
|
| 374 |
result = await worker.chat(messages=messages, temperature=temperature,
|
| 375 |
max_tokens=max_tokens, response_format=response_format)
|
| 376 |
self.model = model
|
| 377 |
+
self.name = f"nim-chain::{self._short_id(model)}"
|
| 378 |
+
latency_ms = int((time.time() - call_t0) * 1000)
|
| 379 |
+
await _append_usage({
|
| 380 |
+
"ts": _now_iso_z(),
|
| 381 |
+
"role": self.role,
|
| 382 |
+
"chain_primary": chain_primary,
|
| 383 |
+
"served_model": model,
|
| 384 |
+
"latency_ms": latency_ms,
|
| 385 |
+
"success": True,
|
| 386 |
+
})
|
| 387 |
return result
|
| 388 |
except Exception as e:
|
| 389 |
last_err = e
|
|
|
|
| 391 |
except Exception:
|
| 392 |
pass
|
| 393 |
|
| 394 |
+
# Total exhaustion β log a single failure record so the admin panel
|
| 395 |
+
# surfaces "judge has 12% failure rate over last 24h" type signal.
|
| 396 |
+
latency_ms = int((time.time() - call_t0) * 1000)
|
| 397 |
+
await _append_usage({
|
| 398 |
+
"ts": _now_iso_z(),
|
| 399 |
+
"role": self.role,
|
| 400 |
+
"chain_primary": chain_primary,
|
| 401 |
+
"served_model": None,
|
| 402 |
+
"latency_ms": latency_ms,
|
| 403 |
+
"success": False,
|
| 404 |
+
})
|
| 405 |
raise RuntimeError(
|
| 406 |
f"NimChainLLM exhausted all {len(self.chain)} candidates. Last error: "
|
| 407 |
f"{type(last_err).__name__}: {str(last_err)[:120]}"
|
|
|
|
| 411 |
def get_brain_llm() -> NimChainLLM:
|
| 412 |
"""Heavy brain β multi-model NIM chain with automatic fallback.
|
| 413 |
Primary: Qwen 3-Next 80B. See BRAIN_CHAIN for fallback order."""
|
| 414 |
+
return NimChainLLM(chain=BRAIN_CHAIN, timeout=30.0, role="brain")
|
| 415 |
|
| 416 |
|
| 417 |
def get_fast_brain_llm() -> NimChainLLM:
|
| 418 |
"""Fast brain β multi-model NIM chain optimized for low TTFT.
|
| 419 |
Primary: Qwen 3-Next 80B. See FAST_BRAIN_CHAIN for fallback order."""
|
| 420 |
+
return NimChainLLM(chain=FAST_BRAIN_CHAIN, timeout=20.0, role="fast_brain")
|
| 421 |
|
| 422 |
|
| 423 |
def get_judge_llm(language: str = "en") -> NimChainLLM:
|
|
|
|
| 428 |
fallbacks (GPT-OSS, Kimi, MiniMax, Llama-4 Maverick) when the primary
|
| 429 |
pool is congested. `language` arg kept for call-site compatibility.
|
| 430 |
"""
|
| 431 |
+
return NimChainLLM(chain=JUDGE_CHAIN, timeout=30.0, role="judge")
|
backend/providers/openrouter_llm.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenRouter β cross-provider fallback brain/judge for the reasoning stack.
|
| 2 |
+
|
| 3 |
+
OpenRouter aggregates dozens of OSS + proprietary models behind one
|
| 4 |
+
OpenAI-compatible endpoint at
|
| 5 |
+
POST https://openrouter.ai/api/v1/chat/completions.
|
| 6 |
+
|
| 7 |
+
Why have this in the chain at all when NIM is primary?
|
| 8 |
+
- NIM has had regional pool outages (full-tier brownouts on the DeepSeek-V4
|
| 9 |
+
and Meta Llama pools, multi-hour). If every brain candidate inside NIM
|
| 10 |
+
sits behind the same regional ingress, a NIM-side incident takes the
|
| 11 |
+
whole reasoning stack down.
|
| 12 |
+
- OpenRouter is a fully different provider (different DNS, different
|
| 13 |
+
region, different upstream pools) so its inclusion as the last entries
|
| 14 |
+
of BRAIN_CHAIN + JUDGE_CHAIN keeps the brain + judge alive through a
|
| 15 |
+
complete NIM outage.
|
| 16 |
+
|
| 17 |
+
Drop-in behaviour matches `NvidiaNimLLM`:
|
| 18 |
+
- Bearer auth + OpenAI request shape
|
| 19 |
+
- 4 attempts with exponential backoff on 429 / 5xx
|
| 20 |
+
- Returns `LLMResult` with `text` + `model` populated
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import asyncio
|
| 26 |
+
from typing import Optional
|
| 27 |
+
|
| 28 |
+
import httpx
|
| 29 |
+
|
| 30 |
+
from backend.config import settings
|
| 31 |
+
from backend.providers.base import ChatMessage, LLMProvider, LLMResult
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 35 |
+
|
| 36 |
+
# Default model: openai/gpt-oss-120b β OpenAI's open-weights GPT-OSS 120B.
|
| 37 |
+
# Free on OpenRouter (no cost tier), MIT licensed, strong on reasoning +
|
| 38 |
+
# instruction following β a sane cross-provider fallback for both brain and
|
| 39 |
+
# judge roles when NIM is fully down.
|
| 40 |
+
DEFAULT_MODEL = "openai/gpt-oss-120b"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class OpenRouterLLM(LLMProvider):
|
| 44 |
+
name = "openrouter"
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
model: str = DEFAULT_MODEL,
|
| 49 |
+
api_key: Optional[str] = None,
|
| 50 |
+
timeout: float = 120.0,
|
| 51 |
+
):
|
| 52 |
+
self.api_key = api_key or getattr(settings, "OPENROUTER_API_KEY", "")
|
| 53 |
+
self.model = model
|
| 54 |
+
self.timeout = timeout
|
| 55 |
+
if not self.api_key:
|
| 56 |
+
raise RuntimeError(
|
| 57 |
+
"OPENROUTER_API_KEY not set. Get a key at https://openrouter.ai/keys "
|
| 58 |
+
"and add OPENROUTER_API_KEY=sk-or-... to .env"
|
| 59 |
+
)
|
| 60 |
+
self.name = f"openrouter::{model.split('/')[-1]}"
|
| 61 |
+
|
| 62 |
+
async def chat(
|
| 63 |
+
self,
|
| 64 |
+
messages: list[ChatMessage],
|
| 65 |
+
temperature: float = 0.2,
|
| 66 |
+
max_tokens: int = 1024,
|
| 67 |
+
response_format: Optional[dict] = None,
|
| 68 |
+
) -> LLMResult:
|
| 69 |
+
body: dict = {
|
| 70 |
+
"model": self.model,
|
| 71 |
+
"messages": [{"role": m.role, "content": m.content} for m in messages],
|
| 72 |
+
"temperature": temperature,
|
| 73 |
+
"max_tokens": max_tokens,
|
| 74 |
+
}
|
| 75 |
+
if response_format:
|
| 76 |
+
body["response_format"] = response_format
|
| 77 |
+
|
| 78 |
+
headers = {
|
| 79 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 80 |
+
"Content-Type": "application/json",
|
| 81 |
+
# OpenRouter requires HTTP-Referer + X-Title for free-tier rate-limit
|
| 82 |
+
# categorization + analytics. Without these the key still works but
|
| 83 |
+
# is treated as anonymous traffic (lower priority).
|
| 84 |
+
"HTTP-Referer": "https://huggingface.co/spaces/rohitsar567/InsuranceBot",
|
| 85 |
+
"X-Title": "Insurance Bot",
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 89 |
+
attempts = 4
|
| 90 |
+
delay = 1.0
|
| 91 |
+
for attempt in range(attempts):
|
| 92 |
+
resp = await client.post(OPENROUTER_URL, headers=headers, json=body)
|
| 93 |
+
if resp.status_code == 429 or (500 <= resp.status_code < 600):
|
| 94 |
+
if attempt == attempts - 1:
|
| 95 |
+
resp.raise_for_status()
|
| 96 |
+
ra = resp.headers.get("Retry-After")
|
| 97 |
+
wait = float(ra) if ra and ra.replace(".", "").isdigit() else delay
|
| 98 |
+
await asyncio.sleep(wait)
|
| 99 |
+
delay *= 2
|
| 100 |
+
continue
|
| 101 |
+
resp.raise_for_status()
|
| 102 |
+
break
|
| 103 |
+
payload = resp.json()
|
| 104 |
+
|
| 105 |
+
choice = payload["choices"][0]
|
| 106 |
+
msg = choice.get("message", {}) or {}
|
| 107 |
+
text = msg.get("content") or msg.get("reasoning_content") or ""
|
| 108 |
+
usage = payload.get("usage", {})
|
| 109 |
+
return LLMResult(
|
| 110 |
+
text=text,
|
| 111 |
+
model=payload.get("model", self.model),
|
| 112 |
+
prompt_tokens=usage.get("prompt_tokens"),
|
| 113 |
+
completion_tokens=usage.get("completion_tokens"),
|
| 114 |
+
raw=payload,
|
| 115 |
+
)
|
frontend/public/admin/llm-control.html
CHANGED
|
@@ -216,6 +216,98 @@
|
|
| 216 |
#toast.error { border-color: var(--red); }
|
| 217 |
#toast.info { border-color: var(--blue); }
|
| 218 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
.hidden { display: none !important; }
|
| 220 |
.actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
| 221 |
.gate-error {
|
|
@@ -296,9 +388,20 @@
|
|
| 296 |
var STATE = {
|
| 297 |
password: '',
|
| 298 |
health: null, // { models: [ { model, status, latency_ms, last_error, last_success } ], counters: { healthy, degraded, down } }
|
| 299 |
-
chains: null
|
|
|
|
| 300 |
};
|
| 301 |
var ROLES = ['brain', 'fast_brain', 'judge'];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
var STORAGE_KEY = 'admin_password';
|
| 303 |
|
| 304 |
// ----- Utilities -----
|
|
@@ -549,6 +652,21 @@
|
|
| 549 |
return 'unknown';
|
| 550 |
}
|
| 551 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
function renderChains() {
|
| 553 |
var grid = $('chains-grid');
|
| 554 |
clearChildren(grid);
|
|
@@ -559,25 +677,111 @@
|
|
| 559 |
var chain = STATE.chains[role];
|
| 560 |
if (!Array.isArray(chain)) chain = [];
|
| 561 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
var card = createEl('div', { className: 'card chain-card' });
|
| 563 |
|
|
|
|
| 564 |
var header = createEl('div', { className: 'row-between' });
|
| 565 |
-
var
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
card.appendChild(header);
|
| 571 |
|
| 572 |
-
|
| 573 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
|
| 575 |
-
var
|
| 576 |
-
|
|
|
|
| 577 |
|
| 578 |
-
function
|
| 579 |
-
|
| 580 |
|
|
|
|
| 581 |
var actions = createEl('div', { className: 'actions' });
|
| 582 |
var saveBtn = createEl('button', { className: 'primary', text: 'Save' });
|
| 583 |
saveBtn.onclick = function () {
|
|
@@ -598,7 +802,9 @@
|
|
| 598 |
};
|
| 599 |
|
| 600 |
var revertBtn = createEl('button', { text: 'Reload' });
|
| 601 |
-
revertBtn.onclick = function () {
|
|
|
|
|
|
|
| 602 |
|
| 603 |
actions.appendChild(saveBtn);
|
| 604 |
actions.appendChild(revertBtn);
|
|
@@ -608,27 +814,50 @@
|
|
| 608 |
});
|
| 609 |
}
|
| 610 |
|
| 611 |
-
function
|
| 612 |
-
clearChildren(
|
| 613 |
var chain = STATE.chains[role] || [];
|
| 614 |
if (!chain.length) {
|
| 615 |
-
var
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
| 617 |
return;
|
| 618 |
}
|
| 619 |
chain.forEach(function (model, idx) {
|
| 620 |
-
var
|
| 621 |
-
|
| 622 |
-
item.appendChild(statusPill(statusForModel(model)));
|
| 623 |
|
| 624 |
-
var
|
| 625 |
-
|
| 626 |
|
|
|
|
| 627 |
if (idx === 0) {
|
| 628 |
-
var star = createEl('span', { className: 'primary-
|
| 629 |
-
|
| 630 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 631 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
var moves = createEl('span', { className: 'move-buttons' });
|
| 633 |
var up = createEl('button', { className: 'icon-btn', text: 'β', title: 'Move up' });
|
| 634 |
up.disabled = (idx === 0);
|
|
@@ -638,7 +867,7 @@
|
|
| 638 |
var tmp = arr[idx - 1];
|
| 639 |
arr[idx - 1] = arr[idx];
|
| 640 |
arr[idx] = tmp;
|
| 641 |
-
|
| 642 |
};
|
| 643 |
var down = createEl('button', { className: 'icon-btn', text: 'β', title: 'Move down' });
|
| 644 |
down.disabled = (idx === chain.length - 1);
|
|
@@ -648,16 +877,25 @@
|
|
| 648 |
var tmp = arr[idx + 1];
|
| 649 |
arr[idx + 1] = arr[idx];
|
| 650 |
arr[idx] = tmp;
|
| 651 |
-
|
| 652 |
};
|
| 653 |
moves.appendChild(up);
|
| 654 |
moves.appendChild(down);
|
| 655 |
-
|
|
|
|
| 656 |
|
| 657 |
-
|
| 658 |
});
|
| 659 |
}
|
| 660 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 661 |
function setLastUpdated() {
|
| 662 |
var el = $('last-updated');
|
| 663 |
if (!el) return;
|
|
@@ -685,8 +923,19 @@
|
|
| 685 |
});
|
| 686 |
}
|
| 687 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 688 |
function refreshAll() {
|
| 689 |
-
return Promise.all([fetchHealth(), fetchChains()]).then(function () {
|
| 690 |
renderCounters();
|
| 691 |
renderHealthTable();
|
| 692 |
renderChains();
|
|
|
|
| 216 |
#toast.error { border-color: var(--red); }
|
| 217 |
#toast.info { border-color: var(--blue); }
|
| 218 |
|
| 219 |
+
/* Role badge β colored pill (BRAIN / FAST_BRAIN / JUDGE) */
|
| 220 |
+
.role-badge {
|
| 221 |
+
display: inline-block;
|
| 222 |
+
padding: 3px 10px;
|
| 223 |
+
border-radius: 6px;
|
| 224 |
+
font-size: 11px;
|
| 225 |
+
font-weight: 700;
|
| 226 |
+
letter-spacing: 0.06em;
|
| 227 |
+
color: #fff;
|
| 228 |
+
vertical-align: middle;
|
| 229 |
+
margin-right: 8px;
|
| 230 |
+
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, monospace;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
/* Compact summary blocks above the chain table */
|
| 234 |
+
.summary-row {
|
| 235 |
+
display: grid;
|
| 236 |
+
grid-template-columns: 1fr 1fr;
|
| 237 |
+
gap: 12px;
|
| 238 |
+
margin: 12px 0 16px;
|
| 239 |
+
}
|
| 240 |
+
.summary-block {
|
| 241 |
+
padding: 10px 12px;
|
| 242 |
+
background: #0b0d12;
|
| 243 |
+
border: 1px solid var(--border);
|
| 244 |
+
border-radius: 8px;
|
| 245 |
+
}
|
| 246 |
+
.summary-block .label {
|
| 247 |
+
font-size: 10px;
|
| 248 |
+
text-transform: uppercase;
|
| 249 |
+
letter-spacing: 0.08em;
|
| 250 |
+
color: var(--muted);
|
| 251 |
+
margin-bottom: 6px;
|
| 252 |
+
}
|
| 253 |
+
.summary-block .model-name {
|
| 254 |
+
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, monospace;
|
| 255 |
+
font-size: 13px;
|
| 256 |
+
word-break: break-all;
|
| 257 |
+
line-height: 1.35;
|
| 258 |
+
}
|
| 259 |
+
.summary-block .stats-line {
|
| 260 |
+
margin-top: 6px;
|
| 261 |
+
font-size: 11px;
|
| 262 |
+
color: var(--muted);
|
| 263 |
+
}
|
| 264 |
+
.summary-block .stats-line .sep {
|
| 265 |
+
margin: 0 6px;
|
| 266 |
+
color: #3a4250;
|
| 267 |
+
}
|
| 268 |
+
.primary-mark { color: var(--green); margin-right: 4px; }
|
| 269 |
+
|
| 270 |
+
/* Chain table */
|
| 271 |
+
.chain-table { width: 100%; border-collapse: collapse; font-size: 12px; margin-bottom: 12px; }
|
| 272 |
+
.chain-table thead th {
|
| 273 |
+
text-align: left;
|
| 274 |
+
padding: 8px 8px;
|
| 275 |
+
background: #0b0d12;
|
| 276 |
+
border-bottom: 1px solid var(--border);
|
| 277 |
+
color: var(--muted);
|
| 278 |
+
font-weight: 600;
|
| 279 |
+
font-size: 10px;
|
| 280 |
+
text-transform: uppercase;
|
| 281 |
+
letter-spacing: 0.05em;
|
| 282 |
+
}
|
| 283 |
+
.chain-table tbody td {
|
| 284 |
+
padding: 8px 8px;
|
| 285 |
+
border-bottom: 1px solid var(--border);
|
| 286 |
+
vertical-align: middle;
|
| 287 |
+
}
|
| 288 |
+
.chain-table tbody tr:last-child td { border-bottom: none; }
|
| 289 |
+
.chain-table .model-cell {
|
| 290 |
+
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, monospace;
|
| 291 |
+
word-break: break-all;
|
| 292 |
+
max-width: 280px;
|
| 293 |
+
}
|
| 294 |
+
.chain-table .num-cell { text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
| 295 |
+
.chain-table .icon-btn { padding: 2px 7px; font-size: 12px; line-height: 1.2; }
|
| 296 |
+
.chain-table tbody tr.is-primary td { background: rgba(63, 185, 80, 0.05); }
|
| 297 |
+
|
| 298 |
+
.unverified-flag {
|
| 299 |
+
display: inline-block;
|
| 300 |
+
margin-left: 6px;
|
| 301 |
+
padding: 1px 6px;
|
| 302 |
+
font-size: 10px;
|
| 303 |
+
letter-spacing: 0.04em;
|
| 304 |
+
text-transform: uppercase;
|
| 305 |
+
border-radius: 4px;
|
| 306 |
+
background: rgba(210, 153, 34, 0.18);
|
| 307 |
+
color: var(--yellow);
|
| 308 |
+
border: 1px solid rgba(210, 153, 34, 0.35);
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
.hidden { display: none !important; }
|
| 312 |
.actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
| 313 |
.gate-error {
|
|
|
|
| 388 |
var STATE = {
|
| 389 |
password: '',
|
| 390 |
health: null, // { models: [ { model, status, latency_ms, last_error, last_success } ], counters: { healthy, degraded, down } }
|
| 391 |
+
chains: null, // { brain: [...], fast_brain: [...], judge: [...] }
|
| 392 |
+
usage: null // { brain: {...}, fast_brain: {...}, judge: {...} } from /api/admin/usage
|
| 393 |
};
|
| 394 |
var ROLES = ['brain', 'fast_brain', 'judge'];
|
| 395 |
+
var ROLE_COLORS = {
|
| 396 |
+
brain: '#58a6ff', // blue
|
| 397 |
+
fast_brain: '#39c5cf', // cyan
|
| 398 |
+
judge: '#a371f7' // purple
|
| 399 |
+
};
|
| 400 |
+
var ROLE_LABELS = {
|
| 401 |
+
brain: 'BRAIN',
|
| 402 |
+
fast_brain: 'FAST_BRAIN',
|
| 403 |
+
judge: 'JUDGE'
|
| 404 |
+
};
|
| 405 |
var STORAGE_KEY = 'admin_password';
|
| 406 |
|
| 407 |
// ----- Utilities -----
|
|
|
|
| 652 |
return 'unknown';
|
| 653 |
}
|
| 654 |
|
| 655 |
+
// Index by_model array from /api/admin/usage by model id, for O(1) lookup
|
| 656 |
+
// when rendering one chain row.
|
| 657 |
+
function usageStatsForRole(role) {
|
| 658 |
+
var u = STATE.usage && STATE.usage[role];
|
| 659 |
+
if (!u || !Array.isArray(u.by_model)) return { byModel: {}, total: 0, payload: u || null };
|
| 660 |
+
var map = {};
|
| 661 |
+
u.by_model.forEach(function (m) { if (m && m.model) map[m.model] = m; });
|
| 662 |
+
return { byModel: map, total: Number(u.total_calls_24h) || 0, payload: u };
|
| 663 |
+
}
|
| 664 |
+
|
| 665 |
+
function fmtPct(x) {
|
| 666 |
+
if (x == null || isNaN(x)) return 'β';
|
| 667 |
+
return (Number(x) * 100).toFixed(1) + '%';
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
function renderChains() {
|
| 671 |
var grid = $('chains-grid');
|
| 672 |
clearChildren(grid);
|
|
|
|
| 677 |
var chain = STATE.chains[role];
|
| 678 |
if (!Array.isArray(chain)) chain = [];
|
| 679 |
|
| 680 |
+
var stats = usageStatsForRole(role);
|
| 681 |
+
var payload = stats.payload || {};
|
| 682 |
+
var primaryModel = payload.primary_model || chain[0] || null;
|
| 683 |
+
var nextBest = payload.next_best_recommended || null;
|
| 684 |
+
var nextBestUnverified = !!payload.next_best_is_unverified;
|
| 685 |
+
|
| 686 |
var card = createEl('div', { className: 'card chain-card' });
|
| 687 |
|
| 688 |
+
// --- Header: colored badge + role label + 24h call count ---
|
| 689 |
var header = createEl('div', { className: 'row-between' });
|
| 690 |
+
var headerLeft = createEl('div');
|
| 691 |
+
var badge = createEl('span', { className: 'role-badge', text: ROLE_LABELS[role] || String(role).toUpperCase() });
|
| 692 |
+
badge.style.background = ROLE_COLORS[role] || '#444';
|
| 693 |
+
headerLeft.appendChild(badge);
|
| 694 |
+
var roleTitle = createEl('span', { text: 'Chain configuration' });
|
| 695 |
+
roleTitle.style.fontSize = '15px';
|
| 696 |
+
roleTitle.style.fontWeight = '600';
|
| 697 |
+
headerLeft.appendChild(roleTitle);
|
| 698 |
+
header.appendChild(headerLeft);
|
| 699 |
+
|
| 700 |
+
var headerRight = createEl('div', { className: 'small muted' });
|
| 701 |
+
var totalCalls = stats.total;
|
| 702 |
+
var sr = (payload && payload.success_rate != null) ? fmtPct(payload.success_rate) : 'β';
|
| 703 |
+
headerRight.textContent = totalCalls + ' calls / 24h Β· ' + sr + ' success';
|
| 704 |
+
header.appendChild(headerRight);
|
| 705 |
card.appendChild(header);
|
| 706 |
|
| 707 |
+
// --- Summary row: Currently primary + Next best recommended ---
|
| 708 |
+
var summary = createEl('div', { className: 'summary-row' });
|
| 709 |
+
|
| 710 |
+
var primaryBlock = createEl('div', { className: 'summary-block' });
|
| 711 |
+
var primaryLabel = createEl('div', { className: 'label', text: 'Currently primary' });
|
| 712 |
+
primaryBlock.appendChild(primaryLabel);
|
| 713 |
+
var primaryNameLine = createEl('div', { className: 'model-name' });
|
| 714 |
+
var primaryStar = createEl('span', { className: 'primary-mark', text: 'β
' });
|
| 715 |
+
primaryStar.style.color = 'var(--green)';
|
| 716 |
+
primaryNameLine.appendChild(primaryStar);
|
| 717 |
+
primaryNameLine.appendChild(document.createTextNode(primaryModel || 'β'));
|
| 718 |
+
primaryBlock.appendChild(primaryNameLine);
|
| 719 |
+
var primaryStatsRow = stats.byModel[primaryModel];
|
| 720 |
+
var primaryStatsLine = createEl('div', { className: 'stats-line' });
|
| 721 |
+
if (primaryStatsRow) {
|
| 722 |
+
primaryStatsLine.appendChild(document.createTextNode(fmtPct(primaryStatsRow.share) + ' share'));
|
| 723 |
+
primaryStatsLine.appendChild(createEl('span', { className: 'sep', text: 'Β·' }));
|
| 724 |
+
primaryStatsLine.appendChild(document.createTextNode(fmtLatency(primaryStatsRow.avg_latency_ms) + ' avg'));
|
| 725 |
+
primaryStatsLine.appendChild(createEl('span', { className: 'sep', text: 'Β·' }));
|
| 726 |
+
primaryStatsLine.appendChild(document.createTextNode(fmtPct(primaryStatsRow.success_rate) + ' success'));
|
| 727 |
+
} else {
|
| 728 |
+
primaryStatsLine.textContent = 'No 24h traffic recorded yet.';
|
| 729 |
+
}
|
| 730 |
+
primaryBlock.appendChild(primaryStatsLine);
|
| 731 |
+
summary.appendChild(primaryBlock);
|
| 732 |
+
|
| 733 |
+
var nextBlock = createEl('div', { className: 'summary-block' });
|
| 734 |
+
var nextLabel = createEl('div', { className: 'label', text: 'Next best recommended' });
|
| 735 |
+
nextBlock.appendChild(nextLabel);
|
| 736 |
+
var nextNameLine = createEl('div', { className: 'model-name' });
|
| 737 |
+
nextNameLine.appendChild(document.createTextNode(nextBest || 'β'));
|
| 738 |
+
if (nextBest && nextBestUnverified) {
|
| 739 |
+
var flag = createEl('span', { className: 'unverified-flag', text: 'unverified' });
|
| 740 |
+
nextNameLine.appendChild(flag);
|
| 741 |
+
}
|
| 742 |
+
nextBlock.appendChild(nextNameLine);
|
| 743 |
+
var nextStatsLine = createEl('div', { className: 'stats-line' });
|
| 744 |
+
if (nextBest) {
|
| 745 |
+
var nextHealth = statusForModel(nextBest);
|
| 746 |
+
var nextHealthRow = healthRowFor(nextBest);
|
| 747 |
+
var latStr = nextHealthRow ? fmtLatency(nextHealthRow.latency_ms != null ? nextHealthRow.latency_ms : nextHealthRow.latency) : 'β';
|
| 748 |
+
nextStatsLine.appendChild(document.createTextNode('health: ' + normalizeStatus(nextHealth)));
|
| 749 |
+
nextStatsLine.appendChild(createEl('span', { className: 'sep', text: 'Β·' }));
|
| 750 |
+
nextStatsLine.appendChild(document.createTextNode(latStr + ' last probe'));
|
| 751 |
+
if (nextBestUnverified) {
|
| 752 |
+
nextStatsLine.appendChild(createEl('span', { className: 'sep', text: 'Β·' }));
|
| 753 |
+
nextStatsLine.appendChild(document.createTextNode('no healthy alternative β fallback choice'));
|
| 754 |
+
}
|
| 755 |
+
} else {
|
| 756 |
+
nextStatsLine.textContent = 'No alternative in chain.';
|
| 757 |
+
}
|
| 758 |
+
nextBlock.appendChild(nextStatsLine);
|
| 759 |
+
summary.appendChild(nextBlock);
|
| 760 |
+
|
| 761 |
+
card.appendChild(summary);
|
| 762 |
+
|
| 763 |
+
// --- Full chain table ---
|
| 764 |
+
var table = createEl('table', { className: 'chain-table' });
|
| 765 |
+
var thead = createEl('thead');
|
| 766 |
+
var headRow = createEl('tr');
|
| 767 |
+
['#', 'Model', 'Status', '24h calls', 'Share', 'Avg ms', 'Success', 'Actions'].forEach(function (h) {
|
| 768 |
+
var th = createEl('th', { text: h });
|
| 769 |
+
if (h === '24h calls' || h === 'Share' || h === 'Avg ms' || h === 'Success' || h === '#') {
|
| 770 |
+
th.style.textAlign = 'right';
|
| 771 |
+
}
|
| 772 |
+
headRow.appendChild(th);
|
| 773 |
+
});
|
| 774 |
+
thead.appendChild(headRow);
|
| 775 |
+
table.appendChild(thead);
|
| 776 |
|
| 777 |
+
var tbody = createEl('tbody');
|
| 778 |
+
table.appendChild(tbody);
|
| 779 |
+
card.appendChild(table);
|
| 780 |
|
| 781 |
+
function rerenderTable() { renderChainTableRows(tbody, role, stats); }
|
| 782 |
+
rerenderTable();
|
| 783 |
|
| 784 |
+
// --- Save / Reload actions ---
|
| 785 |
var actions = createEl('div', { className: 'actions' });
|
| 786 |
var saveBtn = createEl('button', { className: 'primary', text: 'Save' });
|
| 787 |
saveBtn.onclick = function () {
|
|
|
|
| 802 |
};
|
| 803 |
|
| 804 |
var revertBtn = createEl('button', { text: 'Reload' });
|
| 805 |
+
revertBtn.onclick = function () {
|
| 806 |
+
refreshAll().catch(handleFetchErr);
|
| 807 |
+
};
|
| 808 |
|
| 809 |
actions.appendChild(saveBtn);
|
| 810 |
actions.appendChild(revertBtn);
|
|
|
|
| 814 |
});
|
| 815 |
}
|
| 816 |
|
| 817 |
+
function renderChainTableRows(tbody, role, stats) {
|
| 818 |
+
clearChildren(tbody);
|
| 819 |
var chain = STATE.chains[role] || [];
|
| 820 |
if (!chain.length) {
|
| 821 |
+
var tr = createEl('tr');
|
| 822 |
+
var td = createEl('td', { text: 'Empty chain.', attrs: { colspan: '8' } });
|
| 823 |
+
td.classList.add('muted');
|
| 824 |
+
tr.appendChild(td);
|
| 825 |
+
tbody.appendChild(tr);
|
| 826 |
return;
|
| 827 |
}
|
| 828 |
chain.forEach(function (model, idx) {
|
| 829 |
+
var tr = createEl('tr');
|
| 830 |
+
if (idx === 0) tr.classList.add('is-primary');
|
|
|
|
| 831 |
|
| 832 |
+
var idxCell = createEl('td', { className: 'num-cell', text: String(idx + 1) });
|
| 833 |
+
tr.appendChild(idxCell);
|
| 834 |
|
| 835 |
+
var modelCell = createEl('td', { className: 'model-cell' });
|
| 836 |
if (idx === 0) {
|
| 837 |
+
var star = createEl('span', { className: 'primary-mark', text: 'β
' });
|
| 838 |
+
modelCell.appendChild(star);
|
| 839 |
}
|
| 840 |
+
modelCell.appendChild(document.createTextNode(model));
|
| 841 |
+
tr.appendChild(modelCell);
|
| 842 |
+
|
| 843 |
+
var statusCell = createEl('td');
|
| 844 |
+
statusCell.appendChild(statusPill(statusForModel(model)));
|
| 845 |
+
tr.appendChild(statusCell);
|
| 846 |
+
|
| 847 |
+
var b = stats.byModel[model];
|
| 848 |
+
var callsCell = createEl('td', { className: 'num-cell', text: b ? String(b.calls) : '0' });
|
| 849 |
+
tr.appendChild(callsCell);
|
| 850 |
+
|
| 851 |
+
var shareCell = createEl('td', { className: 'num-cell', text: b ? fmtPct(b.share) : 'β' });
|
| 852 |
+
tr.appendChild(shareCell);
|
| 853 |
+
|
| 854 |
+
var latCell = createEl('td', { className: 'num-cell', text: b ? fmtLatency(b.avg_latency_ms) : 'β' });
|
| 855 |
+
tr.appendChild(latCell);
|
| 856 |
|
| 857 |
+
var successCell = createEl('td', { className: 'num-cell', text: b ? fmtPct(b.success_rate) : 'β' });
|
| 858 |
+
tr.appendChild(successCell);
|
| 859 |
+
|
| 860 |
+
var actionsCell = createEl('td');
|
| 861 |
var moves = createEl('span', { className: 'move-buttons' });
|
| 862 |
var up = createEl('button', { className: 'icon-btn', text: 'β', title: 'Move up' });
|
| 863 |
up.disabled = (idx === 0);
|
|
|
|
| 867 |
var tmp = arr[idx - 1];
|
| 868 |
arr[idx - 1] = arr[idx];
|
| 869 |
arr[idx] = tmp;
|
| 870 |
+
renderChainTableRows(tbody, role, stats);
|
| 871 |
};
|
| 872 |
var down = createEl('button', { className: 'icon-btn', text: 'β', title: 'Move down' });
|
| 873 |
down.disabled = (idx === chain.length - 1);
|
|
|
|
| 877 |
var tmp = arr[idx + 1];
|
| 878 |
arr[idx + 1] = arr[idx];
|
| 879 |
arr[idx] = tmp;
|
| 880 |
+
renderChainTableRows(tbody, role, stats);
|
| 881 |
};
|
| 882 |
moves.appendChild(up);
|
| 883 |
moves.appendChild(down);
|
| 884 |
+
actionsCell.appendChild(moves);
|
| 885 |
+
tr.appendChild(actionsCell);
|
| 886 |
|
| 887 |
+
tbody.appendChild(tr);
|
| 888 |
});
|
| 889 |
}
|
| 890 |
|
| 891 |
+
function healthRowFor(modelName) {
|
| 892 |
+
var rows = healthRows();
|
| 893 |
+
for (var i = 0; i < rows.length; i++) {
|
| 894 |
+
if (rows[i].model === modelName) return rows[i];
|
| 895 |
+
}
|
| 896 |
+
return null;
|
| 897 |
+
}
|
| 898 |
+
|
| 899 |
function setLastUpdated() {
|
| 900 |
var el = $('last-updated');
|
| 901 |
if (!el) return;
|
|
|
|
| 923 |
});
|
| 924 |
}
|
| 925 |
|
| 926 |
+
function fetchUsage() {
|
| 927 |
+
// Backward-compatible: usage endpoint may return empty stats when the
|
| 928 |
+
// JSONL log doesn't exist yet. Treat any failure as "no usage data"
|
| 929 |
+
// so the UI still renders the chain editor cleanly.
|
| 930 |
+
return apiGet('/api/admin/usage').then(function (data) {
|
| 931 |
+
STATE.usage = (data && typeof data === 'object') ? data : null;
|
| 932 |
+
}).catch(function () {
|
| 933 |
+
STATE.usage = null;
|
| 934 |
+
});
|
| 935 |
+
}
|
| 936 |
+
|
| 937 |
function refreshAll() {
|
| 938 |
+
return Promise.all([fetchHealth(), fetchChains(), fetchUsage()]).then(function () {
|
| 939 |
renderCounters();
|
| 940 |
renderHealthTable();
|
| 941 |
renderChains();
|