Spaces:
Sleeping
Sleeping
Fix space container runtime and alignment [app.py]
Browse files
app.py
CHANGED
|
@@ -1,542 +1,35 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
# ---------------------------------------------------------------------------
|
| 38 |
-
# App + singletons
|
| 39 |
-
# ---------------------------------------------------------------------------
|
| 40 |
-
|
| 41 |
-
HARVEST_DIR = Path(os.environ.get("HARVEST_DIR", str(DEFAULT_HARVEST_DIR)))
|
| 42 |
-
FRONTEND_DIST = Path(__file__).resolve().parent / "frontend" / "dist"
|
| 43 |
-
|
| 44 |
-
#: Root directory under which `POST /v1/system/commit` is allowed to write.
|
| 45 |
-
#: Defaults to the repository root; override with ``COMMIT_ROOT`` for tighter
|
| 46 |
-
#: sandboxing in production. The endpoint refuses to write anywhere outside
|
| 47 |
-
#: this resolved root.
|
| 48 |
-
COMMIT_ROOT = Path(
|
| 49 |
-
os.environ.get("COMMIT_ROOT", str(Path(__file__).resolve().parent))
|
| 50 |
-
).resolve()
|
| 51 |
-
|
| 52 |
-
#: Origins permitted to call the API from a browser. The Vercel command face
|
| 53 |
-
#: ("Citadel Nexus") is the canonical UI; additional origins can be supplied
|
| 54 |
-
#: via the ``CORS_ALLOW_ORIGINS`` env var (comma-separated).
|
| 55 |
-
_DEFAULT_CORS_ORIGINS = (
|
| 56 |
-
"https://citadel-nexus-private.vercel.app",
|
| 57 |
-
)
|
| 58 |
-
_extra_origins = [
|
| 59 |
-
o.strip()
|
| 60 |
-
for o in os.environ.get("CORS_ALLOW_ORIGINS", "").split(",")
|
| 61 |
-
if o.strip()
|
| 62 |
-
]
|
| 63 |
-
CORS_ALLOW_ORIGINS = list(dict.fromkeys((*_DEFAULT_CORS_ORIGINS, *_extra_origins)))
|
| 64 |
-
|
| 65 |
-
app = FastAPI(
|
| 66 |
-
title="TIA Document Ingestion & Semantic Search API",
|
| 67 |
-
version="1.1.0",
|
| 68 |
-
description=(
|
| 69 |
-
"Enterprise-grade RAG API. Ingests markdown/text archives from a local "
|
| 70 |
-
"volume and serves semantic search and multi-persona responses over them."
|
| 71 |
-
),
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
# CORS — the Vercel "Citadel Nexus" command face is the canonical browser
|
| 75 |
-
# client. We use an explicit allow-list (no wildcard) so credentialed requests
|
| 76 |
-
# from the HUD work and arbitrary origins are rejected at the edge.
|
| 77 |
-
app.add_middleware(
|
| 78 |
-
CORSMiddleware,
|
| 79 |
-
allow_origins=CORS_ALLOW_ORIGINS,
|
| 80 |
-
allow_credentials=True,
|
| 81 |
-
allow_methods=["GET", "POST", "OPTIONS"],
|
| 82 |
-
allow_headers=["Authorization", "Content-Type"],
|
| 83 |
-
max_age=600,
|
| 84 |
-
)
|
| 85 |
-
|
| 86 |
-
_rag_engine = RAGEngine(harvest_dir=HARVEST_DIR)
|
| 87 |
-
_persona_engine: PersonaEngine | None = None
|
| 88 |
-
_PROCESS_START_TS = time.time()
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def get_rag_engine() -> RAGEngine:
|
| 92 |
-
"""Dependency accessor so tests can override the engine instance."""
|
| 93 |
-
return _rag_engine
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def get_persona_engine() -> PersonaEngine:
|
| 97 |
-
"""Lazy-build the persona engine so RAG-only deployments stay light."""
|
| 98 |
-
global _persona_engine
|
| 99 |
-
if _persona_engine is None:
|
| 100 |
-
_persona_engine = PersonaEngine(rag_engine=_rag_engine)
|
| 101 |
-
return _persona_engine
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
# ---------------------------------------------------------------------------
|
| 105 |
-
# Schemas
|
| 106 |
-
# ---------------------------------------------------------------------------
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
class HealthResponse(BaseModel):
|
| 110 |
-
status: str = "ok"
|
| 111 |
-
service: str = "tia-rag-api"
|
| 112 |
-
version: str = "1.1.0"
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
class IngestResponse(BaseModel):
|
| 116 |
-
status: str
|
| 117 |
-
files_ingested: int
|
| 118 |
-
chunks_indexed: int
|
| 119 |
-
harvest_dir: str
|
| 120 |
-
backend: str | None = None
|
| 121 |
-
faiss_error: str | None = None
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
class QueryRequest(BaseModel):
|
| 125 |
-
query: str = Field(..., min_length=1, max_length=2048)
|
| 126 |
-
top_k: int = Field(5, ge=1, le=50)
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
class QueryHit(BaseModel):
|
| 130 |
-
source: str
|
| 131 |
-
index: int
|
| 132 |
-
text: str
|
| 133 |
-
score: float
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class QueryResponse(BaseModel):
|
| 137 |
-
query: str
|
| 138 |
-
results: list[QueryHit]
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
class PersonaSummary(BaseModel):
|
| 142 |
-
name: str
|
| 143 |
-
title: str
|
| 144 |
-
temperature: float
|
| 145 |
-
tools: list[str]
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
class PersonaListResponse(BaseModel):
|
| 149 |
-
personas: list[PersonaSummary]
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
class PersonaAskRequest(BaseModel):
|
| 153 |
-
query: str = Field(..., min_length=1, max_length=4096)
|
| 154 |
-
top_k: int = Field(5, ge=1, le=20)
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
class PersonaAskResponse(BaseModel):
|
| 158 |
-
persona: str
|
| 159 |
-
query: str
|
| 160 |
-
answer: str
|
| 161 |
-
citations: list[QueryHit]
|
| 162 |
-
model: str
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
class SystemHealthResponse(BaseModel):
|
| 166 |
-
status: str
|
| 167 |
-
service: str = "tia-rag-api"
|
| 168 |
-
version: str = "1.1.0"
|
| 169 |
-
git_sha: str | None = None
|
| 170 |
-
rag: dict
|
| 171 |
-
personas: dict
|
| 172 |
-
harvest_dir: str
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
class SystemStatusResponse(BaseModel):
|
| 176 |
-
"""Lightweight telemetry packet for the Librarian / Vercel HUD.
|
| 177 |
-
|
| 178 |
-
Intentionally unauthenticated and side-effect free so it can be polled
|
| 179 |
-
cheaply by ``.github/workflows/librarian_healthcheck.yml`` and the HUD.
|
| 180 |
-
"""
|
| 181 |
-
|
| 182 |
-
repo: str = "DJ-Goana-Coding/Oppo-TIA"
|
| 183 |
-
version: str = "1.1.0"
|
| 184 |
-
commit: str | None = None
|
| 185 |
-
index_built: bool = False
|
| 186 |
-
personas: list[str] = Field(default_factory=list)
|
| 187 |
-
uptime_seconds: float = 0.0
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
class CommitRequest(BaseModel):
|
| 191 |
-
"""Payload for ``POST /v1/system/commit``.
|
| 192 |
-
|
| 193 |
-
A relative POSIX-style ``path`` (e.g. ``data/notes/today.md``) and the
|
| 194 |
-
UTF-8 ``content`` to write. ``path`` is validated and resolved against
|
| 195 |
-
:data:`COMMIT_ROOT`; any attempt to escape that root (``..``, absolute
|
| 196 |
-
paths, drive letters, NUL bytes, symlink escapes) is rejected.
|
| 197 |
-
"""
|
| 198 |
-
|
| 199 |
-
path: str = Field(..., min_length=1, max_length=1024)
|
| 200 |
-
content: str = Field(..., max_length=5 * 1024 * 1024) # 5 MiB cap
|
| 201 |
-
create_dirs: bool = Field(
|
| 202 |
-
default=True,
|
| 203 |
-
description="If true, create missing parent directories under COMMIT_ROOT.",
|
| 204 |
-
)
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
class CommitResponse(BaseModel):
|
| 208 |
-
status: str
|
| 209 |
-
path: str
|
| 210 |
-
bytes_written: int
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
# ---------------------------------------------------------------------------
|
| 214 |
-
# Endpoints — system
|
| 215 |
-
# ---------------------------------------------------------------------------
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
@app.get("/health", response_model=HealthResponse, tags=["system"])
|
| 219 |
-
def health() -> HealthResponse:
|
| 220 |
-
"""Unauthenticated liveness probe."""
|
| 221 |
-
return HealthResponse()
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
def _git_sha() -> str | None:
|
| 225 |
-
try:
|
| 226 |
-
sha = subprocess.check_output(
|
| 227 |
-
["git", "rev-parse", "--short", "HEAD"],
|
| 228 |
-
stderr=subprocess.DEVNULL,
|
| 229 |
-
cwd=str(Path(__file__).resolve().parent),
|
| 230 |
-
timeout=2,
|
| 231 |
-
)
|
| 232 |
-
return sha.decode().strip() or None
|
| 233 |
-
except Exception:
|
| 234 |
-
return None
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
@app.get(
|
| 238 |
-
"/v1/system/health",
|
| 239 |
-
response_model=SystemHealthResponse,
|
| 240 |
-
tags=["system"],
|
| 241 |
-
)
|
| 242 |
-
def system_health(
|
| 243 |
-
engine: RAGEngine = Depends(get_rag_engine),
|
| 244 |
-
) -> SystemHealthResponse:
|
| 245 |
-
"""Deep health endpoint exposing engine + persona registry state."""
|
| 246 |
-
registry = get_registry()
|
| 247 |
-
return SystemHealthResponse(
|
| 248 |
-
status="ok",
|
| 249 |
-
git_sha=_git_sha(),
|
| 250 |
-
rag=engine.stats(),
|
| 251 |
-
personas={
|
| 252 |
-
"count": len(registry.list()),
|
| 253 |
-
"names": registry.names(),
|
| 254 |
-
},
|
| 255 |
-
harvest_dir=str(HARVEST_DIR),
|
| 256 |
-
)
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
@app.get(
|
| 260 |
-
"/v1/system/status",
|
| 261 |
-
response_model=SystemStatusResponse,
|
| 262 |
-
tags=["system"],
|
| 263 |
-
)
|
| 264 |
-
def system_status(
|
| 265 |
-
engine: RAGEngine = Depends(get_rag_engine),
|
| 266 |
-
) -> SystemStatusResponse:
|
| 267 |
-
"""Librarian-friendly telemetry packet.
|
| 268 |
-
|
| 269 |
-
Unauthenticated by design: this endpoint is polled by the Librarian Hub
|
| 270 |
-
healthcheck workflow and the Vercel HUD. It exposes only non-sensitive
|
| 271 |
-
operational signals — no secrets, no document content.
|
| 272 |
-
|
| 273 |
-
``uptime_seconds`` is per-process: under multi-worker servers
|
| 274 |
-
(e.g. gunicorn) each worker reports its own uptime, not the deployment's.
|
| 275 |
-
"""
|
| 276 |
-
try:
|
| 277 |
-
rag_stats = engine.stats()
|
| 278 |
-
except Exception: # pragma: no cover - defensive
|
| 279 |
-
rag_stats = {}
|
| 280 |
-
index_built = bool(rag_stats.get("chunks_indexed") or rag_stats.get("files_ingested"))
|
| 281 |
-
|
| 282 |
-
try:
|
| 283 |
-
registry = get_registry()
|
| 284 |
-
persona_names = list(registry.names())
|
| 285 |
-
except Exception: # pragma: no cover - defensive
|
| 286 |
-
persona_names = []
|
| 287 |
-
|
| 288 |
-
return SystemStatusResponse(
|
| 289 |
-
commit=_git_sha(),
|
| 290 |
-
index_built=index_built,
|
| 291 |
-
personas=persona_names,
|
| 292 |
-
uptime_seconds=round(time.time() - _PROCESS_START_TS, 3),
|
| 293 |
-
)
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
def _safe_commit_path(rel_path: str) -> Path:
|
| 297 |
-
"""Resolve ``rel_path`` under :data:`COMMIT_ROOT`, refusing escapes.
|
| 298 |
-
|
| 299 |
-
Defences (path-traversal hardening for ``POST /v1/system/commit``):
|
| 300 |
-
|
| 301 |
-
* Reject NUL bytes and empty segments.
|
| 302 |
-
* Reject absolute paths and Windows drive specifiers.
|
| 303 |
-
* Reject any segment equal to ``..``.
|
| 304 |
-
* Resolve the final path and require it to be inside ``COMMIT_ROOT``
|
| 305 |
-
(covers symlinks pointing outside the root).
|
| 306 |
-
"""
|
| 307 |
-
if not rel_path or "\x00" in rel_path:
|
| 308 |
-
raise HTTPException(
|
| 309 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 310 |
-
detail="Invalid path",
|
| 311 |
-
)
|
| 312 |
-
|
| 313 |
-
# Normalise separators but reject anything that already looks absolute.
|
| 314 |
-
candidate = PurePosixPath(rel_path.replace("\\", "/"))
|
| 315 |
-
# ``rel_path[1] == ":"`` catches Windows drive letters like ``C:\foo`` /
|
| 316 |
-
# ``C:/foo`` which ``PurePosixPath`` does not classify as absolute.
|
| 317 |
-
if candidate.is_absolute() or (len(rel_path) >= 2 and rel_path[1] == ":"):
|
| 318 |
-
raise HTTPException(
|
| 319 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 320 |
-
detail="Path must be relative to COMMIT_ROOT",
|
| 321 |
-
)
|
| 322 |
-
if any(part in ("", "..") for part in candidate.parts):
|
| 323 |
-
raise HTTPException(
|
| 324 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 325 |
-
detail="Path traversal segments are not allowed",
|
| 326 |
-
)
|
| 327 |
-
|
| 328 |
-
resolved = (COMMIT_ROOT / Path(*candidate.parts)).resolve()
|
| 329 |
-
try:
|
| 330 |
-
resolved.relative_to(COMMIT_ROOT)
|
| 331 |
-
except ValueError as exc:
|
| 332 |
-
raise HTTPException(
|
| 333 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 334 |
-
detail="Resolved path escapes COMMIT_ROOT",
|
| 335 |
-
) from exc
|
| 336 |
-
return resolved
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
@app.post(
|
| 340 |
-
"/v1/system/commit",
|
| 341 |
-
response_model=CommitResponse,
|
| 342 |
-
tags=["system"],
|
| 343 |
-
status_code=status.HTTP_200_OK,
|
| 344 |
-
)
|
| 345 |
-
def system_commit(
|
| 346 |
-
payload: CommitRequest,
|
| 347 |
-
_principal: Principal = Depends(require_scopes("system:commit")),
|
| 348 |
-
) -> CommitResponse:
|
| 349 |
-
"""Write ``payload.content`` to ``payload.path`` under :data:`COMMIT_ROOT`.
|
| 350 |
-
|
| 351 |
-
This is the Vercel HUD command pipeline entrypoint. It is intentionally
|
| 352 |
-
minimal: a JWT-authenticated, scope-gated, path-traversal-hardened file
|
| 353 |
-
write. Git/commit orchestration (signing, branching, push) is delegated
|
| 354 |
-
to the deployment layer and is out of scope here.
|
| 355 |
-
"""
|
| 356 |
-
target = _safe_commit_path(payload.path)
|
| 357 |
-
if payload.create_dirs:
|
| 358 |
-
target.parent.mkdir(parents=True, exist_ok=True)
|
| 359 |
-
elif not target.parent.is_dir():
|
| 360 |
-
raise HTTPException(
|
| 361 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 362 |
-
detail="Parent directory does not exist",
|
| 363 |
-
)
|
| 364 |
-
|
| 365 |
-
# Re-validate the parent directory after any mkdir so a symlink planted
|
| 366 |
-
# between _safe_commit_path() and the write cannot redirect us out of
|
| 367 |
-
# COMMIT_ROOT (TOCTOU defence). Then open the file with O_NOFOLLOW so
|
| 368 |
-
# the final path component itself cannot be a symlink to elsewhere.
|
| 369 |
-
try:
|
| 370 |
-
target.parent.resolve(strict=True).relative_to(COMMIT_ROOT)
|
| 371 |
-
except (ValueError, FileNotFoundError) as exc:
|
| 372 |
-
raise HTTPException(
|
| 373 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 374 |
-
detail="Resolved parent escapes COMMIT_ROOT",
|
| 375 |
-
) from exc
|
| 376 |
-
|
| 377 |
-
data = payload.content.encode("utf-8")
|
| 378 |
-
if len(data) > 5 * 1024 * 1024:
|
| 379 |
-
raise HTTPException(
|
| 380 |
-
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
|
| 381 |
-
detail="Encoded content exceeds 5 MiB limit",
|
| 382 |
-
)
|
| 383 |
-
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
|
| 384 |
-
try:
|
| 385 |
-
fd = os.open(str(target), flags, 0o644)
|
| 386 |
-
except OSError as exc:
|
| 387 |
-
# ELOOP from O_NOFOLLOW means the target is (or became) a symlink.
|
| 388 |
-
raise HTTPException(
|
| 389 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 390 |
-
detail=f"Refused to write target: {exc.strerror or exc}",
|
| 391 |
-
) from exc
|
| 392 |
-
try:
|
| 393 |
-
with os.fdopen(fd, "wb") as fh:
|
| 394 |
-
fh.write(data)
|
| 395 |
-
except Exception:
|
| 396 |
-
try:
|
| 397 |
-
os.close(fd)
|
| 398 |
-
except OSError:
|
| 399 |
-
pass
|
| 400 |
-
raise
|
| 401 |
-
return CommitResponse(
|
| 402 |
-
status="ok",
|
| 403 |
-
path=str(target.relative_to(COMMIT_ROOT)),
|
| 404 |
-
bytes_written=len(data),
|
| 405 |
-
)
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
# ---------------------------------------------------------------------------
|
| 409 |
-
# Endpoints — harvest
|
| 410 |
-
# ---------------------------------------------------------------------------
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
@app.post(
|
| 414 |
-
"/v1/harvest/ingest",
|
| 415 |
-
response_model=IngestResponse,
|
| 416 |
-
tags=["harvest"],
|
| 417 |
-
status_code=status.HTTP_200_OK,
|
| 418 |
-
)
|
| 419 |
-
def ingest(
|
| 420 |
-
_principal: Principal = Depends(require_scopes("harvest:write")),
|
| 421 |
-
engine: RAGEngine = Depends(get_rag_engine),
|
| 422 |
-
) -> IngestResponse:
|
| 423 |
-
"""Rebuild the RAG index from the harvest directory."""
|
| 424 |
-
try:
|
| 425 |
-
stats = engine.ingest()
|
| 426 |
-
except Exception as exc: # pragma: no cover - defensive
|
| 427 |
-
raise HTTPException(
|
| 428 |
-
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 429 |
-
detail=f"Ingestion failed: {exc}",
|
| 430 |
-
) from exc
|
| 431 |
-
return IngestResponse(status="ok", **stats)
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
@app.post(
|
| 435 |
-
"/v1/harvest/query",
|
| 436 |
-
response_model=QueryResponse,
|
| 437 |
-
tags=["harvest"],
|
| 438 |
-
)
|
| 439 |
-
def query(
|
| 440 |
-
payload: QueryRequest,
|
| 441 |
-
_principal: Principal = Depends(require_scopes("harvest:read")),
|
| 442 |
-
engine: RAGEngine = Depends(get_rag_engine),
|
| 443 |
-
) -> QueryResponse:
|
| 444 |
-
"""Return the top matching chunks for ``query``."""
|
| 445 |
-
hits = engine.search(payload.query, top_k=payload.top_k)
|
| 446 |
-
return QueryResponse(
|
| 447 |
-
query=payload.query,
|
| 448 |
-
results=[QueryHit(**hit) for hit in hits],
|
| 449 |
-
)
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
# ---------------------------------------------------------------------------
|
| 453 |
-
# Endpoints — personas
|
| 454 |
-
# ---------------------------------------------------------------------------
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
@app.get(
|
| 458 |
-
"/v1/personas",
|
| 459 |
-
response_model=PersonaListResponse,
|
| 460 |
-
tags=["personas"],
|
| 461 |
-
)
|
| 462 |
-
def list_personas(
|
| 463 |
-
_principal: Principal = Depends(require_scopes("harvest:read")),
|
| 464 |
-
) -> PersonaListResponse:
|
| 465 |
-
"""List configured personas with their public configuration."""
|
| 466 |
-
registry = get_registry()
|
| 467 |
-
return PersonaListResponse(
|
| 468 |
-
personas=[
|
| 469 |
-
PersonaSummary(
|
| 470 |
-
name=p.name,
|
| 471 |
-
title=p.title,
|
| 472 |
-
temperature=p.temperature,
|
| 473 |
-
tools=list(p.tools),
|
| 474 |
-
)
|
| 475 |
-
for p in registry.list()
|
| 476 |
-
]
|
| 477 |
-
)
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
@app.post(
|
| 481 |
-
"/v1/personas/{name}/ask",
|
| 482 |
-
response_model=PersonaAskResponse,
|
| 483 |
-
tags=["personas"],
|
| 484 |
-
)
|
| 485 |
-
def ask_persona(
|
| 486 |
-
name: str,
|
| 487 |
-
payload: PersonaAskRequest,
|
| 488 |
-
_principal: Principal = Depends(require_scopes("persona:invoke")),
|
| 489 |
-
engine: PersonaEngine = Depends(get_persona_engine),
|
| 490 |
-
) -> PersonaAskResponse:
|
| 491 |
-
"""Run RAG retrieval and answer using the named persona."""
|
| 492 |
-
try:
|
| 493 |
-
response = engine.respond(name, payload.query, top_k=payload.top_k)
|
| 494 |
-
except KeyError as exc:
|
| 495 |
-
raise HTTPException(
|
| 496 |
-
status_code=status.HTTP_404_NOT_FOUND,
|
| 497 |
-
detail=str(exc),
|
| 498 |
-
) from exc
|
| 499 |
-
except ValueError as exc:
|
| 500 |
-
raise HTTPException(
|
| 501 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 502 |
-
detail=str(exc),
|
| 503 |
-
) from exc
|
| 504 |
-
except Exception as exc: # pragma: no cover - defensive
|
| 505 |
-
raise HTTPException(
|
| 506 |
-
status_code=status.HTTP_502_BAD_GATEWAY,
|
| 507 |
-
detail=f"Persona LLM call failed: {exc}",
|
| 508 |
-
) from exc
|
| 509 |
-
return PersonaAskResponse(
|
| 510 |
-
persona=response.persona,
|
| 511 |
-
query=response.query,
|
| 512 |
-
answer=response.answer,
|
| 513 |
-
citations=[QueryHit(**c) for c in response.citations],
|
| 514 |
-
model=response.model,
|
| 515 |
-
)
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
# ---------------------------------------------------------------------------
|
| 519 |
-
# Static UI (mounted only when a built frontend is available)
|
| 520 |
-
# ---------------------------------------------------------------------------
|
| 521 |
-
|
| 522 |
-
if FRONTEND_DIST.is_dir():
|
| 523 |
-
app.mount(
|
| 524 |
-
"/ui",
|
| 525 |
-
StaticFiles(directory=str(FRONTEND_DIST), html=True),
|
| 526 |
-
name="ui",
|
| 527 |
-
)
|
| 528 |
-
|
| 529 |
-
@app.get("/", include_in_schema=False)
|
| 530 |
-
def _root_redirect() -> RedirectResponse: # pragma: no cover - trivial
|
| 531 |
-
return RedirectResponse(url="/ui/")
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
if __name__ == "__main__": # pragma: no cover
|
| 535 |
-
import uvicorn
|
| 536 |
-
|
| 537 |
-
uvicorn.run(
|
| 538 |
-
"app:app",
|
| 539 |
-
host=os.environ.get("HOST", "127.0.0.1"),
|
| 540 |
-
port=int(os.environ.get("PORT", "8000")),
|
| 541 |
-
reload=bool(os.environ.get("RELOAD")),
|
| 542 |
-
)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
|
| 5 |
+
app = FastAPI(
|
| 6 |
+
title="Oppo-TIA Sovereign Node Diode",
|
| 7 |
+
version="1.0.0",
|
| 8 |
+
description="Mobile edge worker bridge, Termux diode, and consciousness relay."
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
app.add_middleware(
|
| 12 |
+
CORSMiddleware,
|
| 13 |
+
allow_origins=["*"],
|
| 14 |
+
allow_credentials=True,
|
| 15 |
+
allow_methods=["*"],
|
| 16 |
+
allow_headers=["*"],
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
@app.get("/")
|
| 20 |
+
def root():
|
| 21 |
+
return {
|
| 22 |
+
"node": "Oppo-TIA Edge Node",
|
| 23 |
+
"status": "OMEGA-STAINLESS",
|
| 24 |
+
"resonance": "9293Hz",
|
| 25 |
+
"role": "Mobile Termux Node & Kiwix Diode"
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
@app.get("/health")
|
| 29 |
+
def health():
|
| 30 |
+
return {"status": "ONLINE", "node": "Oppo-TIA", "port": 7860}
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
import uvicorn
|
| 34 |
+
port = int(os.environ.get("PORT", 7860))
|
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