Spaces:
Sleeping
feat(admin): KI-048 — /api/admin/profiles + /api/admin/performance
Browse filesBackend side of the admin-panel 3-tab restructure. Adds two endpoints
that feed the Profile + Visitor Log and Performance tabs (the LLM Chain
tab continues to use the existing /health, /probe, /chain, /usage).
GET /api/admin/profiles
→ wraps profile_store.list_profiles().
→ returns { profiles: [...], total: N, snapshot_ts: "..." }
→ empty list when data/profiles/ has no entries yet.
GET /api/admin/performance
→ composite from three sources:
• eval/results.json summary block (factual / citation / refusal,
by_brain, by_type, n_questions, ran_at, elapsed_seconds)
• latest 80-audit/full_<ts>/ (most-recently-modified) — merges the
launcher's summary.json with regex-parsed report.md (turns_total,
errors, refusals, p50/p95/p99 ms, brain_routing)
• data/llm_usage.jsonl tail (1000 lines) → per-role count,
success_rate, avg_latency_ms
→ each sub-block independently nullable so a missing data source
doesn't 500 the whole endpoint.
Both endpoints use the existing _check_admin guard (IP allowlist +
X-Admin-Password header, 404-on-fail to hide endpoint existence).
Verified by router introspection:
['/api/admin/health', '/api/admin/probe', '/api/admin/chain',
'/api/admin/chain', '/api/admin/usage', '/api/admin/profiles',
'/api/admin/performance']
Frontend HTML restructure (admin/llm-control.html with 3 tabs) is in
flight as a parallel agent and will commit separately.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- backend/admin.py +241 -0
|
@@ -24,7 +24,9 @@ from __future__ import annotations
|
|
| 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 |
|
|
@@ -268,3 +270,242 @@ async def admin_usage(
|
|
| 268 |
role: _stat_block_for_role(rows, role, chains[role], health_state)
|
| 269 |
for role in ("brain", "fast_brain", "judge")
|
| 270 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
import asyncio
|
| 25 |
import json
|
| 26 |
import os
|
| 27 |
+
import re
|
| 28 |
from collections import deque
|
| 29 |
+
from datetime import datetime, timezone
|
| 30 |
from pathlib import Path
|
| 31 |
from typing import Optional
|
| 32 |
|
|
|
|
| 270 |
role: _stat_block_for_role(rows, role, chains[role], health_state)
|
| 271 |
for role in ("brain", "fast_brain", "judge")
|
| 272 |
}
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
# ---------------------------------------------------------------------------
|
| 276 |
+
# /api/admin/profiles — list every named profile + summary
|
| 277 |
+
# ---------------------------------------------------------------------------
|
| 278 |
+
|
| 279 |
+
@router.get("/api/admin/profiles")
|
| 280 |
+
async def admin_profiles(
|
| 281 |
+
request: Request,
|
| 282 |
+
x_admin_password: Optional[str] = Header(default=None, alias="X-Admin-Password"),
|
| 283 |
+
):
|
| 284 |
+
"""List every named profile in the JSON store + lightweight summary.
|
| 285 |
+
|
| 286 |
+
Returned shape:
|
| 287 |
+
{
|
| 288 |
+
"profiles": [ {name_display, name_slug, first_seen, last_seen,
|
| 289 |
+
session_count, profile_complete_fields}, ... ],
|
| 290 |
+
"total": N,
|
| 291 |
+
"snapshot_ts": "2026-05-14T..."
|
| 292 |
+
}
|
| 293 |
+
"""
|
| 294 |
+
_check_admin(request, x_admin_password)
|
| 295 |
+
|
| 296 |
+
from backend import profile_store
|
| 297 |
+
profiles = profile_store.list_profiles()
|
| 298 |
+
return {
|
| 299 |
+
"profiles": profiles,
|
| 300 |
+
"total": len(profiles),
|
| 301 |
+
"snapshot_ts": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# ---------------------------------------------------------------------------
|
| 306 |
+
# /api/admin/performance — aggregated performance/quality metrics
|
| 307 |
+
# ---------------------------------------------------------------------------
|
| 308 |
+
|
| 309 |
+
_REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _read_eval_summary() -> Optional[dict]:
|
| 313 |
+
"""Return the `summary` block from eval/results.json — or None if missing."""
|
| 314 |
+
p = _REPO_ROOT / "eval" / "results.json"
|
| 315 |
+
if not p.exists():
|
| 316 |
+
return None
|
| 317 |
+
try:
|
| 318 |
+
raw = json.loads(p.read_text(encoding="utf-8"))
|
| 319 |
+
except Exception:
|
| 320 |
+
return None
|
| 321 |
+
summary = raw.get("summary") if isinstance(raw, dict) else None
|
| 322 |
+
if not isinstance(summary, dict):
|
| 323 |
+
return None
|
| 324 |
+
# Surface exactly the fields the admin panel cares about. Use .get so any
|
| 325 |
+
# missing field becomes None rather than raising.
|
| 326 |
+
return {
|
| 327 |
+
"ran_at": summary.get("ran_at"),
|
| 328 |
+
"elapsed_seconds": summary.get("elapsed_seconds"),
|
| 329 |
+
"n_questions": summary.get("n_questions"),
|
| 330 |
+
"factual_accuracy": summary.get("factual_accuracy"),
|
| 331 |
+
"citation_accuracy": summary.get("citation_accuracy"),
|
| 332 |
+
"refusal_precision": summary.get("refusal_precision"),
|
| 333 |
+
"by_brain": summary.get("by_brain") or {},
|
| 334 |
+
"by_type": summary.get("by_type") or {},
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _latest_audit_dir() -> Optional[Path]:
|
| 339 |
+
"""Return the most recently modified `80-audit/full_*` directory containing
|
| 340 |
+
a summary.json. Returns None if no such directory exists."""
|
| 341 |
+
audit_root = _REPO_ROOT / "80-audit"
|
| 342 |
+
if not audit_root.exists():
|
| 343 |
+
return None
|
| 344 |
+
candidates = [d for d in audit_root.glob("full_*") if (d / "summary.json").exists()]
|
| 345 |
+
if not candidates:
|
| 346 |
+
return None
|
| 347 |
+
candidates.sort(key=lambda d: d.stat().st_mtime, reverse=True)
|
| 348 |
+
return candidates[0]
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# Regex helpers for parsing report.md (analyze.py output). Anchored to the
|
| 352 |
+
# specific table rows so they're robust against table reordering.
|
| 353 |
+
_RE_REPORT_PERSONAS = re.compile(r"Personas completed \| \*\*(\d+)\*\* of (\d+)")
|
| 354 |
+
_RE_REPORT_TURNS = re.compile(r"Total turns executed \| \*\*(\d+)\*\*")
|
| 355 |
+
_RE_REPORT_ERRORS = re.compile(r"Errors \(HTTP / timeout / network\) \| (\d+)")
|
| 356 |
+
_RE_REPORT_REFUSALS = re.compile(r"Refusals \(blocked=true\) \| (\d+)")
|
| 357 |
+
_RE_REPORT_P50 = re.compile(r"Latency p50 \| (\d+)\s*ms")
|
| 358 |
+
_RE_REPORT_P95 = re.compile(r"Latency p95 \| (\d+)\s*ms")
|
| 359 |
+
_RE_REPORT_P99 = re.compile(r"Latency p99 \| (\d+)\s*ms")
|
| 360 |
+
_RE_BRAIN_ROW = re.compile(r"^\|\s*`([^`]+)`\s*\|\s*(\d+)\s*\|\s*$")
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _parse_brain_routing(report_text: str) -> dict[str, int]:
|
| 364 |
+
"""Extract the `## 2. Brain routing` table → {brain: turn_count}."""
|
| 365 |
+
out: dict[str, int] = {}
|
| 366 |
+
section_start = report_text.find("## 2. Brain routing")
|
| 367 |
+
if section_start < 0:
|
| 368 |
+
return out
|
| 369 |
+
section_end = report_text.find("## 3.", section_start)
|
| 370 |
+
if section_end < 0:
|
| 371 |
+
section_end = len(report_text)
|
| 372 |
+
for line in report_text[section_start:section_end].splitlines():
|
| 373 |
+
m = _RE_BRAIN_ROW.match(line)
|
| 374 |
+
if m:
|
| 375 |
+
try:
|
| 376 |
+
out[m.group(1)] = int(m.group(2))
|
| 377 |
+
except ValueError:
|
| 378 |
+
continue
|
| 379 |
+
return out
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _read_audit_summary() -> Optional[dict]:
|
| 383 |
+
"""Return aggregate metrics for the latest persona-audit run.
|
| 384 |
+
|
| 385 |
+
The on-disk summary.json is intentionally sparse (it's just the launcher's
|
| 386 |
+
config). The real metrics live in `report.md` (produced by
|
| 387 |
+
tools/audit/analyze.py). We parse it via regex — much cheaper than
|
| 388 |
+
re-walking 100+ transcript JSONs on every admin request.
|
| 389 |
+
|
| 390 |
+
Returns None if there is no audit run yet OR if the report.md hasn't been
|
| 391 |
+
generated (the launcher writes summary.json before analyze.py runs).
|
| 392 |
+
"""
|
| 393 |
+
run_dir = _latest_audit_dir()
|
| 394 |
+
if run_dir is None:
|
| 395 |
+
return None
|
| 396 |
+
|
| 397 |
+
summary_path = run_dir / "summary.json"
|
| 398 |
+
report_path = run_dir / "report.md"
|
| 399 |
+
try:
|
| 400 |
+
launcher_summary = json.loads(summary_path.read_text(encoding="utf-8"))
|
| 401 |
+
except Exception:
|
| 402 |
+
launcher_summary = {}
|
| 403 |
+
|
| 404 |
+
out: dict = {
|
| 405 |
+
"run_id": launcher_summary.get("run_id") or run_dir.name,
|
| 406 |
+
"personas_requested": launcher_summary.get("personas_requested"),
|
| 407 |
+
"personas_completed": launcher_summary.get("personas_completed"),
|
| 408 |
+
"elapsed_seconds": launcher_summary.get("elapsed_seconds"),
|
| 409 |
+
"turns_total": None,
|
| 410 |
+
"errors": None,
|
| 411 |
+
"refusals": None,
|
| 412 |
+
"p50_ms": None,
|
| 413 |
+
"p95_ms": None,
|
| 414 |
+
"p99_ms": None,
|
| 415 |
+
"brain_routing": {},
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
if not report_path.exists():
|
| 419 |
+
return out # launcher ran but analyze.py hasn't; surface what we have
|
| 420 |
+
|
| 421 |
+
try:
|
| 422 |
+
report_text = report_path.read_text(encoding="utf-8")
|
| 423 |
+
except Exception:
|
| 424 |
+
return out
|
| 425 |
+
|
| 426 |
+
def _int_match(rx: re.Pattern[str]) -> Optional[int]:
|
| 427 |
+
m = rx.search(report_text)
|
| 428 |
+
if not m:
|
| 429 |
+
return None
|
| 430 |
+
try:
|
| 431 |
+
return int(m.group(1))
|
| 432 |
+
except (ValueError, IndexError):
|
| 433 |
+
return None
|
| 434 |
+
|
| 435 |
+
# Pull values from report.md — overrides None defaults set above. Personas
|
| 436 |
+
# completed lives in BOTH summary.json and report.md; report.md wins because
|
| 437 |
+
# it reflects the actually-analyzed transcripts (in case the launcher
|
| 438 |
+
# claimed N but only M wrote transcripts).
|
| 439 |
+
p_match = _RE_REPORT_PERSONAS.search(report_text)
|
| 440 |
+
if p_match:
|
| 441 |
+
try:
|
| 442 |
+
out["personas_completed"] = int(p_match.group(1))
|
| 443 |
+
except ValueError:
|
| 444 |
+
pass
|
| 445 |
+
|
| 446 |
+
out["turns_total"] = _int_match(_RE_REPORT_TURNS)
|
| 447 |
+
out["errors"] = _int_match(_RE_REPORT_ERRORS)
|
| 448 |
+
out["refusals"] = _int_match(_RE_REPORT_REFUSALS)
|
| 449 |
+
out["p50_ms"] = _int_match(_RE_REPORT_P50)
|
| 450 |
+
out["p95_ms"] = _int_match(_RE_REPORT_P95)
|
| 451 |
+
out["p99_ms"] = _int_match(_RE_REPORT_P99)
|
| 452 |
+
out["brain_routing"] = _parse_brain_routing(report_text)
|
| 453 |
+
return out
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _read_usage_24h() -> Optional[dict]:
|
| 457 |
+
"""Compute {role: {count, success_rate, avg_latency_ms}} from the last
|
| 458 |
+
USAGE_TAIL_LINES entries of data/llm_usage.jsonl. Returns None if the
|
| 459 |
+
file is missing OR empty so the frontend can render an empty-state.
|
| 460 |
+
|
| 461 |
+
Note: "24h" in the field name is conventional — the actual window is the
|
| 462 |
+
last USAGE_TAIL_LINES rows (typically covers ≈24h of activity at current
|
| 463 |
+
traffic). Keeping the name aligns with the admin UI label.
|
| 464 |
+
"""
|
| 465 |
+
usage_path = _REPO_ROOT / "data" / "llm_usage.jsonl"
|
| 466 |
+
rows = _tail_jsonl(usage_path, USAGE_TAIL_LINES)
|
| 467 |
+
if not rows:
|
| 468 |
+
return None
|
| 469 |
+
|
| 470 |
+
agg: dict[str, dict] = {}
|
| 471 |
+
for r in rows:
|
| 472 |
+
role = r.get("role")
|
| 473 |
+
if not role:
|
| 474 |
+
continue
|
| 475 |
+
bucket = agg.setdefault(role, {"count": 0, "success_count": 0, "latency_sum": 0,
|
| 476 |
+
"latency_n": 0})
|
| 477 |
+
bucket["count"] += 1
|
| 478 |
+
if r.get("success") is True:
|
| 479 |
+
bucket["success_count"] += 1
|
| 480 |
+
lat = r.get("latency_ms")
|
| 481 |
+
if isinstance(lat, (int, float)):
|
| 482 |
+
bucket["latency_sum"] += int(lat)
|
| 483 |
+
bucket["latency_n"] += 1
|
| 484 |
+
|
| 485 |
+
out: dict[str, dict] = {}
|
| 486 |
+
for role, b in agg.items():
|
| 487 |
+
out[role] = {
|
| 488 |
+
"count": b["count"],
|
| 489 |
+
"success_rate": round(b["success_count"] / b["count"], 4) if b["count"] else 0.0,
|
| 490 |
+
"avg_latency_ms": int(b["latency_sum"] / b["latency_n"]) if b["latency_n"] else 0,
|
| 491 |
+
}
|
| 492 |
+
return out
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
@router.get("/api/admin/performance")
|
| 496 |
+
async def admin_performance(
|
| 497 |
+
request: Request,
|
| 498 |
+
x_admin_password: Optional[str] = Header(default=None, alias="X-Admin-Password"),
|
| 499 |
+
):
|
| 500 |
+
"""Aggregated performance/quality metrics for the admin Performance section.
|
| 501 |
+
|
| 502 |
+
All four sub-blocks are independently nullable — a missing eval/results.json
|
| 503 |
+
or absent audit run shouldn't 500 the endpoint.
|
| 504 |
+
"""
|
| 505 |
+
_check_admin(request, x_admin_password)
|
| 506 |
+
return {
|
| 507 |
+
"eval": _read_eval_summary(),
|
| 508 |
+
"audit": _read_audit_summary(),
|
| 509 |
+
"usage_24h": _read_usage_24h(),
|
| 510 |
+
"snapshot_ts": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 511 |
+
}
|