app.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. """
  2. app.py — FastAPI backend for tasplanning.report
  3. RAG pipeline:
  4. 1. Embed the user query via Ollama (nomic-embed-text)
  5. 2. Search Qdrant for the closest chunks, split by corpus/scope
  6. 3. Inject retrieved context into a structured prompt
  7. 4. Call Ollama (llama3.1:8b) and return the answer + source citations
  8. BYOK mode (context_only=True): skip step 4 and return the prompt so
  9. the browser can call its own LLM (Claude, GPT, Grok, local Ollama).
  10. Restart required after any change to this file:
  11. docker compose restart backend
  12. """
  13. import os, re, hmac, logging
  14. import json
  15. import requests
  16. import time
  17. logger = logging.getLogger(__name__)
  18. from typing import Optional, Literal, List, Tuple
  19. from fastapi import FastAPI, Query, HTTPException, Request
  20. from fastapi.middleware.cors import CORSMiddleware
  21. from fastapi.responses import StreamingResponse
  22. from slowapi.middleware import SlowAPIMiddleware
  23. from slowapi.errors import RateLimitExceeded
  24. from limiter import limiter
  25. from fastapi.responses import JSONResponse
  26. from pydantic import BaseModel
  27. from qdrant_client import QdrantClient
  28. from qdrant_client.http import models as qmodels
  29. from collections import Counter, defaultdict
  30. from datetime import datetime
  31. from telemetry import router as telemetry_router, db, ip_hash
  32. # ---------------------------------------------------------------------------
  33. # Environment
  34. # ---------------------------------------------------------------------------
  35. OLLAMA_URL = os.getenv("OLLAMA_URL", "http://192.168.8.73:11434")
  36. QDRANT_URL = os.getenv("QDRANT_URL", "http://localhost:6333")
  37. OLLAMA_KEEP_ALIVE = os.getenv("OLLAMA_KEEP_ALIVE", "-1") # -1 = keep loaded forever
  38. COLLECTION = os.getenv("QDRANT_COLLECTION", "planning_docs")
  39. EMBED_MODEL = os.getenv("EMBED_MODEL", "nomic-embed-text")
  40. CHAT_MODEL = os.getenv("CHAT_MODEL", "llama3.1:8b-instruct-q4_K_M")
  41. CORS_ORIGINS = [o.strip() for o in os.getenv("CORS_ORIGINS", "https://tasplanning.report").split(",") if o.strip()]
  42. # ---------------------------------------------------------------------------
  43. # Demo token gate (disabled by default)
  44. # Enable by setting DEMO_REQUIRE_TOKEN=1 and DEMO_TOKEN=<secret> in .env.
  45. # When enabled, every request to /ask and /admin/* must include:
  46. # Authorization: Bearer <DEMO_TOKEN>
  47. # ---------------------------------------------------------------------------
  48. DEMO_REQUIRE_TOKEN = os.getenv("DEMO_REQUIRE_TOKEN", "0") == "1"
  49. DEMO_TOKEN = os.getenv("DEMO_TOKEN", "")
  50. def _verify_demo_token_if_needed(request):
  51. if not DEMO_REQUIRE_TOKEN:
  52. return
  53. auth = request.headers.get("Authorization", "")
  54. parts = auth.split(" ", 1)
  55. if len(parts) != 2 or parts[0] != "Bearer":
  56. raise HTTPException(status_code=401, detail="Unauthorized")
  57. # compare_digest runs in constant time — prevents timing-based token guessing
  58. if not hmac.compare_digest(parts[1], DEMO_TOKEN):
  59. raise HTTPException(status_code=401, detail="Unauthorized")
  60. # ---------------------------------------------------------------------------
  61. # FastAPI app + CORS
  62. # ---------------------------------------------------------------------------
  63. app = FastAPI()
  64. # If CORS_ORIGINS is empty (shouldn't happen in production) fall back to a
  65. # wildcard with the tasplanning.report regex — credentials cannot be used
  66. # with wildcard origins so allow_credentials is gated on explicit origins.
  67. _origins = CORS_ORIGINS if CORS_ORIGINS else []
  68. _allow_all = len(_origins) == 0
  69. app.add_middleware(
  70. CORSMiddleware,
  71. allow_origins=_origins if not _allow_all else ["*"],
  72. allow_origin_regex=r"https://.*\.tasplanning\.report" if _allow_all else None,
  73. allow_credentials=not _allow_all, # credentials only when origins are explicit
  74. allow_methods=["GET", "POST", "OPTIONS"],
  75. allow_headers=["Content-Type", "Authorization", "X-TPR-SID"],
  76. expose_headers=["X-TPR-SID"],
  77. )
  78. qc = QdrantClient(url=QDRANT_URL)
  79. app.include_router(telemetry_router)
  80. # ---------------------------------------------------------------------------
  81. # Rate limiting (slowapi — in-memory, per IP)
  82. # Shared limiter instance lives in limiter.py to avoid circular imports with
  83. # telemetry.py, which also needs to decorate its own endpoints.
  84. # ---------------------------------------------------------------------------
  85. app.state.limiter = limiter # type: ignore
  86. app.add_middleware(SlowAPIMiddleware)
  87. @app.exception_handler(RateLimitExceeded)
  88. def ratelimit_handler(request, exc):
  89. return JSONResponse(status_code=429, content={"error":"rate_limited","detail":"Too many requests"})
  90. # ---------------------------------------------------------------------------
  91. # Feedback endpoint
  92. # Stores thumbs-up/down ratings alongside the query + answer for prompt tuning.
  93. # Fields are truncated before insert to keep the SQLite row size reasonable.
  94. # ---------------------------------------------------------------------------
  95. class FeedbackBody(BaseModel):
  96. verdict: str # "up" or "down"
  97. query: Optional[str] = None # the question that was asked
  98. answer: Optional[str] = None # the answer that was rated
  99. note: Optional[str] = None # optional free-text from thumbs-down
  100. sid: Optional[str] = None # session id from browser
  101. model: Optional[str] = None # which model answered
  102. scope: Optional[str] = None # which scope was used
  103. sources: Optional[list] = None # which sources were cited
  104. @app.post("/feedback")
  105. @limiter.limit("60/minute")
  106. def feedback(request: Request, body: FeedbackBody):
  107. if body.verdict not in ("up", "down"):
  108. raise HTTPException(status_code=422, detail="verdict must be 'up' or 'down'")
  109. ip = request.client.host if request.client else "0.0.0.0"
  110. sid = body.sid or request.headers.get("X-TPR-SID") or ""
  111. try:
  112. with db() as conn:
  113. conn.execute("""
  114. INSERT INTO feedback
  115. (ts, sid, ip_hash, verdict, query, answer, note, model, scope, sources_json)
  116. VALUES (?,?,?,?,?,?,?,?,?,?)
  117. """, (
  118. datetime.utcnow().isoformat(),
  119. sid, ip_hash(ip), body.verdict,
  120. _trunc(body.query or "", 2000, "feedback.query"),
  121. _trunc(body.answer or "", 8000, "feedback.answer"),
  122. _trunc(body.note or "", 1000, "feedback.note"),
  123. body.model or CHAT_MODEL,
  124. body.scope or "",
  125. _json_dumps(body.sources or []),
  126. ))
  127. conn.commit()
  128. except Exception as e:
  129. logger.exception("[feedback] telemetry insert failed")
  130. # Still return ok — don't surface DB errors to users
  131. return {"ok": True}
  132. # ---------------------------------------------------------------------------
  133. # Ollama helpers
  134. # ---------------------------------------------------------------------------
  135. def slug(s: Optional[str]) -> Optional[str]:
  136. """Normalise a council name to a URL-safe slug for Qdrant filter matching."""
  137. if not s:
  138. return None
  139. return re.sub(r'[^a-z0-9]+', '-', s.strip().lower()).strip('-') or None
  140. def ollama_embed(text: str) -> List[float]:
  141. """Call the Ollama embeddings API and return the float vector."""
  142. try:
  143. r = requests.post(
  144. f"{OLLAMA_URL}/api/embeddings",
  145. json={"model": EMBED_MODEL, "prompt": text},
  146. timeout=60
  147. )
  148. r.raise_for_status()
  149. except requests.Timeout:
  150. logger.error("Ollama embed timeout after 60s (url=%s model=%s)", OLLAMA_URL, EMBED_MODEL)
  151. raise HTTPException(status_code=503, detail="Embedding service timed out")
  152. except requests.ConnectionError:
  153. logger.error("Ollama embed connection error (url=%s)", OLLAMA_URL)
  154. raise HTTPException(status_code=503, detail="Embedding service unavailable")
  155. except requests.HTTPError as e:
  156. logger.error("Ollama embed HTTP %s: %s", e.response.status_code, e.response.text[:200])
  157. raise HTTPException(status_code=502, detail="Embedding service error")
  158. data = r.json()
  159. if "embedding" not in data:
  160. logger.error("Ollama embed unexpected response: %s", str(data)[:200])
  161. raise HTTPException(status_code=502, detail="Embedding service returned unexpected response")
  162. return data["embedding"]
  163. def ollama_chat(prompt: str) -> str:
  164. """
  165. Send a prompt to Ollama and return the generated text.
  166. keep_alive MUST be a top-level key — putting it inside options{} causes
  167. Ollama to silently ignore it and unload the model between requests.
  168. num_ctx is fixed at 6144. Changing it between requests forces Ollama to
  169. reload the model (KV cache is resized), adding ~3–5 s of cold-start latency.
  170. """
  171. try:
  172. r = requests.post(
  173. f"{OLLAMA_URL}/api/generate",
  174. json={
  175. "model": CHAT_MODEL,
  176. "prompt": prompt,
  177. "stream": False,
  178. "options": {
  179. "num_ctx": 6144, # was 8192,
  180. "num_predict": 512,
  181. "temperature": 0.2,
  182. "top_p": 0.9,
  183. "repeat_penalty": 1.1,
  184. },
  185. "keep_alive": -1, # keep model resident in VRAM between requests
  186. },
  187. timeout=180
  188. )
  189. r.raise_for_status()
  190. except requests.Timeout:
  191. logger.error("Ollama chat timeout after 180s (url=%s model=%s)", OLLAMA_URL, CHAT_MODEL)
  192. raise HTTPException(status_code=503, detail="LLM service timed out")
  193. except requests.ConnectionError:
  194. logger.error("Ollama chat connection error (url=%s)", OLLAMA_URL)
  195. raise HTTPException(status_code=503, detail="LLM service unavailable")
  196. except requests.HTTPError as e:
  197. logger.error("Ollama chat HTTP %s: %s", e.response.status_code, e.response.text[:200])
  198. raise HTTPException(status_code=502, detail="LLM service error")
  199. data = r.json()
  200. return data.get("response", "").strip()
  201. def _scroll_points(collection: str, qfilter=None, include_vector: bool=False, page_size: int=200):
  202. """
  203. Page through all points in a collection using Qdrant's scroll API.
  204. Used by /admin/export which needs vectors and supports arbitrary collections.
  205. For payload-only scans over the default collection use _scan_points instead.
  206. """
  207. offset = None
  208. while True:
  209. points, offset = qc.scroll(
  210. collection_name=collection,
  211. limit=page_size,
  212. with_payload=True,
  213. with_vectors=include_vector,
  214. offset=offset,
  215. scroll_filter=qfilter
  216. )
  217. if not points:
  218. break
  219. for pt in points:
  220. yield pt
  221. if offset is None:
  222. break
  223. # ---------------------------------------------------------------------------
  224. # Health + utility endpoints
  225. # ---------------------------------------------------------------------------
  226. @app.get("/readyz")
  227. def readyz():
  228. return {"ok": True}
  229. def _normalize(q: Optional[str]) -> str:
  230. """Collapse whitespace and lowercase — used for dedup tracking in ask_logs."""
  231. return re.sub(r"\s+", " ", (q or "").strip().lower())
  232. def _json_dumps(o) -> str:
  233. return json.dumps(o, ensure_ascii=False, separators=(",",":"))
  234. def _trunc(s: str, limit: int, field: str) -> str:
  235. """Truncate `s` to `limit` chars. Logs a warning if truncation occurs so
  236. data loss is visible in docker logs rather than silently discarded."""
  237. if len(s) > limit:
  238. logger.warning("telemetry field %r truncated from %d to %d chars", field, len(s), limit)
  239. return s[:limit]
  240. return s
  241. # ---- Councils list (prefers payload 'council', falls back to filename token) ----
  242. @app.get("/councils")
  243. def councils():
  244. councils = set()
  245. offset = None
  246. # sample up to ~5k points (50 * 100)
  247. for _ in range(50):
  248. points, offset = qc.scroll(
  249. collection_name=COLLECTION,
  250. limit=100,
  251. with_payload=True,
  252. offset=offset
  253. )
  254. for pt in points:
  255. p = pt.payload or {}
  256. token = (p.get("council") or "").strip().lower()
  257. if not token:
  258. sf = (p.get("source_file") or "").lower()
  259. if sf:
  260. token = sf.replace(".pdf", "").split("_")[0].split("-")[0]
  261. if token:
  262. councils.add(token)
  263. if offset is None:
  264. break
  265. return sorted(councils)
  266. # ---------------------------------------------------------------------------
  267. # Qdrant filter builders
  268. # _mv — exact MatchValue (keyword field, case-sensitive)
  269. # _mt — MatchText (full-text / substring match)
  270. # ---------------------------------------------------------------------------
  271. def _mv(key: str, value: str) -> qmodels.FieldCondition:
  272. return qmodels.FieldCondition(key=key, match=qmodels.MatchValue(value=value))
  273. def _mt(key: str, text: str) -> qmodels.FieldCondition:
  274. return qmodels.FieldCondition(key=key, match=qmodels.MatchText(text=text))
  275. def filter_tps() -> qmodels.Filter:
  276. """TPS only, exact match on corpus."""
  277. return qmodels.Filter(must=[_mv("corpus", "tps")])
  278. def filter_lps(council: str) -> qmodels.Filter:
  279. """
  280. LPS for a specific council (slug), exact match on both fields.
  281. """
  282. cslug = slug(council) or council.lower()
  283. return qmodels.Filter(must=[_mv("corpus", "lps"), _mv("council", cslug)])
  284. def filter_ncc() -> qmodels.Filter:
  285. return qmodels.Filter(must=[_mv("corpus", "ncc")])
  286. def filter_as() -> qmodels.Filter:
  287. return qmodels.Filter(must=[_mv("corpus", "as")])
  288. def with_source_contains(flt: Optional[qmodels.Filter], source_contains: Optional[str]) -> qmodels.Filter:
  289. """AND an additional source_file substring condition onto an existing filter."""
  290. if not source_contains:
  291. return flt
  292. add = _mt("source_file", source_contains)
  293. if flt:
  294. # preserve existing must/should/must_not and AND the filename condition
  295. must = list(getattr(flt, "must", []) or [])
  296. must.append(add)
  297. return qmodels.Filter(
  298. must=must,
  299. should=getattr(flt, "should", None),
  300. must_not=getattr(flt, "must_not", None),
  301. )
  302. return qmodels.Filter(must=[add])
  303. def q_search(vec: List[float], flt: Optional[qmodels.Filter], limit: int):
  304. """ANN vector search — returns up to `limit` scored points."""
  305. results = qc.query_points(
  306. collection_name=COLLECTION,
  307. query=vec,
  308. limit=max(1, limit),
  309. query_filter=flt,
  310. with_payload=True,
  311. )
  312. return results.points
  313. def render_blocks(hits) -> Tuple[List[str], List[dict]]:
  314. """Convert raw Qdrant hits into plain-text context blocks and source dicts."""
  315. blocks, sources = [], []
  316. for h in hits:
  317. p = h.payload or {}
  318. src = f"{p.get('source_file')} (p.{p.get('page')} chunk {p.get('chunk_index')})"
  319. snippet = p.get("text", "")
  320. blocks.append(f"Source: {src}\nText: {snippet}")
  321. sources.append({
  322. "source_file": p.get("source_file"),
  323. "page": p.get("page"),
  324. "chunk_index": p.get("chunk_index"),
  325. "score": h.score
  326. })
  327. return blocks, sources
  328. def combine_context(sections: List[Tuple[str, List[str]]]) -> str:
  329. """Join all section blocks into a single context string for the prompt."""
  330. out = []
  331. for heading, blocks in sections:
  332. if not blocks:
  333. continue
  334. out.append(f"=== {heading} ===")
  335. out.extend(blocks)
  336. return "\n\n".join(out) if out else "No context found."
  337. def _scan_points(qfilter: Optional[qmodels.Filter] = None, max_pages: int = 10000, page_size: int = 200):
  338. """
  339. Iterate through ALL points in the default collection (payload only, no vectors).
  340. Used by /admin/stats, /admin/files, /admin/sample.
  341. For the current dataset size this is fine. If the collection grows very large,
  342. switch to a pre-aggregated summary stored in a separate Qdrant collection or
  343. a background job that writes counts to SQLite.
  344. """
  345. offset = None
  346. pages = 0
  347. while pages < max_pages:
  348. points, offset = qc.scroll(
  349. collection_name=COLLECTION,
  350. limit=page_size,
  351. with_payload=True,
  352. offset=offset,
  353. scroll_filter=qfilter
  354. )
  355. if not points:
  356. break
  357. for pt in points:
  358. yield pt
  359. pages += 1
  360. if offset is None:
  361. break
  362. # ---------------------------------------------------------------------------
  363. # Admin endpoints — require DEMO_TOKEN when DEMO_REQUIRE_TOKEN=1
  364. # All endpoints are rate-limited; /export is tighter (streams full DB).
  365. # ---------------------------------------------------------------------------
  366. @app.get("/admin/stats")
  367. @limiter.limit("30/minute")
  368. def admin_stats(request: Request, council: Optional[str] = None, corpus: Optional[str] = None):
  369. _verify_demo_token_if_needed(request)
  370. must = []
  371. if council:
  372. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  373. if corpus:
  374. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  375. qfilter = qmodels.Filter(must=must) if must else None
  376. corp = Counter()
  377. councils = Counter()
  378. total = 0
  379. for pt in _scan_points(qfilter=qfilter):
  380. p = pt.payload or {}
  381. corp[(p.get("corpus") or "").lower()] += 1
  382. if p.get("council"):
  383. councils[(p.get("council") or "").lower()] += 1
  384. total += 1
  385. return {
  386. "collection": COLLECTION,
  387. "total_points": total,
  388. "by_corpus": dict(corp),
  389. "by_council": dict(councils),
  390. "note": "Counts are points (chunks), not documents.",
  391. }
  392. @app.get("/admin/files")
  393. @limiter.limit("30/minute")
  394. def admin_files(request: Request, council: Optional[str] = None, corpus: Optional[str] = None, contains: Optional[str] = None, limit: int = 200):
  395. _verify_demo_token_if_needed(request)
  396. must = []
  397. if council:
  398. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  399. if corpus:
  400. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  401. if contains:
  402. must.append(qmodels.FieldCondition(key="source_file", match=qmodels.MatchText(text=contains)))
  403. qfilter = qmodels.Filter(must=must) if must else None
  404. files = defaultdict(lambda: {"points": 0, "corpus": None, "council": None, "pages": set()})
  405. for pt in _scan_points(qfilter=qfilter):
  406. p = pt.payload or {}
  407. f = (p.get("source_file") or "").strip()
  408. if not f:
  409. continue
  410. rec = files[f]
  411. rec["points"] += 1
  412. rec["corpus"] = rec["corpus"] or p.get("corpus")
  413. rec["council"] = rec["council"] or p.get("council")
  414. if p.get("page") is not None:
  415. rec["pages"].add(p["page"])
  416. # shape for output
  417. out = []
  418. for f, rec in files.items():
  419. out.append({
  420. "source_file": f,
  421. "corpus": rec["corpus"],
  422. "council": rec["council"],
  423. "points": rec["points"],
  424. "page_count_est": len(rec["pages"]) if rec["pages"] else None,
  425. })
  426. # sort by points desc, limit
  427. out.sort(key=lambda x: x["points"], reverse=True)
  428. return out[:max(1, limit)]
  429. @app.get("/admin/sample")
  430. @limiter.limit("30/minute")
  431. def admin_sample(request: Request, council: Optional[str] = None, corpus: Optional[str] = None, n: int = 5):
  432. _verify_demo_token_if_needed(request)
  433. must = []
  434. if council:
  435. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  436. if corpus:
  437. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  438. qfilter = qmodels.Filter(must=must) if must else None
  439. samples = []
  440. for pt in _scan_points(qfilter=qfilter):
  441. p = pt.payload or {}
  442. txt = (p.get("text") or "").strip()
  443. if not txt:
  444. continue
  445. samples.append({
  446. "source_file": p.get("source_file"),
  447. "corpus": p.get("corpus"),
  448. "council": p.get("council"),
  449. "page": p.get("page"),
  450. "chunk_index": p.get("chunk_index"),
  451. "preview": (txt[:400] + "…") if len(txt) > 400 else txt
  452. })
  453. if len(samples) >= max(1, n):
  454. break
  455. return samples
  456. @app.get("/admin/export")
  457. @limiter.limit("5/minute")
  458. def admin_export(
  459. request: Request,
  460. collection: str = COLLECTION,
  461. council: Optional[str] = None,
  462. corpus: Optional[str] = None,
  463. source_contains: Optional[str] = None,
  464. include_vector: bool = False,
  465. limit: Optional[int] = None
  466. ):
  467. _verify_demo_token_if_needed(request)
  468. must = []
  469. if council:
  470. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  471. if corpus:
  472. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  473. if source_contains:
  474. must.append(qmodels.FieldCondition(key="source_file", match=qmodels.MatchText(text=source_contains)))
  475. qfilter = qmodels.Filter(must=must) if must else None
  476. def gen():
  477. count = 0
  478. for pt in _scroll_points(collection, qfilter=qfilter, include_vector=include_vector):
  479. obj = {
  480. "id": str(getattr(pt, "id", None)),
  481. "payload": pt.payload or {},
  482. }
  483. if include_vector:
  484. obj["vector"] = pt.vector
  485. yield json.dumps(obj, ensure_ascii=False) + "\n"
  486. count += 1
  487. if limit and count >= limit:
  488. break
  489. filename = f'{collection}-{corpus or "all"}-{council or "all"}.ndjson'
  490. headers = {"Content-Disposition": f'attachment; filename="{filename}"'}
  491. return StreamingResponse(gen(), media_type="application/x-ndjson", headers=headers)
  492. # ---------------------------------------------------------------------------
  493. # Section-specific format guides
  494. # Each section_id maps to a tightly-scoped formatting instruction injected at
  495. # the end of the prompt. This steers the LLM output for structured report
  496. # sections without changing the core RAG prompt.
  497. # ---------------------------------------------------------------------------
  498. def _section_format_guide(section_id: Optional[str], section_title: str, ctx: dict) -> str:
  499. """
  500. Return strict, section-specific formatting guidance for the LLM.
  501. Keep these short, prescriptive, and impossible to ignore.
  502. """
  503. sid = (section_id or "").lower()
  504. # Utility bits from context
  505. zones = ctx.get("planning_zones") or []
  506. zone_label = ", ".join(zones) if zones else "the applicable zone"
  507. council_label = ctx.get("council") or ""
  508. # ---- ZONING (tables of clauses like your sample) ----
  509. if sid in {"zoning", "zoning-41", "zoning-42", "zoning-43", "zoning-44", "zoning-441", "zoning-442"}:
  510. return f"""
  511. FORMAT REQUIREMENTS (MANDATORY):
  512. - Produce a concise preface (≤ 2 sentences) naming {zone_label}.
  513. - Then include a Markdown table listing EACH visible clause found in CONTEXT that applies to the zone or LPS for **{council_label or 'the selected council'}**.
  514. - One row per subclause. If an A/P pair exists (e.g., A1 / P1), include both in the same row.
  515. - Columns (exact):
  516. | Clause | Topic | Acceptable Solution (A) | Performance Criteria (P) | Assessment | Source |
  517. - "Clause": the clause number (e.g., "12.3.1 A1" or "DOR-S1.7.1").
  518. - "Topic": short label extracted from the clause heading.
  519. - "Acceptable Solution (A)" and "Performance Criteria (P)": quote briefly—no more than 1–2 lines each.
  520. - "Assessment": state clearly whether the proposal meets A, or relies on P. If unknown from CONTEXT, write "TBC".
  521. - "Source": filename + page (from CONTEXT).
  522. - Only include clauses actually present in CONTEXT; NEVER invent clause numbers or text.
  523. - After the table, add a one-paragraph summary noting any items assessed as TBC or non-compliant.
  524. """.strip()
  525. # ---- Codes overview list/table (optional future) ----
  526. if sid.startswith("code-"):
  527. return """
  528. FORMAT REQUIREMENTS:
  529. - Start with one sentence stating which Code and why it is triggered.
  530. - Then provide a short checklist or table of the relevant sub-clauses (A vs P), with Source for each.
  531. - Keep to 150–250 words + table.
  532. """.strip()
  533. # ---- Permit Overview (concise triggers) ----
  534. if sid == "permit-overview":
  535. return """
  536. FORMAT REQUIREMENTS:
  537. - Produce 3 blocks with headings:
  538. 1) "Project Context" – 3–5 bullet points (site, proposal, zone).
  539. 2) "Applicable Provisions" – bullets grouping TPS SPP, LPS (selected council), and triggered Codes.
  540. 3) "Assessment Path" – bullet list of key clauses to assess next.
  541. - Cite specific clause numbers ONLY if present in CONTEXT (include Source).
  542. """.strip()
  543. # ---- Default (no special formatting) ----
  544. return """
  545. FORMAT REQUIREMENTS:
  546. - Use concise Markdown with short paragraphs and bullets as needed.
  547. - Cite briefly (filename + page) when quoting a control.
  548. """.strip()
  549. # ---------------------------------------------------------------------------
  550. # /ask — core RAG endpoint
  551. # ---------------------------------------------------------------------------
  552. class AskBody(BaseModel):
  553. # accept multiple keys from different frontends
  554. query: Optional[str] = None
  555. question: Optional[str] = None
  556. q: Optional[str] = None
  557. prompt: Optional[str] = None
  558. top_k: int = 10
  559. council: Optional[str] = None
  560. include_ncc: bool = False
  561. include_standards: bool = False
  562. source_contains: Optional[str] = None
  563. scope: Literal['state_plus_local','local_only','state_only','any'] = 'state_plus_local'
  564. section_id: Optional[str] = None
  565. # BYOK mode: return context blocks without calling Ollama.
  566. # The browser then calls its own LLM with the returned context + prompt.
  567. context_only: bool = False
  568. def _allowed(p: dict, scope: str, cslug: Optional[str]) -> bool:
  569. """
  570. Secondary guardrail applied after the Qdrant vector search.
  571. Qdrant filters are the primary gate; this catches any edge-case leakage
  572. (e.g. MatchText returning a partial match across corpora).
  573. """
  574. corp = (p.get("corpus") or "").lower()
  575. council = (p.get("council") or "").lower()
  576. if scope == "local_only":
  577. return corp == "lps" and cslug and council == cslug
  578. if scope == "state_only":
  579. return corp == "tps"
  580. if scope == "state_plus_local":
  581. return corp == "tps" or (corp == "lps" and cslug and council == cslug)
  582. return True
  583. def do_ask(
  584. query: str,
  585. top_k: int = 10,
  586. council: Optional[str] = None,
  587. include_ncc: bool = False,
  588. include_standards: bool = False,
  589. source_contains: Optional[str] = None,
  590. scope: str = "state_plus_local",
  591. section_id: Optional[str] = None,
  592. context_only: bool = False,
  593. ):
  594. top_k = max(1, min(top_k, 30)) # clamp: at least 1, at most 30
  595. vec = ollama_embed(query)
  596. cslug = slug(council) if council else None
  597. # Build the list of (section_heading, qdrant_filter) pairs based on scope.
  598. # Each pair is searched independently so we can control the chunk budget
  599. # per corpus — avoids TPS drowning out LPS results or vice versa.
  600. scopes: List[Tuple[str, qmodels.Filter]] = []
  601. if scope in ("state_only", "state_plus_local", "any"):
  602. scopes.append(("Tasmanian Planning Scheme (SPP)", filter_tps()))
  603. if scope in ("local_only", "state_plus_local", "any") and cslug:
  604. scopes.append((f"Local Provisions Schedule — {cslug}", filter_lps(cslug)))
  605. if include_ncc:
  606. scopes.append(("National Construction Code (NCC)", filter_ncc()))
  607. if include_standards:
  608. scopes.append(("Australian Standards (AS)", filter_as()))
  609. # Apply additional filename filter if requested (AND)
  610. scopes = [(name, with_source_contains(flt, source_contains)) for name, flt in scopes]
  611. # Divide top_k across scopes: SPP and LPS each get ~1/3, the remainder
  612. # is split evenly across any extra corpora (NCC, AS).
  613. per_spp = max(3, top_k // 3) if any(n.startswith("Tasmanian Planning Scheme") for n, _ in scopes) else 0
  614. per_lps = max(3, top_k // 3) if any(n.startswith("Local Provisions Schedule") for n, _ in scopes) else 0
  615. remaining = max(1, top_k - (per_spp + per_lps))
  616. extra_scopes = sum(1 for n, _ in scopes if not (n.startswith("Tasmanian Planning Scheme") or n.startswith("Local Provisions Schedule")))
  617. per_extra = max(1, remaining // max(1, extra_scopes)) if extra_scopes else 0
  618. limits: List[int] = []
  619. for name, _ in scopes:
  620. if name.startswith("Tasmanian Planning Scheme"):
  621. limits.append(per_spp)
  622. elif name.startswith("Local Provisions Schedule"):
  623. limits.append(per_lps)
  624. else:
  625. limits.append(per_extra)
  626. sections: List[Tuple[str, List[str]]] = []
  627. all_sources: List[dict] = []
  628. for (name, flt), lim in zip(scopes, limits):
  629. if lim <= 0:
  630. continue
  631. hits = q_search(vec, flt, lim)
  632. # Guardrail: drop any hit that violates scope/council
  633. hits = [h for h in hits if _allowed(h.payload or {}, scope, cslug)]
  634. blocks, sources = render_blocks(hits)
  635. sections.append((name, blocks))
  636. all_sources.extend(sources)
  637. context = combine_context(sections)
  638. format_guide = _section_format_guide(
  639. section_id,
  640. section_title="(auto)",
  641. ctx={
  642. "council": council, # from do_ask parameter
  643. "planning_zones": [], # populate if you have zone detection
  644. }
  645. )
  646. prompt = f"""
  647. You are an expert Tasmanian planning and building compliance assistant with deep knowledge of the Tasmanian Planning Scheme structure.
  648. ## AUTHORITY ORDER — always apply in this sequence:
  649. 1. State Planning Provisions (SPP) — the statewide baseline. Cite clause numbers exactly.
  650. 2. Local Provisions Schedule (LPS) for the selected council — overrides SPP where it differs.
  651. 3. National Construction Code (NCC) — building controls only, keep separate from planning.
  652. 4. Australian Standards — only when directly referenced by a clause in CONTEXT.
  653. ## STRICT RULES:
  654. - Use ONLY information present in CONTEXT below. Never invent clause numbers, standards, or measurements.
  655. - If CONTEXT does not contain enough information to answer, say: "The provided context does not cover this — check the TPSO viewer directly at tpso.planning.tas.gov.au"
  656. - Every specific standard or requirement you state MUST include its source: (filename, p.N)
  657. - Quote clause text briefly (1–2 lines max) then explain in plain English.
  658. - Distinguish clearly between Acceptable Solutions (A) and Performance Criteria (P).
  659. ## OUTPUT FORMAT:
  660. - Use Markdown: ## for main headings, ### for sub-headings, **bold** for clause numbers.
  661. - For setbacks, parking rates, or multiple standards: use a Markdown table with columns: Clause | Requirement | A or P | Source
  662. - End every response with a ## Sources section listing each cited document and page.
  663. - Keep answers concise but complete — do not pad or repeat information.
  664. - Professional planning language; avoid informal phrasing.
  665. ## CONTEXT (retrieved from Tasmanian Planning Scheme documents):
  666. {context}
  667. {format_guide}
  668. ## QUESTION:
  669. {query}
  670. ## ANSWER:
  671. """.strip()
  672. # BYOK mode: skip Ollama and return the context + prompt so the
  673. # browser can call its own LLM provider (Claude, GPT, Grok, etc.)
  674. if context_only:
  675. return {
  676. "context_only": True,
  677. "context": context,
  678. "prompt": prompt,
  679. "sources": all_sources,
  680. # Include the raw section blocks so the browser can inspect them
  681. "sections": [
  682. {"heading": name, "blocks": blocks}
  683. for name, blocks in sections
  684. ]
  685. }
  686. answer = ollama_chat(prompt)
  687. return {"answer": answer, "sources": all_sources}
  688. @app.get("/ask")
  689. @limiter.limit("20/minute")
  690. def ask_get(
  691. request: Request,
  692. query: str = Query(..., description="User question"),
  693. top_k: int = 10,
  694. council: Optional[str] = None,
  695. include_ncc: bool = False,
  696. include_standards: bool = False,
  697. source_contains: Optional[str] = None,
  698. scope: str = "state_plus_local",
  699. section_id: Optional[str] = None,
  700. context_only: bool = False,
  701. ):
  702. _verify_demo_token_if_needed(request)
  703. started = time.perf_counter()
  704. out = do_ask(query, top_k, council, include_ncc, include_standards, source_contains, scope, section_id, context_only)
  705. latency_ms = int((time.perf_counter() - started) * 1000)
  706. # Telemetry insert — never allowed to break the response
  707. try:
  708. ip = request.client.host if request.client else "0.0.0.0"
  709. sid = request.headers.get("X-TPR-SID") or request.cookies.get("sid") or ""
  710. allow_tps = scope in ("state_only", "state_plus_local")
  711. topk = [{"id": f"{s.get('source_file')}#p{s.get('page')}", "score": s.get("score")} for s in (out.get("sources") or [])]
  712. with db() as conn:
  713. conn.execute("""
  714. INSERT INTO ask_logs
  715. (ts, sid, ip_hash, query, normalized, scope, allow_tps, latency_ms,
  716. model, ok, topk_json, tokens_in, tokens_out, answer)
  717. VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
  718. """, (
  719. datetime.utcnow().isoformat(),
  720. sid, ip_hash(ip), query, _normalize(query),
  721. scope, int(allow_tps),
  722. latency_ms, CHAT_MODEL, 1, _json_dumps(topk), 0, 0,
  723. _trunc(out.get("answer") or "", 8000, "ask_get.answer"),
  724. ))
  725. conn.commit()
  726. except Exception as e:
  727. logger.exception("[telemetry] ask_get insert failed")
  728. return out
  729. @app.post("/ask")
  730. @limiter.limit("20/minute")
  731. def ask_post(request: Request, body: AskBody):
  732. _verify_demo_token_if_needed(request)
  733. qtxt = (body.query or body.question or body.q or body.prompt or "").strip()
  734. if not qtxt:
  735. raise HTTPException(status_code=422, detail="Missing query/question")
  736. started = time.perf_counter()
  737. out = do_ask(
  738. query=qtxt,
  739. top_k=body.top_k,
  740. council=body.council,
  741. include_ncc=body.include_ncc,
  742. include_standards=body.include_standards,
  743. source_contains=body.source_contains,
  744. scope=body.scope,
  745. section_id=body.section_id,
  746. context_only=body.context_only,
  747. )
  748. latency_ms = int((time.perf_counter() - started) * 1000)
  749. # Telemetry insert — never allowed to break the response
  750. try:
  751. ip = request.client.host if request.client else "0.0.0.0"
  752. sid = request.headers.get("X-TPR-SID") or request.cookies.get("sid") or ""
  753. allow_tps = body.scope in ("state_only", "state_plus_local")
  754. topk = [{"id": f"{s.get('source_file')}#p{s.get('page')}", "score": s.get("score")} for s in (out.get("sources") or [])]
  755. with db() as conn:
  756. conn.execute("""
  757. INSERT INTO ask_logs
  758. (ts, sid, ip_hash, query, normalized, scope, allow_tps, latency_ms,
  759. model, ok, topk_json, tokens_in, tokens_out, answer)
  760. VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
  761. """, (
  762. datetime.utcnow().isoformat(),
  763. sid, ip_hash(ip), qtxt, _normalize(qtxt),
  764. body.scope, int(allow_tps),
  765. latency_ms, CHAT_MODEL, 1, _json_dumps(topk), 0, 0,
  766. _trunc(out.get("answer") or "", 8000, "ask_post.answer"),
  767. ))
  768. conn.commit()
  769. except Exception as e:
  770. logger.exception("[telemetry] ask_post insert failed")
  771. return out