File size: 1,865 Bytes
07c2907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json, os
from pathlib import Path

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel


def _load_env():
    p = Path(__file__).resolve().parent.parent / ".env"
    if p.exists():
        for line in p.read_text().splitlines():
            if "=" in line and not line.startswith("#"):
                k, v = line.split("=", 1)
                os.environ.setdefault(k.strip(), v.strip())


_load_env()
from . import agent, audit, tools  # noqa: E402  (after env load)

app = FastAPI(title="StatAgent")
REPLAY = Path(__file__).resolve().parent.parent / "examples" / "replay.json"


class Q(BaseModel):
    question: str
    session: str = "demo"


class D(BaseModel):
    approve: bool


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/ask")
def ask(q: Q):
    try:
        return agent.ask(q.question, q.session)
    except Exception as e:
        # graceful fallback: replay a saved run when the LLM is unavailable / rate-limited
        if REPLAY.exists():
            runs = json.loads(REPLAY.read_text())
            pick = next((r for r in runs if r["question"].lower()[:25] == q.question.lower()[:25]), runs[0])
            return {**pick, "answer": "*[Replayed saved example - live LLM unavailable]*\n\n" + pick["answer"]}
        raise HTTPException(503, str(e))


@app.get("/datasets")
def datasets():
    return {k: {"desc": v, "columns": list(tools.load(k).columns)} for k, v in tools.list_datasets().items()}


@app.get("/series/{dataset}/{column}")
def series(dataset: str, column: str):
    return tools.series(dataset, column)


@app.get("/proposals")
def proposals():
    return audit.proposals()


@app.post("/proposals/{pid}")
def decide(pid: int, d: D):
    audit.decide(pid, d.approve)
    return {"ok": True}


@app.get("/audit")
def get_audit(n: int = 100):
    return audit.entries(n)