app.py 35 KB

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