File size: 2,736 Bytes
613af80 | 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | """REST API (FastAPI) around the system.
Run: uvicorn src.api:app --reload then open http://127.0.0.1:8000/docs
Never send real patient data: notes and symptoms are sent to a free external LLM API.
"""
from __future__ import annotations
from functools import lru_cache
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from .agent import QuestionAgent
from .system import DISCLAIMER, DiagnosticSystem, build_system
app = FastAPI(title="Rare disease diagnosis support (research)", description=DISCLAIMER, version="0.1.0")
@lru_cache(maxsize=1)
def get_system() -> DiagnosticSystem:
return build_system()
def get_agent() -> QuestionAgent:
return QuestionAgent(get_system())
class DiagnoseRequest(BaseModel):
codes: list[str] = Field(default_factory=list, description="HPO codes, e.g. HP:0001250")
note: str | None = Field(None, description="Free-text note (invented or public cases only)")
class UpdateRequest(BaseModel):
codes: list[str]
llm_sets: list[list[str]]
confirmed: list[str] = Field(default_factory=list)
excluded: list[str] = Field(default_factory=list)
@app.get("/health")
def health() -> dict:
return {"status": "ok", "disclaimer": DISCLAIMER}
@app.post("/diagnose")
def diagnose(req: DiagnoseRequest) -> dict:
system, agent = get_system(), get_agent()
understood = system.understand_note(req.note) if req.note else []
codes = list(dict.fromkeys(req.codes + [c for c, _, _ in understood]))
unknown = [c for c in codes if c not in system.kb.terms]
if unknown:
raise HTTPException(422, f"Unknown HPO codes: {unknown}")
if not codes:
raise HTTPException(422, "Give HPO codes or a note.")
d = system.diagnose(codes)
questions = agent.choose_questions(d.ranking, codes)
return {
"symptoms": [{"code": c, "name": system.kb.term_name(c)} for c in codes],
"to_verify": [{"code": c, "name": n, "similarity": round(s, 2)} for c, n, s in understood
if s < system.settings.to_verify_threshold],
"metabolic_share": d.metabolic_share,
"ranking": system.explain(d.ranking, codes),
"questions": [{"code": q, "name": system.kb.term_name(q), "lab": system.kb.is_metabolic(q)} for q in questions],
"llm_sets": [sorted(s) for s in d.llm_sets],
"disclaimer": DISCLAIMER,
}
@app.post("/update")
def update(req: UpdateRequest) -> dict:
system, agent = get_system(), get_agent()
ranking = agent.update(req.codes, [set(s) for s in req.llm_sets], req.confirmed, req.excluded)
codes = list(dict.fromkeys(req.codes + req.confirmed))
return {"ranking": system.explain(ranking, codes), "disclaimer": DISCLAIMER}
|