Update app.py
Browse files9 unmodified lines10111213141550 unmodified lines666768697071727374757610 unmodified lines8788899091929343 unmodified lines1371381391401411421435 unmodified lines1491501511521531541551561571581591601612 unmodified lines1641651661671681691703 unmodified lines17417517617717817918033 unmodified lines21421521621721821922077 unmodified lines2982993003013023033041 unmodified line3063073083093103113123 unmodified lines3163173183193203213223 unmodified lines3263273283293303313326 unmodified lines33934034134234334434534627 unmodified lines37437537637737837938038138238338438538638738846 unmodified lines4354364374384394402 unmodified lines44344444544644744844950 unmodified lines5005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356362 unmodified lines6396406416426436446456466476 unmodified lines6546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956963 unmodified lines7007017027037047057067077087097109 unmodified lines72072172272372472572672772872973073173273330 unmodified lines7647657667677687697707 unmodified lines77877978078178278378478578678778878979079179279379479579679713 unmodified lines81181281381481581681781881982082182282343 unmodified lines86786886987087187287387487587687787887988088188212 unmodified lines89589689789889990090190290390421 unmodified lines92692792892993093193293311 unmodified lines9459469479489499509519529539549559569579589599602 unmodified lines96396496596696796814 unmodified lines98398498598698798846 unmodified lines103510361037103810391040104110421 unmodified line104410451046104710481049105010511052105310541055105610571058105921 unmodified lines10811082108310841085108610871088108910901091109210931094109510967 unmodified lines110411051106110711081109111052 unmodified lines116311641165116611671168116911 unmodified lines11811182118311841185118611879 unmodified lines- Auto-detects 429s and marks endpoints as cooled down- Respects RPM / RPD / RPS limits configured per provider- Smart selection skips exhausted endpoints"""import os50 unmodified linesclass RateLimitState:def __init__(self):self._lock = asyncio.Lock()# cooldown_until: float timestampself._cooldown: Dict[str, float] = {}# request timestamps for RPM/RPD/RPS tracking: deque of floatsself._timestamps: Dict[str, deque] = defaultdict(lambda: deque(maxlen=10000))# round-robin index per poolself._rr_index: Dict[str, int] = defaultdict(int)def key(self, provider_id: str, model_name: str) -> str:10 unmodified linesk = self.key(provider_id, model_name)now = time.time()# Check hard cooldown (from 429)if self._cooldown.get(k, 0) > now:return False43 unmodified linesif not authorization or not authorization.startswith("Bearer "):raise HTTPException(status_code=401, detail="Missing Authorization header")token = authorization[7:]# Admin key always worksif token == ADMIN_KEY:return tokendata = load_data()5 unmodified lines# ── Routing logic ──────────────────────────────────────────────────────────────async def resolve_endpoint(model_str: str, data: dict):"""Returns (provider_cfg, actual_model_name) or raises HTTPException.Handles:- "provider_id/model_name" → direct provider lookup- "pool_name" → pool routing"""# Direct: contains a slash → treat as provider_id/modelif "/" in model_str:parts = model_str.split("/", 1)provider_id, model_name = parts[0], parts[1]2 unmodified linesraise HTTPException(status_code=404, detail=f"Provider '{provider_id}' not found")return provider, model_name, provider_id# Pool lookuppool = Nonepool_id = Nonefor pid, p in data["pool_models"].items():3 unmodified linesbreakif not pool:raise HTTPException(status_code=404, detail=f"Model or pool '{model_str}' not found. Use 'provider_id/model_name' or a configured pool name.")members = pool.get("members", [])if not members:33 unmodified lineschosen_m, chosen_p = random.choices(available, weights=weights, k=1)[0]return chosen_p, chosen_m["model_name"], chosen_m["provider_id"]raise HTTPException(status_code=429, detail=f"All endpoints in pool '{model_str}' are currently rate-limited. Try again shortly.")# ── Proxy logic ────────────────────────────────────────────────────────────────77 unmodified linestemperature: Optional[float] = Nonemax_tokens: Optional[int] = Nonetop_p: Optional[float] = None# Pass through any extra fieldsmodel_config = {"extra": "allow"}@app.post("/v1/chat/completions")1 unmodified linedata = load_data()provider, model_name, provider_id = await resolve_endpoint(request.model, data)body = request.model_dump(exclude_none=True, exclude={"model"})# Include any extra fields passed throughbody.update(request.model_extra or {})return await proxy_request(provider, model_name, provider_id, body, request.stream or False)3 unmodified linesnow = int(time.time())models = []# Direct provider models (listed as provider_id/model if provider has known models)for pid, p in data["providers"].items():for m in p.get("known_models", []):models.append({3 unmodified lines"owned_by": pid,})# Pool modelsfor pool_id, pool in data["pool_models"].items():models.append({"id": pool["name"],6 unmodified lines# ── Admin API ──────────────────────────────────────────────────────────────────# --- API Keys ---@app.get("/admin/api-keys")async def get_api_keys(_=Depends(require_admin)):data = load_data()27 unmodified lines@app.get("/admin/providers")async def get_providers(_=Depends(require_admin)):data = load_data()# Return providers with masked API keys and live rate limit stateresult = []for pid, p in data["providers"].items():entry = {**p, "id": pid}raw = entry.get("api_key", "")entry["api_key_masked"] = raw[:6] + "..." + raw[-4:] if len(raw) > 10 else "****"# Don't send actual key to frontendentry.pop("api_key", None)# Add live cooldown info per known modelcooldowns = {}for m in p.get("known_models", []):cd = rl_state.get_cooldown_remaining(pid, m)46 unmodified linessave_data(data)return {"deleted": True}# --- Pool Models ---@app.get("/admin/pools")2 unmodified linesresult = []for pool_id, pool in data["pool_models"].items():entry = {**pool, "id": pool_id}# Annotate members with live availabilityannotated = []for m in pool.get("members", []):provider = data["providers"].get(m["provider_id"], {})50 unmodified lines"api_keys": len(data["api_keys"]),}# ── Dashboard (embedded HTML) ──────────────────────────────────────────────────DASHBOARD_HTML = r"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>RyzGateway</title><style>*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }:root {--bg: #0f0f11;--surface: #17171a;--surface2: #1e1e23;--surface3: #26262d;--border: rgba(255,255,255,0.08);--border-strong: rgba(255,255,255,0.15);--text: #e8e8f0;--muted: #888899;--accent: #7c6af7;--accent-dim: rgba(124,106,247,0.15);--accent-hover: #9080ff;--green: #4ade80;--green-dim: rgba(74,222,128,0.12);--red: #f87171;--red-dim: rgba(248,113,113,0.12);--amber: #fbbf24;--amber-dim: rgba(251,191,36,0.12);--radius: 8px;--radius-lg: 12px;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;}body { background: var(--bg); color: var(--text); min-height: 100vh; }/* Layout */.app { display: flex; min-height: 100vh; }.sidebar { width: 220px; flex-shrink: 0; background: var(--surface); border-right: 1px solid var(--border); padding: 1.5rem 0; display: flex; flex-direction: column; position: fixed; top: 0; left: 0; height: 100vh; z-index: 100; }.main { margin-left: 220px; flex: 1; padding: 2rem; max-width: 960px; }/* Sidebar */.logo { padding: 0 1.25rem 1.5rem; border-bottom: 1px solid var(--border); margin-bottom: 0.75rem; }.logo-text { font-size: 1.1rem; font-weight: 700; color: var(--text); letter-spacing: -0.02em; }.logo-sub { font-size: 0.7rem; color: var(--muted); margin-top: 2px; }.nav-item { display: flex; align-items: center; gap: 10px; padding: 0.55rem 1.25rem; color: var(--muted); cursor: pointer; font-size: 0.875rem; transition: all 0.15s; border-left: 2px solid transparent; }.nav-item:hover { color: var(--text); background: var(--surface2); }.nav-item.active { color: var(--accent); background: var(--accent-dim); border-left-color: var(--accent); }.nav-item svg { width: 16px; height: 16px; flex-shrink: 0; }.nav-section { font-size: 0.65rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; padding: 1rem 1.25rem 0.4rem; }/* Auth gate */#auth-gate { position: fixed; inset: 0; background: var(--bg); display: flex; align-items: center; justify-content: center; z-index: 999; }.auth-box { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 2rem; width: 340px; }.auth-box h2 { font-size: 1.1rem; margin-bottom: 0.5rem; }.auth-box p { color: var(--muted); font-size: 0.85rem; margin-bottom: 1.5rem; }/* Page header */.page-header { margin-bottom: 1.75rem; }.page-title { font-size: 1.35rem; font-weight: 700; letter-spacing: -0.02em; }.page-sub { color: var(--muted); font-size: 0.85rem; margin-top: 4px; }/* Cards */.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 1.25rem; }.card + .card { margin-top: 1rem; }/* Stats row */.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; margin-bottom: 1.5rem; }.stat { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 1rem 1.25rem; }.stat-val { font-size: 1.75rem; font-weight: 700; color: var(--text); }.stat-label { font-size: 0.75rem; color: var(--muted); margin-top: 2px; }/* Table */.table-wrap { overflow-x: auto; }table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }th { text-align: left; color: var(--muted); font-weight: 500; font-size: 0.75rem; padding: 0 0.75rem 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; }td { padding: 0.7rem 0.75rem; border-top: 1px solid var(--border); vertical-align: middle; }tr:hover td { background: var(--surface2); }/* Badges */.badge { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 99px; font-size: 0.72rem; font-weight: 500; }.badge-green { background: var(--green-dim); color: var(--green); }.badge-red { background: var(--red-dim); color: var(--red); }.badge-amber { background: var(--amber-dim); color: var(--amber); }.badge-purple { background: var(--accent-dim); color: var(--accent); }.badge-gray { background: rgba(255,255,255,0.06); color: var(--muted); }.dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }/* Buttons */.btn { display: inline-flex; align-items: center; gap: 6px; padding: 0.45rem 0.9rem; border-radius: var(--radius); border: 1px solid var(--border-strong); background: var(--surface2); color: var(--text); font-size: 0.82rem; cursor: pointer; transition: all 0.15s; white-space: nowrap; }.btn:hover { background: var(--surface3); border-color: rgba(255,255,255,0.22); }.btn-primary { background: var(--accent); border-color: var(--accent); color: #fff; }.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }.btn-danger { background: var(--red-dim); border-color: rgba(248,113,113,0.3); color: var(--red); }.btn-danger:hover { background: rgba(248,113,113,0.2); }.btn-sm { padding: 0.3rem 0.65rem; font-size: 0.78rem; }.btn-row { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 1rem; }/* Forms */.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem; }.form-grid.full { grid-template-columns: 1fr; }.field { display: flex; flex-direction: column; gap: 5px; }.field.span2 { grid-column: span 2; }label { font-size: 0.78rem; color: var(--muted); font-weight: 500; }input, select, textarea { background: var(--surface2); border: 1px solid var(--border-strong); border-radius: var(--radius); color: var(--text); padding: 0.5rem 0.75rem; font-size: 0.85rem; font-family: inherit; width: 100%; transition: border-color 0.15s; }input:focus, select:focus, textarea:focus { outline: none; border-color: var(--accent); }select option { background: var(--surface2); }textarea { min-height: 70px; resize: vertical; }.field-note { font-size: 0.72rem; color: var(--muted); }/* Modal */.overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.65); display: flex; align-items: center; justify-content: center; z-index: 500; padding: 1rem; }.modal { background: var(--surface); border: 1px solid var(--border-strong); border-radius: var(--radius-lg); width: 100%; max-width: 560px; max-height: 90vh; overflow-y: auto; }.modal-header { padding: 1.25rem 1.5rem 1rem; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }.modal-title { font-size: 1rem; font-weight: 600; }.modal-body { padding: 1.25rem 1.5rem; }.modal-footer { padding: 1rem 1.5rem; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 0.5rem; }.close-btn { background: none; border: none; color: var(--muted); cursor: pointer; font-size: 1.2rem; line-height: 1; padding: 4px; }.close-btn:hover { color: var(--text); }/* Members list in pool */.member-item { display: flex; align-items: center; gap: 8px; background: var(--surface2); border: 1px solid var(--border); border-radius: var(--radius); padding: 0.5rem 0.75rem; margin-bottom: 0.5rem; }.member-item .member-label { flex: 1; font-size: 0.82rem; }.member-badge { font-size: 0.72rem; color: var(--muted); }/* Code / key display */.key-display { font-family: 'SF Mono', Consolas, monospace; font-size: 0.8rem; background: var(--surface2); border: 1px solid var(--border); border-radius: var(--radius); padding: 0.5rem 0.75rem; word-break: break-all; color: var(--green); }/* Toast */#toast { position: fixed; bottom: 1.5rem; right: 1.5rem; background: var(--surface3); border: 1px solid var(--border-strong); border-radius: var(--radius); padding: 0.65rem 1rem; font-size: 0.83rem; z-index: 9999; opacity: 0; transition: opacity 0.2s; pointer-events: none; max-width: 300px; }#toast.show { opacity: 1; }/* Empty state */.empty { text-align: center; padding: 3rem 1rem; color: var(--muted); font-size: 0.9rem; }2 unmodified lines.section { display: none; }.section.active { display: block; }/* Help callout */.callout { background: var(--accent-dim); border: 1px solid rgba(124,106,247,0.25); border-radius: var(--radius); padding: 0.85rem 1rem; font-size: 0.82rem; color: var(--text); margin-bottom: 1.25rem; line-height: 1.6; }.callout code { background: rgba(255,255,255,0.1); border-radius: 4px; padding: 1px 5px; font-family: monospace; font-size: 0.8rem; }</style></head><body>6 unmodified lines<label>Admin Key</label><input type="password" id="login-key" placeholder="sk-admin-..." /></div><button class="btn btn-primary" style="width:100%" onclick="doLogin()">Sign in</button><div id="login-err" style="color:var(--red);font-size:0.8rem;margin-top:0.75rem;display:none">Invalid key.</div></div></div><div class="app" id="app-shell" style="display:none"><aside class="sidebar"><div class="logo"><div class="logo-text">RyzGateway</div><div class="logo-sub">BYOK AI Router</div></div><div class="nav-section">Overview</div><div class="nav-item active" onclick="nav('overview')"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>Dashboard</div><div class="nav-section">Configure</div><div class="nav-item" onclick="nav('providers')"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>Providers</div><div class="nav-item" onclick="nav('pools')"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>Model Pools</div><div class="nav-item" onclick="nav('keys')"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>API Keys</div><div class="nav-section">Reference</div><div class="nav-item" onclick="nav('docs')"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>Usage Docs</div></aside><main class="main"><!-- OVERVIEW --><div class="section active" id="sec-overview">3 unmodified lines</div><div class="stats" id="stats-row"><div class="stat"><div class="stat-val" id="stat-providers">—</div><div class="stat-label">Providers</div></div><div class="stat"><div class="stat-val" id="stat-pools">—</div><div class="stat-label">Model Pools</div></div><div class="stat"><div class="stat-val" id="stat-keys">—</div><div class="stat-label">API Keys</div></div></div><div class="card"><div style="font-size:0.85rem;font-weight:600;margin-bottom:1rem">Provider health</div><div id="health-list"><div class="empty">No providers configured</div></div></div></div>9 unmodified lines<button class="btn" onclick="loadProviders()">↺ Refresh</button></div><div class="callout"><strong>Provider ID</strong> is auto-generated from the name and used in model routing:<br>Use <code>provider-id/exact-model-name</code> in your API calls to route directly to this provider.</div><div class="card"><div class="table-wrap"><table><thead><tr><th>Provider</th><th>Base URL</th><th>Rate limit</th><th>Models</th><th>Status</th><th></th></tr></thead><tbody id="providers-tbody"><tr><td colspan="6"><div class="empty">Loading...</div></td></tr></tbody></table>30 unmodified lines<div class="card"><div class="table-wrap"><table><thead><tr><th>Name</th><th>Key</th><th>Created</th><th></th></tr></thead><tbody id="keys-tbody"><tr><td colspan="4"><div class="empty">Loading...</div></td></tr></tbody></table></div>7 unmodified lines<div class="page-sub">How to use RyzGateway in your apps</div></div><div class="card" style="margin-bottom:1rem"><div style="font-size:0.85rem;font-weight:600;margin-bottom:0.75rem">Base URL</div><div class="key-display" id="base-url-display"></div><div style="font-size:0.78rem;color:var(--muted);margin-top:0.5rem">Point any OpenAI-compatible client at this URL.</div></div><div class="card" style="margin-bottom:1rem"><div style="font-size:0.85rem;font-weight:600;margin-bottom:0.75rem">Model name formats</div><div style="font-size:0.85rem;line-height:1.8;color:var(--text)"><div style="margin-bottom:0.75rem"><span style="font-family:monospace;background:var(--surface2);padding:2px 6px;border-radius:4px;color:var(--accent)">provider-id/exact-model-name</span> — Direct passthrough. Requests go to that provider using the exact model string, no pool routing.</div><div><span style="font-family:monospace;background:var(--surface2);padding:2px 6px;border-radius:4px;color:var(--green)">pool-name</span> — Pool routing. Gateway picks the best available member based on your pool strategy (round-robin, priority, weighted).</div></div></div><div class="card" style="margin-bottom:1rem"><div style="font-size:0.85rem;font-weight:600;margin-bottom:0.75rem">Example: Python (openai SDK)</div><pre style="font-size:0.78rem;background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius);padding:0.875rem;overflow-x:auto;line-height:1.7;color:var(--text)"><code>import openaiclient = openai.OpenAI(base_url="<span id="doc-base-url"></span>",13 unmodified lines)</code></pre></div><div class="card"><div style="font-size:0.85rem;font-weight:600;margin-bottom:0.75rem">Rate limit types</div><table style="font-size:0.82rem"><thead><tr><th>Type</th><th>Meaning</th><th>Window</th></tr></thead><tbody><tr><td><span class="badge badge-purple">RPM</span></td><td>Requests per minute</td><td>60 seconds</td></tr><tr><td><span class="badge badge-green">RPS</span></td><td>Requests per second</td><td>1 second</td></tr><tr><td><span class="badge badge-amber">RPD</span></td><td>Requests per day</td><td>86400 seconds</td></tr><tr><td><span class="badge badge-gray">None</span></td><td>No limit tracked</td><td>—</td></tr></tbody></table>43 unmodified linesconst opts = { method, headers: { 'Authorization': 'Bearer ' + ADMIN_KEY, 'Content-Type': 'application/json' } };if (body) opts.body = JSON.stringify(body);const r = await fetch(path, opts);if (!r.ok) { const t = await r.text(); throw new Error(t); }return r.json();}// ── Navigation ───────────────────────────────────────────────────────────────function nav(id) {document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));document.getElementById('sec-' + id).classList.add('active');event.currentTarget.classList.add('active');if (id === 'overview') loadOverview();if (id === 'providers') loadProviders();if (id === 'pools') loadPools();12 unmodified linesfunction toast(msg, type='ok') {const el = document.getElementById('toast');el.textContent = msg;el.style.borderColor = type === 'err' ? 'var(--red-dim)' : 'var(--border-strong)';el.classList.add('show');clearTimeout(toastTimer);toastTimer = setTimeout(() => el.classList.remove('show'), 3000);}// ── Modal ────────────────────────────────────────────────────────────────────21 unmodified lines? `<span class="badge badge-amber"><span class="dot"></span>${cds.length} cooling</span>`: `<span class="badge badge-green"><span class="dot"></span>OK</span>`;const rl = p.rate_type !== 'none' ? `<span class="badge badge-gray">${p.rate_limit} ${p.rate_type.toUpperCase()}</span>` : '<span class="badge badge-gray">no limit</span>';return `<div style="display:flex;align-items:center;gap:12px;padding:0.6rem 0;border-bottom:1px solid var(--border)"><div style="flex:1;font-size:0.85rem;font-weight:500">${p.name} <span style="color:var(--muted);font-weight:400;font-size:0.78rem">${p.id}</span></div><div>${rl}</div><div>${status}</div></div>`;11 unmodified linesconst rl = p.rate_type !== 'none' ? `${p.rate_limit} ${p.rate_type.toUpperCase()}` : '—';const cds = Object.entries(p.active_cooldowns || {});const statusBadge = cds.length? `<span class="badge badge-amber"><span class="dot"></span>${cds.length} cooling</span>`: `<span class="badge badge-green"><span class="dot"></span>OK</span>`;const models = (p.known_models || []).length;return `<tr><td><div style="font-weight:500">${p.name}</div><div style="font-size:0.75rem;color:var(--muted)">${p.id}</div></td><td style="font-size:0.78rem;color:var(--muted);max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${p.base_url}</td><td>${rl}</td><td>${models} known</td><td>${statusBadge}</td><td style="text-align:right"><button class="btn btn-sm" onclick='editProvider(${JSON.stringify(p)})'>Edit</button><button class="btn btn-sm btn-danger" onclick="deleteProvider('${p.id}','${p.name}')">Del</button></td>2 unmodified lines} catch(e) { console.error(e); }}function openProviderModal(existing) {const p = existing || {};const isEdit = !!p.id;14 unmodified lines<div class="field"><label>Rate limit value</label><input id="p-rlimit" type="number" value="${p.rate_limit||0}" min="0"></div><div class="field span2"><label>Known models (comma-separated)</label><input id="p-models" value="${(p.known_models||[]).join(', ')}" placeholder="gpt-4o, gpt-4o-mini, ..."></div><div class="field span2"><label>Notes</label><textarea id="p-notes">${p.notes||''}</textarea></div></div>`;const footer = `<button class="btn" onclick="closeModal()">Cancel</button>46 unmodified linesconst stratBadge = {round_robin:'<span class="badge badge-purple">Round robin</span>', priority:'<span class="badge badge-amber">Priority</span>', weighted:'<span class="badge badge-green">Weighted</span>'}[pool.strategy] || '';const members = (pool.members||[]).map(m => {const avail = m.available;const cd = m.cooldown_remaining > 0 ? ` — cooling ${m.cooldown_remaining}s` : '';const badge = avail ? '<span class="badge badge-green"><span class="dot"></span>OK</span>' : `<span class="badge badge-red"><span class="dot"></span>Rate limited${cd}</span>`;return `<div class="member-item"><div class="member-label"><strong>${m.provider_id}</strong> / ${m.model_name}</div>${m.weight !== undefined ? `<span class="member-badge">w:${m.weight}</span>` : ''}1 unmodified line</div>`;}).join('');return `<div class="card" style="margin-bottom:1rem"><div style="display:flex;align-items:center;gap:10px;margin-bottom:1rem"><div style="flex:1"><div style="font-weight:600;font-size:0.95rem">${pool.name}</div><div style="font-size:0.75rem;color:var(--muted)">${pool.id}</div></div>${stratBadge}<button class="btn btn-sm" onclick='openPoolModal(${JSON.stringify(pool)})'>Edit</button><button class="btn btn-sm btn-danger" onclick="deletePool('${pool.id}','${pool.name}')">Del</button></div>${members || '<div style="color:var(--muted);font-size:0.82rem">No members</div>'}</div>`;}).join('');} catch(e) { console.error(e); }21 unmodified lines</select></div></div><div style="font-size:0.78rem;color:var(--muted);font-weight:500;margin-bottom:0.5rem">MEMBERS</div><div id="pool-members-list"></div><div style="background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius);padding:0.85rem;margin-top:0.5rem"><div style="font-size:0.78rem;color:var(--muted);margin-bottom:0.6rem">Add member</div><div style="display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:end"><div class="field"><label>Provider</label><select id="new-m-prov">${provOpts||'<option>No providers</option>'}</select></div><div class="field"><label>Model name</label><input id="new-m-model" placeholder="google/gemini-flash-1.5"></div><div class="field"><label>Weight</label><input id="new-m-weight" type="number" value="1" min="1" style="width:60px"></div></div><button class="btn btn-sm" style="margin-top:8px" onclick="addPoolMember()">+ Add</button></div>`;const footer = `7 unmodified linesfunction renderPoolMembers() {const el = document.getElementById('pool-members-list');if (!el) return;if (!poolMembers.length) { el.innerHTML = '<div style="color:var(--muted);font-size:0.82rem;margin-bottom:0.5rem">No members yet</div>'; return; }el.innerHTML = poolMembers.map((m, i) =>`<div class="member-item"><div class="member-label">${m.provider_id} / ${m.model_name}</div>52 unmodified lines`<tr><td style="font-weight:500">${k.name}</td><td><div class="key-display">${k.key}</div></td><td style="color:var(--muted);font-size:0.78rem">${new Date(k.created_at*1000).toLocaleDateString()}</td><td style="text-align:right"><button class="btn btn-sm btn-danger" onclick="deleteKey('${k.id}','${k.name}')">Delete</button></td></tr>`).join('');11 unmodified linesconst name = document.getElementById('key-name').value.trim();if (!name) { toast('Name required', 'err'); return; }try {const k = await api('POST', '/admin/api-keys', { name });closeModal();toast('Key created');loadKeys();9 unmodified lines1011121314151617181950 unmodified lines707172737475767710 unmodified lines88899091929343 unmodified lines1371381391401411425 unmodified lines1481491501511521532 unmodified lines1561571581591601613 unmodified lines16516616716816917017133 unmodified lines20520620720820921021177 unmodified lines2892902912922932941 unmodified line2962972982993003013 unmodified lines3053063073083093103 unmodified lines3143153163173183196 unmodified lines32632732832933033127 unmodified lines35936036136236336436536636736836937037146 unmodified lines4184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744752 unmodified lines47847948048148248350 unmodified lines5345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247252 unmodified lines7287297307317327337347357367377387397407417427437447457467477487497507517527537547557567576 unmodified lines7647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148153 unmodified lines8198208218228238248258268278288299 unmodified lines83984084184284384484584684784884985085130 unmodified lines8828838848858868878887 unmodified lines89689789889990090190290390490590690790890991091191291391491513 unmodified lines92993093193293393493593693793893994094143 unmodified lines98598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101112 unmodified lines1024102510261027102810291030103110321033103421 unmodified lines1056105710581059106010611062106311 unmodified lines107510761077107810791080108110821083108410851086108710881089109010912 unmodified lines10941095109610971098109911001101110211031104110511061107110811091110111114 unmodified lines11261127112811291130113111321133113446 unmodified lines118111821183118411851186118711881 unmodified line119011911192119311941195119611971198119912001201120212031204120521 unmodified lines12271228122912301231123212331234123512361237123812391240124112427 unmodified lines125012511252125312541255125652 unmodified lines130913101311131213131314131511 unmodified lines13271328132913301331133213339 unmodified lines- Auto-detects 429s and marks endpoints as cooled down- Respects RPM / RPD / RPS limits configured per provider- Smart selection skips exhausted endpointsFeatures:- Glassmorphism UI (highly optimized for mobile touch)- Auto-fetches and imports models directly from provider's /v1/models"""import os50 unmodified linesclass RateLimitState:def __init__(self):self._lock = asyncio.Lock()self._cooldown: Dict[str, float] = {}self._timestamps: Dict[str, deque] = defaultdict(lambda: deque(maxlen=10000))self._rr_index: Dict[str, int] = defaultdict(int)def key(self, provider_id: str, model_name: str) -> str:10 unmodified linesk = self.key(provider_id, model_name)now = time.time()if self._cooldown.get(k, 0) > now:return False43 unmodified linesif not authorization or not authorization.startswith("Bearer "):raise HTTPException(status_code=401, detail="Missing Authorization header")token = authorization[7:]if token == ADMIN_KEY:return tokendata = load_data()5 unmodified lines# ── Routing logic ──────────────────────────────────────────────────────────────async def resolve_endpoint(model_str: str, data: dict):if "/" in model_str:parts = model_str.split("/", 1)provider_id, model_name = parts[0], parts[1]2 unmodified linesraise HTTPException(status_code=404, detail=f"Provider '{provider_id}' not found")return provider, model_name, provider_idpool = Nonepool_id = Nonefor pid, p in data["pool_models"].items():3 unmodified linesbreakif not pool:raise HTTPException(status_code=404, detail=f"Model or pool '{model_str}' not found.")members = pool.get("members", [])if not members:33 unmodified lineschosen_m, chosen_p = random.choices(available, weights=weights, k=1)[0]return chosen_p, chosen_m["model_name"], chosen_m["provider_id"]raise HTTPException(status_code=429, detail=f"All endpoints in pool '{model_str}' are currently rate-limited.")# ── Proxy logic ────────────────────────────────────────────────────────────────77 unmodified linestemperature: Optional[float] = Nonemax_tokens: Optional[int] = Nonetop_p: Optional[float] = Nonemodel_config = {"extra": "allow"}@app.post("/v1/chat/completions")1 unmodified linedata = load_data()provider, model_name, provider_id = await resolve_endpoint(request.model, data)body = request.model_dump(exclude_none=True, exclude={"model"})body.update(request.model_extra or {})return await proxy_request(provider, model_name, provider_id, body, request.stream or False)3 unmodified linesnow = int(time.time())models = []for pid, p in data["providers"].items():for m in p.get("known_models", []):models.append({3 unmodified lines"owned_by": pid,})for pool_id, pool in data["pool_models"].items():models.append({"id": pool["name"],6 unmodified lines# ── Admin API ──────────────────────────────────────────────────────────────────@app.get("/admin/api-keys")async def get_api_keys(_=Depends(require_admin)):data = load_data()27 unmodified lines@app.get("/admin/providers")async def get_providers(_=Depends(require_admin)):data = load_data()result = []for pid, p in data["providers"].items():entry = {**p, "id": pid}raw = entry.get("api_key", "")entry["api_key_masked"] = raw[:6] + "..." + raw[-4:] if len(raw) > 10 else "****"entry.pop("api_key", None)cooldowns = {}for m in p.get("known_models", []):cd = rl_state.get_cooldown_remaining(pid, m)46 unmodified linessave_data(data)return {"deleted": True}@app.post("/admin/providers/{pid}/fetch-models")async def fetch_provider_models(pid: str, _=Depends(require_admin)):data = load_data()if pid not in data["providers"]:raise HTTPException(status_code=404, detail="Provider not found")p = data["providers"][pid]base_url = p["base_url"].rstrip("/")api_key = p["api_key"]if not base_url or not api_key:raise HTTPException(status_code=400, detail="Provider base_url or api_key is missing.")headers = {"Authorization": f"Bearer {api_key}","Content-Type": "application/json",}try:async with httpx.AsyncClient(timeout=15.0) as client:resp = await client.get(f"{base_url}/models", headers=headers)if resp.status_code != 200:raise HTTPException(status_code=502, detail=f"Upstream returned {resp.status_code}: {resp.text[:200]}")resp_data = resp.json()models = []if isinstance(resp_data, dict) and "data" in resp_data:for item in resp_data["data"]:if "id" in item:models.append(item["id"])elif isinstance(resp_data, list):for item in resp_data:if isinstance(item, dict) and "id" in item:models.append(item["id"])elif isinstance(item, str):models.append(item)if not models:raise HTTPException(status_code=404, detail="No models found in upstream /v1/models response.")# Remove duplicates and sortunique_models = sorted(list(set(models)))p["known_models"] = unique_modelssave_data(data)return {"fetched_count": len(unique_models), "models": unique_models}except httpx.RequestError as e:raise HTTPException(status_code=502, detail=f"Network error fetching models: {str(e)}")# --- Pool Models ---@app.get("/admin/pools")2 unmodified linesresult = []for pool_id, pool in data["pool_models"].items():entry = {**pool, "id": pool_id}annotated = []for m in pool.get("members", []):provider = data["providers"].get(m["provider_id"], {})50 unmodified lines"api_keys": len(data["api_keys"]),}# ── Dashboard (Mobile-Optimized Glassmorphism UI) ──────────────────────────────DASHBOARD_HTML = r"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>RyzGateway</title><style>*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }:root {--bg: #0a0a0f;--surface-glass: rgba(20, 20, 30, 0.55);--surface-glass-strong: rgba(30, 30, 45, 0.7);--border-glass: rgba(255, 255, 255, 0.1);--border-glass-strong: rgba(255, 255, 255, 0.2);--text: #f0f0f5;--muted: #8888a0;--accent: #7c6af7;--accent-dim: rgba(124,106,247,0.2);--accent-hover: #9080ff;--green: #4ade80;--green-dim: rgba(74,222,128,0.15);--red: #f87171;--red-dim: rgba(248,113,113,0.15);--amber: #fbbf24;--amber-dim: rgba(251,191,36,0.15);--radius: 10px;--radius-lg: 16px;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;}html, body { height: 100%; overscroll-behavior: none; }body {background: var(--bg);color: var(--text);min-height: 100vh;background-image:radial-gradient(circle at 0% 0%, rgba(124, 106, 247, 0.15) 0%, transparent 40%),radial-gradient(circle at 100% 100%, rgba(74, 222, 128, 0.1) 0%, transparent 40%);background-attachment: fixed;}/* Layout */.app { display: flex; min-height: 100vh; }.sidebar {width: 260px;flex-shrink: 0;background: var(--surface-glass);backdrop-filter: blur(20px) saturate(150%);-webkit-backdrop-filter: blur(20px) saturate(150%);border-right: 1px solid var(--border-glass);padding: 1.5rem 0;display: flex;flex-direction: column;position: fixed;top: 0; left: 0; height: 100vh;z-index: 100;transition: transform 0.3s ease;}.main {flex: 1;padding: 2rem;max-width: 960px;margin-left: 260px;}.mobile-header {display: none;position: sticky;top: 0;background: var(--surface-glass);backdrop-filter: blur(20px) saturate(150%);-webkit-backdrop-filter: blur(20px) saturate(150%);border-bottom: 1px solid var(--border-glass);padding: 1rem;z-index: 90;align-items: center;justify-content: space-between;}.menu-btn {background: rgba(255,255,255,0.1);border: 1px solid var(--border-glass);color: var(--text);width: 40px; height: 40px;border-radius: 10px;display: flex; align-items: center; justify-content: center;cursor: pointer;}/* Sidebar */.logo { padding: 0 1.25rem 1.5rem; border-bottom: 1px solid var(--border-glass); margin-bottom: 0.75rem; }.logo-text { font-size: 1.2rem; font-weight: 700; color: var(--text); letter-spacing: -0.02em; }.logo-sub { font-size: 0.75rem; color: var(--muted); margin-top: 4px; }.nav-item { display: flex; align-items: center; gap: 12px; padding: 0.75rem 1.25rem; color: var(--muted); cursor: pointer; font-size: 0.9rem; transition: all 0.2s; border-left: 3px solid transparent; }.nav-item:hover { color: var(--text); background: rgba(255,255,255,0.05); }.nav-item.active { color: var(--text); background: var(--accent-dim); border-left-color: var(--accent); }.nav-item svg { width: 18px; height: 18px; flex-shrink: 0; }.nav-section { font-size: 0.7rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; padding: 1.25rem 1.25rem 0.5rem; }/* Auth gate */#auth-gate { position: fixed; inset: 0; background: rgba(0,0,0,0.8); backdrop-filter: blur(10px); display: flex; align-items: center; justify-content: center; z-index: 999; padding: 1rem; }.auth-box { background: var(--surface-glass-strong); backdrop-filter: blur(30px) saturate(150%); -webkit-backdrop-filter: blur(30px) saturate(150%); border: 1px solid var(--border-glass-strong); border-radius: var(--radius-lg); padding: 2rem; width: 100%; max-width: 360px; }.auth-box h2 { font-size: 1.25rem; margin-bottom: 0.5rem; }.auth-box p { color: var(--muted); font-size: 0.85rem; margin-bottom: 1.5rem; }/* Page header */.page-header { margin-bottom: 1.75rem; }.page-title { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.02em; }.page-sub { color: var(--muted); font-size: 0.875rem; margin-top: 4px; }/* Cards */.card { background: var(--surface-glass); backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px); border: 1px solid var(--border-glass); border-radius: var(--radius-lg); padding: 1.25rem; transition: border-color 0.2s; }.card + .card { margin-top: 1rem; }/* Stats row */.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; margin-bottom: 1.5rem; }.stat { background: var(--surface-glass); backdrop-filter: blur(15px); border: 1px solid var(--border-glass); border-radius: var(--radius); padding: 1rem; text-align: center; }.stat-val { font-size: 1.5rem; font-weight: 700; color: var(--text); }.stat-label { font-size: 0.7rem; color: var(--muted); margin-top: 4px; text-transform: uppercase; letter-spacing: 0.05em; }/* Table */.table-wrap { overflow-x: auto; }table { width: 100%; border-collapse: collapse; font-size: 0.875rem; }th { text-align: left; color: var(--muted); font-weight: 500; font-size: 0.75rem; padding: 0 0.75rem 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; }td { padding: 0.875rem 0.75rem; border-top: 1px solid var(--border-glass); vertical-align: middle; }tr:hover td { background: rgba(255,255,255,0.03); }/* Badges */.badge { display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; border-radius: 99px; font-size: 0.7rem; font-weight: 600; }.badge-green { background: var(--green-dim); color: var(--green); }.badge-red { background: var(--red-dim); color: var(--red); }.badge-amber { background: var(--amber-dim); color: var(--amber); }.badge-purple { background: var(--accent-dim); color: var(--accent); }.badge-gray { background: rgba(255,255,255,0.08); color: var(--muted); }.dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }/* Buttons */.btn { display: inline-flex; align-items: center; gap: 6px; padding: 0.5rem 1rem; border-radius: var(--radius); border: 1px solid var(--border-glass-strong); background: rgba(255,255,255,0.05); color: var(--text); font-size: 0.85rem; cursor: pointer; transition: all 0.2s; white-space: nowrap; }.btn:hover { background: rgba(255,255,255,0.1); }.btn:active { transform: scale(0.97); }.btn-primary { background: var(--accent); border-color: var(--accent); color: #fff; }.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }.btn-danger { background: var(--red-dim); border-color: rgba(248,113,113,0.3); color: var(--red); }.btn-sm { padding: 0.35rem 0.7rem; font-size: 0.75rem; }.btn-row { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 1rem; }/* Forms */.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }.form-grid.full { grid-template-columns: 1fr; }.field { display: flex; flex-direction: column; gap: 6px; }.field.span2 { grid-column: span 2; }label { font-size: 0.8rem; color: var(--muted); font-weight: 500; }input, select, textarea { background: rgba(0,0,0,0.2); border: 1px solid var(--border-glass-strong); border-radius: var(--radius); color: var(--text); padding: 0.65rem 0.85rem; font-size: 0.9rem; font-family: inherit; width: 100%; transition: border-color 0.2s; }input:focus, select:focus, textarea:focus { outline: none; border-color: var(--accent); }select option { background: #1a1a25; }textarea { min-height: 70px; resize: vertical; }/* Modal */.overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(5px); display: flex; align-items: flex-end; justify-content: center; z-index: 500; padding: 0; }.modal { background: var(--surface-glass-strong); backdrop-filter: blur(30px) saturate(150%); -webkit-backdrop-filter: blur(30px) saturate(150%); border: 1px solid var(--border-glass-strong); border-radius: 20px 20px 0 0; width: 100%; max-width: 600px; max-height: 90vh; overflow-y: auto; animation: slideUp 0.3s ease-out; }@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }.modal-header { padding: 1.5rem 1.5rem 1rem; border-bottom: 1px solid var(--border-glass); display: flex; align-items: center; justify-content: space-between; position: sticky; top: 0; background: inherit; z-index: 10; }.modal-title { font-size: 1.1rem; font-weight: 600; }.modal-body { padding: 1.5rem; }.modal-footer { padding: 1rem 1.5rem; border-top: 1px solid var(--border-glass); display: flex; justify-content: flex-end; gap: 0.5rem; position: sticky; bottom: 0; background: inherit; }.close-btn { background: rgba(255,255,255,0.05); border: 1px solid var(--border-glass); color: var(--muted); cursor: pointer; font-size: 1.2rem; line-height: 1; padding: 6px 10px; border-radius: 8px; }.close-btn:hover { color: var(--text); background: rgba(255,255,255,0.1); }/* Members list in pool */.member-item { display: flex; align-items: center; gap: 8px; background: rgba(255,255,255,0.03); border: 1px solid var(--border-glass); border-radius: var(--radius); padding: 0.65rem 0.85rem; margin-bottom: 0.5rem; }.member-item .member-label { flex: 1; font-size: 0.85rem; word-break: break-all; }.member-badge { font-size: 0.75rem; color: var(--muted); }/* Code / key display */.key-display { font-family: 'SF Mono', Consolas, monospace; font-size: 0.8rem; background: rgba(0,0,0,0.3); border: 1px solid var(--border-glass); border-radius: var(--radius); padding: 0.65rem 0.85rem; word-break: break-all; color: var(--green); }.code-block { font-family: 'SF Mono', Consolas, monospace; font-size: 0.8rem; background: rgba(0,0,0,0.3); border: 1px solid var(--border-glass); border-radius: var(--radius); padding: 1rem; overflow-x: auto; line-height: 1.6; }/* Toast */#toast { position: fixed; bottom: 2rem; left: 50%; transform: translateX(-50%); background: var(--surface-glass-strong); backdrop-filter: blur(20px); border: 1px solid var(--border-glass-strong); border-radius: 99px; padding: 0.75rem 1.5rem; font-size: 0.85rem; z-index: 9999; opacity: 0; transition: opacity 0.2s, transform 0.2s; pointer-events: none; max-width: 90%; text-align: center; }#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }/* Empty state */.empty { text-align: center; padding: 3rem 1rem; color: var(--muted); font-size: 0.9rem; }2 unmodified lines.section { display: none; }.section.active { display: block; }/* Callout */.callout { background: var(--accent-dim); border: 1px solid rgba(124,106,247,0.3); border-radius: var(--radius); padding: 1rem; font-size: 0.85rem; color: var(--text); margin-bottom: 1.25rem; line-height: 1.6; }.callout code { background: rgba(0,0,0,0.3); border-radius: 4px; padding: 2px 6px; font-family: monospace; font-size: 0.8rem; color: var(--accent); }/* Mobile optimizations */@media (max-width: 768px) {.sidebar { transform: translateX(-100%); box-shadow: 5px 0 30px rgba(0,0,0,0.5); }.sidebar.open { transform: translateX(0); }.main { margin-left: 0; padding: 1rem; padding-bottom: 3rem; }.mobile-header { display: flex; }.form-grid { grid-template-columns: 1fr; }.field.span2 { grid-column: span 1; }.page-title { font-size: 1.25rem; }.stats { gap: 0.5rem; }.stat-val { font-size: 1.25rem; }.card { padding: 1rem; }th, td { padding: 0.65rem 0.5rem; font-size: 0.8rem; }.hide-mobile { display: none; }}/* Prevent body scroll when menu open */body.menu-open { overflow: hidden; }.menu-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 99; }body.menu-open .menu-overlay { display: block; }</style></head><body>6 unmodified lines<label>Admin Key</label><input type="password" id="login-key" placeholder="sk-admin-..." /></div><button class="btn btn-primary" style="width:100%; justify-content:center;" onclick="doLogin()">Sign in</button><div id="login-err" style="color:var(--red);font-size:0.8rem;margin-top:0.75rem;display:none">Invalid key.</div></div></div><div class="app" id="app-shell" style="display:none"><div class="menu-overlay" onclick="toggleMenu()"></div><aside class="sidebar" id="sidebar"><div class="logo"><div class="logo-text">RyzGateway</div><div class="logo-sub">BYOK AI Router</div></div><div class="nav-section">Overview</div><div class="nav-item active" onclick="nav('overview', this)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>Dashboard</div><div class="nav-section">Configure</div><div class="nav-item" onclick="nav('providers', this)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>Providers</div><div class="nav-item" onclick="nav('pools', this)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>Model Pools</div><div class="nav-item" onclick="nav('keys', this)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>API Keys</div><div class="nav-section">Reference</div><div class="nav-item" onclick="nav('docs', this)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>Usage Docs</div></aside><main class="main"><div class="mobile-header"><button class="menu-btn" onclick="toggleMenu()"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg></button><div style="font-weight:600">RyzGateway</div><div style="width:40px"></div></div><!-- OVERVIEW --><div class="section active" id="sec-overview">3 unmodified lines</div><div class="stats" id="stats-row"><div class="stat"><div class="stat-val" id="stat-providers">—</div><div class="stat-label">Providers</div></div><div class="stat"><div class="stat-val" id="stat-pools">—</div><div class="stat-label">Pools</div></div><div class="stat"><div class="stat-val" id="stat-keys">—</div><div class="stat-label">Keys</div></div></div><div class="card"><div style="font-size:0.9rem;font-weight:600;margin-bottom:1rem">Provider health</div><div id="health-list"><div class="empty">No providers configured</div></div></div></div>9 unmodified lines<button class="btn" onclick="loadProviders()">↺ Refresh</button></div><div class="callout"><strong>Provider ID</strong> is auto-generated from the name and used in model routing. Use <code>provider-id/exact-model-name</code> to route directly. Click <strong>Fetch Models</strong> on a provider to auto-import available models.</div><div class="card"><div class="table-wrap"><table><thead><tr><th>Provider</th><th class="hide-mobile">Base URL</th><th>Rate limit</th><th>Models</th><th>Status</th><th></th></tr></thead><tbody id="providers-tbody"><tr><td colspan="6"><div class="empty">Loading...</div></td></tr></tbody></table>30 unmodified lines<div class="card"><div class="table-wrap"><table><thead><tr><th>Name</th><th>Key</th><th class="hide-mobile">Created</th><th></th></tr></thead><tbody id="keys-tbody"><tr><td colspan="4"><div class="empty">Loading...</div></td></tr></tbody></table></div>7 unmodified lines<div class="page-sub">How to use RyzGateway in your apps</div></div><div class="card" style="margin-bottom:1rem"><div style="font-size:0.9rem;font-weight:600;margin-bottom:0.75rem">Base URL</div><div class="key-display" id="base-url-display"></div><div style="font-size:0.8rem;color:var(--muted);margin-top:0.5rem">Point any OpenAI-compatible client at this URL.</div></div><div class="card" style="margin-bottom:1rem"><div style="font-size:0.9rem;font-weight:600;margin-bottom:0.75rem">Model name formats</div><div style="font-size:0.85rem;line-height:1.8;color:var(--text)"><div style="margin-bottom:0.75rem"><span style="font-family:monospace;background:rgba(0,0,0,0.3);padding:3px 8px;border-radius:6px;color:var(--accent)">provider-id/exact-model-name</span> — Direct passthrough.</div><div><span style="font-family:monospace;background:rgba(0,0,0,0.3);padding:3px 8px;border-radius:6px;color:var(--green)">pool-name</span> — Pool routing.</div></div></div><div class="card" style="margin-bottom:1rem"><div style="font-size:0.9rem;font-weight:600;margin-bottom:0.75rem">Example: Python (openai SDK)</div><pre class="code-block"><code>import openaiclient = openai.OpenAI(base_url="<span id="doc-base-url"></span>",13 unmodified lines)</code></pre></div><div class="card"><div style="font-size:0.9rem;font-weight:600;margin-bottom:0.75rem">Rate limit types</div><table style="font-size:0.85rem"><thead><tr><th>Type</th><th>Meaning</th><th>Window</th></tr></thead><tbody><tr><td><span class="badge badge-purple">RPM</span></td><td>Requests per minute</td><td>60s</td></tr><tr><td><span class="badge badge-green">RPS</span></td><td>Requests per second</td><td>1s</td></tr><tr><td><span class="badge badge-amber">RPD</span></td><td>Requests per day</td><td>86400s</td></tr><tr><td><span class="badge badge-gray">None</span></td><td>No limit tracked</td><td>—</td></tr></tbody></table>43 unmodified linesconst opts = { method, headers: { 'Authorization': 'Bearer ' + ADMIN_KEY, 'Content-Type': 'application/json' } };if (body) opts.body = JSON.stringify(body);const r = await fetch(path, opts);if (!r.ok) {const t = await r.text();let msg = t;try { const j = JSON.parse(t); msg = j.detail || t; } catch(e) {}throw new Error(msg);}return r.json();}// ── Navigation ───────────────────────────────────────────────────────────────function toggleMenu() {document.body.classList.toggle('menu-open');document.getElementById('sidebar').classList.toggle('open');}function nav(id, el) {document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));document.getElementById('sec-' + id).classList.add('active');if(el) el.classList.add('active');if (window.innerWidth <= 768) toggleMenu();if (id === 'overview') loadOverview();if (id === 'providers') loadProviders();if (id === 'pools') loadPools();12 unmodified linesfunction toast(msg, type='ok') {const el = document.getElementById('toast');el.textContent = msg;el.style.color = type === 'err' ? 'var(--red)' : 'var(--text)';el.style.borderColor = type === 'err' ? 'var(--red-dim)' : 'var(--border-glass-strong)';el.classList.add('show');clearTimeout(toastTimer);toastTimer = setTimeout(() => el.classList.remove('show'), 3500);}// ── Modal ────────────────────────────────────────────────────────────────────21 unmodified lines? `<span class="badge badge-amber"><span class="dot"></span>${cds.length} cooling</span>`: `<span class="badge badge-green"><span class="dot"></span>OK</span>`;const rl = p.rate_type !== 'none' ? `<span class="badge badge-gray">${p.rate_limit} ${p.rate_type.toUpperCase()}</span>` : '<span class="badge badge-gray">no limit</span>';return `<div style="display:flex;align-items:center;gap:12px;padding:0.75rem 0;border-bottom:1px solid var(--border-glass)"><div style="flex:1;font-size:0.9rem;font-weight:500">${p.name} <span style="color:var(--muted);font-weight:400;font-size:0.8rem">${p.id}</span></div><div>${rl}</div><div>${status}</div></div>`;11 unmodified linesconst rl = p.rate_type !== 'none' ? `${p.rate_limit} ${p.rate_type.toUpperCase()}` : '—';const cds = Object.entries(p.active_cooldowns || {});const statusBadge = cds.length? `<span class="badge badge-amber"><span class="dot"></span>${cds.length}</span>`: `<span class="badge badge-green"><span class="dot"></span>OK</span>`;const models = (p.known_models || []).length;return `<tr><td><div style="font-weight:500">${p.name}</div><div style="font-size:0.75rem;color:var(--muted)">${p.id}</div></td><td class="hide-mobile" style="font-size:0.8rem;color:var(--muted);max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${p.base_url}</td><td style="font-size:0.8rem">${rl}</td><td style="font-size:0.8rem">${models}</td><td>${statusBadge}</td><td style="text-align:right; white-space:nowrap;"><button class="btn btn-sm" onclick='fetchModels("${p.id}")' title="Auto-fetch models from provider">Fetch</button><button class="btn btn-sm" onclick='editProvider(${JSON.stringify(p)})'>Edit</button><button class="btn btn-sm btn-danger" onclick="deleteProvider('${p.id}','${p.name}')">Del</button></td>2 unmodified lines} catch(e) { console.error(e); }}async function fetchModels(pid) {toast('Fetching models...');try {const res = await api('POST', `/admin/providers/${pid}/fetch-models`);toast(`Successfully imported ${res.fetched_count} models!`);loadProviders();loadOverview();} catch(e) {toast('Fetch failed: ' + e.message, 'err');}}function openProviderModal(existing) {const p = existing || {};const isEdit = !!p.id;14 unmodified lines<div class="field"><label>Rate limit value</label><input id="p-rlimit" type="number" value="${p.rate_limit||0}" min="0"></div><div class="field span2"><label>Known models (comma-separated)</label><input id="p-models" value="${(p.known_models||[]).join(', ')}" placeholder="gpt-4o, gpt-4o-mini, ..."></div><div class="field span2"><label>Notes</label><textarea id="p-notes">${p.notes||''}</textarea></div></div><div class="callout" style="margin-top:1rem;font-size:0.8rem">Tip: Save the provider first, then click "Fetch" on the providers list to automatically pull and populate the models list.</div>`;const footer = `<button class="btn" onclick="closeModal()">Cancel</button>46 unmodified linesconst stratBadge = {round_robin:'<span class="badge badge-purple">Round robin</span>', priority:'<span class="badge badge-amber">Priority</span>', weighted:'<span class="badge badge-green">Weighted</span>'}[pool.strategy] || '';const members = (pool.members||[]).map(m => {const avail = m.available;const cd = m.cooldown_remaining > 0 ? ` (${m.cooldown_remaining}s)` : '';const badge = avail ? '<span class="badge badge-green"><span class="dot"></span>OK</span>' : `<span class="badge badge-red"><span class="dot"></span>RL${cd}</span>`;return `<div class="member-item"><div class="member-label"><strong>${m.provider_id}</strong> / ${m.model_name}</div>${m.weight !== undefined ? `<span class="member-badge">w:${m.weight}</span>` : ''}1 unmodified line</div>`;}).join('');return `<div class="card" style="margin-bottom:1rem"><div style="display:flex;align-items:center;gap:10px;margin-bottom:1rem;flex-wrap:wrap"><div style="flex:1;min-width: 150px"><div style="font-weight:600;font-size:1rem">${pool.name}</div><div style="font-size:0.8rem;color:var(--muted)">${pool.id}</div></div>${stratBadge}<button class="btn btn-sm" onclick='openPoolModal(${JSON.stringify(pool)})'>Edit</button><button class="btn btn-sm btn-danger" onclick="deletePool('${pool.id}','${pool.name}')">Del</button></div>${members || '<div style="color:var(--muted);font-size:0.85rem">No members</div>'}</div>`;}).join('');} catch(e) { console.error(e); }21 unmodified lines</select></div></div><div style="font-size:0.8rem;color:var(--muted);font-weight:500;margin-bottom:0.5rem">MEMBERS</div><div id="pool-members-list"></div><div style="background:rgba(0,0,0,0.2);border:1px solid var(--border-glass);border-radius:var(--radius);padding:1rem;margin-top:0.5rem"><div style="font-size:0.8rem;color:var(--muted);margin-bottom:0.75rem">Add member</div><div class="form-grid" style="grid-template-columns: 1fr 1.5fr auto; gap:8px;align-items:end"><div class="field"><label>Provider</label><select id="new-m-prov">${provOpts||'<option>No providers</option>'}</select></div><div class="field"><label>Model name</label><input id="new-m-model" placeholder="google/gemini-flash-1.5"></div><div class="field"><label>Wgt</label><input id="new-m-weight" type="number" value="1" min="1" style="width:70px"></div></div><button class="btn btn-sm" style="margin-top:10px;width:100%;justify-content:center" onclick="addPoolMember()">+ Add Member</button></div>`;const footer = `7 unmodified linesfunction renderPoolMembers() {const el = document.getElementById('pool-members-list');if (!el) return;if (!poolMembers.length) { el.innerHTML = '<div style="color:var(--muted);font-size:0.85rem;margin-bottom:0.5rem">No members yet</div>'; return; }el.innerHTML = poolMembers.map((m, i) =>`<div class="member-item"><div class="member-label">${m.provider_id} / ${m.model_name}</div>52 unmodified lines`<tr><td style="font-weight:500">${k.name}</td><td><div class="key-display">${k.key}</div></td><td class="hide-mobile" style="color:var(--muted);font-size:0.8rem">${new Date(k.created_at*1000).toLocaleDateString()}</td><td style="text-align:right"><button class="btn btn-sm btn-danger" onclick="deleteKey('${k.id}','${k.name}')">Delete</button></td></tr>`).join('');11 unmodified linesconst name = document.getElementById('key-name').value.trim();if (!name) { toast('Name required', 'err'); return; }try {await api('POST', '/admin/api-keys', { name });closeModal();toast('Key created');loadKeys();
app.py+295-149