"""Production SAEBase pages plus the existing read-only research API and MCP tools.""" from __future__ import annotations import sys from pathlib import Path from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles from gradio import Server ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT / "apps" / "research-lab")) from backend import api as research # noqa: E402 from fastapi import HTTPException # noqa: E402 import ablation # noqa: E402 import public_records # noqa: E402 SITE = ROOT / "site" app = Server(title="OpenSAE SAEBase") research.app.router.routes[:] = [ route for route in research.app.router.routes if getattr(route, "path", None) not in {"/", "/assets"} ] app.include_router(research.app.router) @app.get("/", include_in_schema=False) def homepage() -> FileResponse: return FileResponse(SITE / "index.html") def _bounds(limit: int, offset: int, max_limit: int) -> None: if type(limit) is not int or type(offset) is not int: raise ValueError("limit and offset must be integers") if not 1 <= limit <= max_limit or offset < 0 or offset > 100000: raise ValueError(f"limit must be 1..{max_limit} and offset must be nonnegative") def _envelope(tool: str, mode: str, status: str, result: dict, warning: str | None = None) -> dict: return { "schema_version": "1.0", "project": "saebase", "tool": tool, "status": status, "compute_mode": mode, "provenance": { "api": "apps/research-lab/backend/api.py", "evidence": "conf/coverage/stage_d_evidence", "protocol": "stage_d.population.v1", "gpu_inference": False, }, "warning": warning, "result": result, } @app.mcp.tool(name="list_sae_sites") @app.api(name="list_sae_sites", concurrency_limit=8) def list_sae_sites(model: str = "", sae: str = "", limit: int = 25, offset: int = 0) -> dict: """List verified historical SAE sites from the frozen research matrix.""" _bounds(limit, offset, 100) page = research.sites(model, sae, limit, offset) return _envelope("list_sae_sites", "historical_verified", "ok", page) @app.mcp.tool(name="get_site_results") @app.api(name="get_site_results", concurrency_limit=8) def get_site_results( model: str = "", metric: str = "", site_id: str = "", limit: int = 25, offset: int = 0 ) -> dict: """Return historical metric rows for verified sites, with protocol and evidence URL.""" _bounds(limit, offset, 200) page = research.results(model, metric, site_id, limit, offset) return _envelope("get_site_results", "historical_verified", "ok", page) @app.mcp.tool(name="validate_intervention") @app.api(name="validate_intervention", concurrency_limit=4) def validate_intervention( site_id: str, text: str, operation: str = "ablate", feature_ids: list[int] | None = None, strength: float = 1.0, max_new_tokens: int = 32, ) -> dict: """Validate an intervention request. This does not enqueue or run a model.""" spec = research.InterventionSpec( site_id=site_id, text=text, operation=operation, feature_ids=list(feature_ids or []), strength=strength, max_new_tokens=max_new_tokens, ) try: body = research.preflight(spec) except HTTPException as exc: return _envelope( "validate_intervention", "validation_only", "rejected", {"valid": False, "submitted": False, "ran_model": False, "detail": exc.detail}, ) return _envelope("validate_intervention", "validation_only", "blocked", body) def _public_envelope(tool: str, mode: str, status: str, result: dict, warning: str | None = None) -> dict: return { "schema_version": "1.0", "project": "saebase", "tool": tool, "status": status, "compute_mode": mode, "provenance": { "feature_atlas": "assets/features.json", "feature_schema": "opensae.feature_atlas.observed_last_token.v1", "lab_evidence": "lab-experiments/data/evidence.json", "lab_schema": "opensae.lab.evidence.v1", "stage_d_is_separate": True, }, "warning": warning, "result": result, } @app.mcp.tool(name="list_feature_atlas") @app.api(name="list_feature_atlas", concurrency_limit=8) def list_feature_atlas(model: str = "", q: str = "", limit: int = 25, offset: int = 0) -> dict: """List the published 14-feature atlas. This reads the public file and does not run a model.""" _bounds(limit, offset, 50) if not isinstance(model, str) or not isinstance(q, str): raise ValueError("model and q must be strings") return _public_envelope("list_feature_atlas", "historical_verified", "ok", { "summary": public_records.atlas_summary(), "page": public_records.list_features(model, q, limit, offset), }) @app.mcp.tool(name="get_feature_record") @app.api(name="get_feature_record", concurrency_limit=8) def get_feature_record(feature_id: str) -> dict: """Return one published feature and its recorded last-token ablations.""" if not isinstance(feature_id, str) or not feature_id.strip(): raise ValueError("feature_id must be a non-empty string") found = public_records.get_feature(feature_id) if found is None: return _public_envelope("get_feature_record", "unavailable", "unavailable", { "feature_id": feature_id, "reason": "Not one of the published atlas features", }) return _public_envelope("get_feature_record", "historical_verified", "ok", found) @app.mcp.tool(name="list_lab_records") @app.api(name="list_lab_records", concurrency_limit=8) def list_lab_records(kind: str = "effects", limit: int = 10, offset: int = 0) -> dict: """Read public lab evidence by protocol. Unreviewed prompt text is omitted.""" _bounds(limit, offset, 20) return _public_envelope("list_lab_records", "historical_verified", "ok", public_records.list_lab_records(kind, limit, offset)) def _ablation_duration(feature_id: str, prompt_sha256: str) -> int: return 300 try: import spaces except Exception: # noqa: BLE001 class _Spaces: def GPU(self, *args, **kwargs): def decorate(fn): return fn return decorate spaces = _Spaces() @app.mcp.tool(name="ablate_published_feature") @app.api(name="ablate_published_feature", concurrency_limit=1) @spaces.GPU(duration=_ablation_duration) def ablate_published_feature(feature_id: str, prompt_sha256: str) -> dict: """Ablate one deployed published feature on its recorded public prompt.""" try: body = ablation.ablate(feature_id, prompt_sha256) except ValueError as exc: return _public_envelope("ablate_published_feature", "unavailable", "blocked", { "feature_id": feature_id, "reason": str(exc), "inference": "not_run", }) mode = "live_gpu" if body["gpu_execution"] else "live_cpu" return _public_envelope("ablate_published_feature", mode, "ok", body) @app.get("/use-with-agents", include_in_schema=False) def agents_page() -> FileResponse: return FileResponse(ROOT / "use-with-agents.html") @app.get("/app.js", include_in_schema=False) def root_app_js() -> FileResponse: return FileResponse(SITE / "app.js") @app.get("/style.css", include_in_schema=False) def root_style() -> FileResponse: return FileResponse(SITE / "style.css") @app.get("/styles.css", include_in_schema=False) def root_styles() -> FileResponse: return FileResponse(SITE / "styles.css") app.mount("/assets", StaticFiles(directory=str(SITE / "assets")), name="assets") app.mount("/data", StaticFiles(directory=str(SITE / "data")), name="data") app.mount("/lab-experiments", StaticFiles(directory=str(SITE / "lab-experiments")), name="lab") if __name__ == "__main__": app.launch(mcp_server=True)