app(1).py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. import os, re
  2. import json
  3. import requests
  4. import time
  5. from typing import Optional, Literal, List, Tuple
  6. from fastapi import FastAPI, Query, HTTPException, Request
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from fastapi.responses import StreamingResponse
  9. from slowapi.middleware import SlowAPIMiddleware
  10. from slowapi import Limiter
  11. from slowapi.util import get_remote_address
  12. from slowapi.errors import RateLimitExceeded
  13. from fastapi.responses import JSONResponse
  14. from pydantic import BaseModel
  15. from qdrant_client import QdrantClient
  16. from qdrant_client.http import models as qmodels
  17. from collections import Counter, defaultdict
  18. from datetime import datetime
  19. from telemetry import router as telemetry_router, db, ip_hash
  20. # ---- Environment ----
  21. OLLAMA_URL = os.getenv("OLLAMA_URL", "http://192.168.8.73:11434")
  22. QDRANT_URL = os.getenv("QDRANT_URL", "http://localhost:6333")
  23. OLLAMA_KEEP_ALIVE = -1
  24. COLLECTION = os.getenv("QDRANT_COLLECTION", "planning_docs")
  25. EMBED_MODEL = os.getenv("EMBED_MODEL", "nomic-embed-text")
  26. CHAT_MODEL = os.getenv("CHAT_MODEL", "llama3.1:8b")
  27. CORS_ORIGINS = [o.strip() for o in os.getenv("CORS_ORIGINS", "https://tasplanning.report").split(",") if o.strip()]
  28. # ---- DEMO TOKEN ----
  29. DEMO_REQUIRE_TOKEN = os.getenv("DEMO_REQUIRE_TOKEN", "0") == "1"
  30. DEMO_TOKEN = os.getenv("DEMO_TOKEN", "")
  31. def _verify_demo_token_if_needed(request):
  32. if not DEMO_REQUIRE_TOKEN:
  33. return
  34. auth = request.headers.get("Authorization", "")
  35. if not (auth.startswith("Bearer ") and auth.split(" ",1)[1] == DEMO_TOKEN):
  36. raise HTTPException(status_code=401, detail="Unauthorized")
  37. # ---- FAST API ----
  38. app = FastAPI()
  39. # Allowed origins — always include your frontend explicitly
  40. _origins = CORS_ORIGINS if CORS_ORIGINS else []
  41. _allow_all = len(_origins) == 0
  42. app.add_middleware(
  43. CORSMiddleware,
  44. allow_origins=_origins if not _allow_all else ["*"],
  45. allow_origin_regex=r"https://.*\.tasplanning\.report" if _allow_all else None,
  46. allow_credentials=not _allow_all, # credentials only when origins are explicit
  47. allow_methods=["GET", "POST", "OPTIONS"],
  48. allow_headers=["Content-Type", "Authorization", "X-TPR-SID"],
  49. expose_headers=["X-TPR-SID"],
  50. )
  51. qc = QdrantClient(url=QDRANT_URL)
  52. app.include_router(telemetry_router)
  53. # ---- SLOW API ----
  54. limiter = Limiter(key_func=get_remote_address)
  55. app.state.limiter = limiter # type: ignore
  56. app.add_middleware(SlowAPIMiddleware)
  57. @app.exception_handler(RateLimitExceeded)
  58. def ratelimit_handler(request, exc):
  59. return JSONResponse(status_code=429, content={"error":"rate_limited","detail":"Too many requests"})
  60. # ---- Ollama helpers ----
  61. def slug(s: Optional[str]) -> Optional[str]:
  62. if not s:
  63. return None
  64. return re.sub(r'[^a-z0-9]+', '-', s.strip().lower()).strip('-') or None
  65. def ollama_embed(text: str) -> List[float]:
  66. r = requests.post(
  67. f"{OLLAMA_URL}/api/embeddings",
  68. json={"model": EMBED_MODEL, "prompt": text},
  69. timeout=60
  70. )
  71. r.raise_for_status()
  72. data = r.json()
  73. if "embedding" not in data:
  74. raise RuntimeError(f"Ollama embeddings error: {data}")
  75. return data["embedding"]
  76. def ollama_chat(prompt: str) -> str:
  77. r = requests.post(
  78. f"{OLLAMA_URL}/api/generate",
  79. json={
  80. "model": CHAT_MODEL,
  81. "prompt": prompt,
  82. "stream": False,
  83. "options": {
  84. "num_ctx": 8192,
  85. "num_predict": 512,
  86. "temperature": 0.2,
  87. "top_p": 0.9,
  88. "repeat_penalty": 1.1,
  89. },
  90. "keep_alive": OLLAMA_KEEP_ALIVE # ← moved outside options, uses env var
  91. },
  92. timeout=180
  93. )
  94. r.raise_for_status()
  95. data = r.json()
  96. return data.get("response", "").strip()
  97. def _scroll_points(collection: str, qfilter=None, include_vector: bool=False, page_size: int=200):
  98. offset = None
  99. while True:
  100. points, offset = qc.scroll(
  101. collection_name=collection,
  102. limit=page_size,
  103. with_payload=True,
  104. with_vectors=include_vector,
  105. offset=offset,
  106. scroll_filter=qfilter
  107. )
  108. if not points:
  109. break
  110. for pt in points:
  111. yield pt
  112. if offset is None:
  113. break
  114. # ---- Health ----
  115. @app.get("/readyz")
  116. def readyz():
  117. return {"ok": True}
  118. def _normalize(q: Optional[str]) -> str:
  119. return re.sub(r"\s+", " ", (q or "").strip().lower())
  120. def _json_dumps(o) -> str:
  121. return json.dumps(o, ensure_ascii=False, separators=(",",":"))
  122. # ---- Councils list (prefers payload 'council', falls back to filename token) ----
  123. @app.get("/councils")
  124. def councils():
  125. councils = set()
  126. offset = None
  127. # sample up to ~5k points (50 * 100)
  128. for _ in range(50):
  129. points, offset = qc.scroll(
  130. collection_name=COLLECTION,
  131. limit=100,
  132. with_payload=True,
  133. offset=offset
  134. )
  135. for pt in points:
  136. p = pt.payload or {}
  137. token = (p.get("council") or "").strip().lower()
  138. if not token:
  139. sf = (p.get("source_file") or "").lower()
  140. if sf:
  141. token = sf.replace(".pdf", "").split("_")[0].split("-")[0]
  142. if token:
  143. councils.add(token)
  144. if offset is None:
  145. break
  146. return sorted(councils)
  147. # ---- Filter builders ----
  148. def _mv(key: str, value: str) -> qmodels.FieldCondition:
  149. return qmodels.FieldCondition(key=key, match=qmodels.MatchValue(value=value))
  150. def _mt(key: str, text: str) -> qmodels.FieldCondition:
  151. return qmodels.FieldCondition(key=key, match=qmodels.MatchText(text=text))
  152. def filter_tps() -> qmodels.Filter:
  153. """TPS only, exact match on corpus."""
  154. return qmodels.Filter(must=[_mv("corpus", "tps")])
  155. def filter_lps(council: str) -> qmodels.Filter:
  156. """
  157. LPS for a specific council (slug), exact match on both fields.
  158. """
  159. cslug = slug(council) or council.lower()
  160. return qmodels.Filter(must=[_mv("corpus", "lps"), _mv("council", cslug)])
  161. def filter_ncc() -> qmodels.Filter:
  162. return qmodels.Filter(must=[_mv("corpus", "ncc")])
  163. def filter_as() -> qmodels.Filter:
  164. return qmodels.Filter(must=[_mv("corpus", "as")])
  165. def with_source_contains(flt: Optional[qmodels.Filter], source_contains: Optional[str]) -> qmodels.Filter:
  166. if not source_contains:
  167. return flt
  168. add = _mt("source_file", source_contains)
  169. if flt:
  170. # preserve existing must/should/must_not and AND the filename condition
  171. must = list(getattr(flt, "must", []) or [])
  172. must.append(add)
  173. return qmodels.Filter(
  174. must=must,
  175. should=getattr(flt, "should", None),
  176. must_not=getattr(flt, "must_not", None),
  177. )
  178. return qmodels.Filter(must=[add])
  179. def q_search(vec: List[float], flt: Optional[qmodels.Filter], limit: int):
  180. results = qc.query_points(
  181. collection_name=COLLECTION,
  182. query=vec,
  183. limit=max(1, limit),
  184. query_filter=flt,
  185. with_payload=True,
  186. )
  187. return results.points
  188. def render_blocks(hits) -> Tuple[List[str], List[dict]]:
  189. blocks, sources = [], []
  190. for h in hits:
  191. p = h.payload or {}
  192. src = f"{p.get('source_file')} (p.{p.get('page')} chunk {p.get('chunk_index')})"
  193. snippet = p.get("text", "")
  194. blocks.append(f"Source: {src}\nText: {snippet}")
  195. sources.append({
  196. "source_file": p.get("source_file"),
  197. "page": p.get("page"),
  198. "chunk_index": p.get("chunk_index"),
  199. "score": h.score
  200. })
  201. return blocks, sources
  202. def combine_context(sections: List[Tuple[str, List[str]]]) -> str:
  203. out = []
  204. for heading, blocks in sections:
  205. if not blocks:
  206. continue
  207. out.append(f"=== {heading} ===")
  208. out.extend(blocks)
  209. return "\n\n".join(out) if out else "No context found."
  210. def _scan_points(qfilter: Optional[qmodels.Filter] = None, max_pages: int = 10000, page_size: int = 200):
  211. """
  212. Iterate through ALL points (filtered if qfilter given).
  213. For your current dataset this is fine; if it grows huge later we'll switch to a stored summary or a background job.
  214. """
  215. offset = None
  216. pages = 0
  217. while pages < max_pages:
  218. points, offset = qc.scroll(
  219. collection_name=COLLECTION,
  220. limit=page_size,
  221. with_payload=True,
  222. offset=offset,
  223. scroll_filter=qfilter
  224. )
  225. if not points:
  226. break
  227. for pt in points:
  228. yield pt
  229. pages += 1
  230. if offset is None:
  231. break
  232. @app.get("/admin/stats")
  233. def admin_stats(council: Optional[str] = None, corpus: Optional[str] = None):
  234. must = []
  235. if council:
  236. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  237. if corpus:
  238. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  239. qfilter = qmodels.Filter(must=must) if must else None
  240. corp = Counter()
  241. councils = Counter()
  242. total = 0
  243. for pt in _scan_points(qfilter=qfilter):
  244. p = pt.payload or {}
  245. corp[(p.get("corpus") or "").lower()] += 1
  246. if p.get("council"):
  247. councils[(p.get("council") or "").lower()] += 1
  248. total += 1
  249. return {
  250. "collection": COLLECTION,
  251. "total_points": total,
  252. "by_corpus": dict(corp),
  253. "by_council": dict(councils),
  254. "note": "Counts are points (chunks), not documents.",
  255. }
  256. @app.get("/admin/files")
  257. def admin_files(council: Optional[str] = None, corpus: Optional[str] = None, contains: Optional[str] = None, limit: int = 200):
  258. must = []
  259. if council:
  260. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  261. if corpus:
  262. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  263. if contains:
  264. must.append(qmodels.FieldCondition(key="source_file", match=qmodels.MatchText(text=contains)))
  265. qfilter = qmodels.Filter(must=must) if must else None
  266. files = defaultdict(lambda: {"points": 0, "corpus": None, "council": None, "pages": set()})
  267. for pt in _scan_points(qfilter=qfilter):
  268. p = pt.payload or {}
  269. f = (p.get("source_file") or "").strip()
  270. if not f:
  271. continue
  272. rec = files[f]
  273. rec["points"] += 1
  274. rec["corpus"] = rec["corpus"] or p.get("corpus")
  275. rec["council"] = rec["council"] or p.get("council")
  276. if p.get("page") is not None:
  277. rec["pages"].add(p["page"])
  278. # shape for output
  279. out = []
  280. for f, rec in files.items():
  281. out.append({
  282. "source_file": f,
  283. "corpus": rec["corpus"],
  284. "council": rec["council"],
  285. "points": rec["points"],
  286. "page_count_est": len(rec["pages"]) if rec["pages"] else None,
  287. })
  288. # sort by points desc, limit
  289. out.sort(key=lambda x: x["points"], reverse=True)
  290. return out[:max(1, limit)]
  291. @app.get("/admin/sample")
  292. def admin_sample(council: Optional[str] = None, corpus: Optional[str] = None, n: int = 5):
  293. must = []
  294. if council:
  295. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  296. if corpus:
  297. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  298. qfilter = qmodels.Filter(must=must) if must else None
  299. samples = []
  300. for pt in _scan_points(qfilter=qfilter):
  301. p = pt.payload or {}
  302. txt = (p.get("text") or "").strip()
  303. if not txt:
  304. continue
  305. samples.append({
  306. "source_file": p.get("source_file"),
  307. "corpus": p.get("corpus"),
  308. "council": p.get("council"),
  309. "page": p.get("page"),
  310. "chunk_index": p.get("chunk_index"),
  311. "preview": (txt[:400] + "…") if len(txt) > 400 else txt
  312. })
  313. if len(samples) >= max(1, n):
  314. break
  315. return samples
  316. @app.get("/admin/export")
  317. def admin_export(
  318. collection: str = COLLECTION,
  319. council: Optional[str] = None,
  320. corpus: Optional[str] = None,
  321. source_contains: Optional[str] = None,
  322. include_vector: bool = False,
  323. limit: Optional[int] = None
  324. ):
  325. must = []
  326. if council:
  327. must.append(qmodels.FieldCondition(key="council", match=qmodels.MatchText(text=council.lower())))
  328. if corpus:
  329. must.append(qmodels.FieldCondition(key="corpus", match=qmodels.MatchText(text=corpus.lower())))
  330. if source_contains:
  331. must.append(qmodels.FieldCondition(key="source_file", match=qmodels.MatchText(text=source_contains)))
  332. qfilter = qmodels.Filter(must=must) if must else None
  333. def gen():
  334. count = 0
  335. for pt in _scroll_points(collection, qfilter=qfilter, include_vector=include_vector):
  336. obj = {
  337. "id": str(getattr(pt, "id", None)),
  338. "payload": pt.payload or {},
  339. }
  340. if include_vector:
  341. obj["vector"] = pt.vector
  342. yield json.dumps(obj, ensure_ascii=False) + "\n"
  343. count += 1
  344. if limit and count >= limit:
  345. break
  346. filename = f'{collection}-{corpus or "all"}-{council or "all"}.ndjson'
  347. headers = {"Content-Disposition": f'attachment; filename="{filename}"'}
  348. return StreamingResponse(gen(), media_type="application/x-ndjson", headers=headers)
  349. def _section_format_guide(section_id: Optional[str], section_title: str, ctx: dict) -> str:
  350. """
  351. Return strict, section-specific formatting guidance for the LLM.
  352. Keep these short, prescriptive, and impossible to ignore.
  353. """
  354. sid = (section_id or "").lower()
  355. # Utility bits from context
  356. zones = ctx.get("planning_zones") or []
  357. zone_label = ", ".join(zones) if zones else "the applicable zone"
  358. council_label = ctx.get("council") or ""
  359. # ---- ZONING (tables of clauses like your sample) ----
  360. if sid in {"zoning", "zoning-41", "zoning-42", "zoning-43", "zoning-44", "zoning-441", "zoning-442"}:
  361. return f"""
  362. FORMAT REQUIREMENTS (MANDATORY):
  363. - Produce a concise preface (≤ 2 sentences) naming {zone_label}.
  364. - 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'}**.
  365. - One row per subclause. If an A/P pair exists (e.g., A1 / P1), include both in the same row.
  366. - Columns (exact):
  367. | Clause | Topic | Acceptable Solution (A) | Performance Criteria (P) | Assessment | Source |
  368. - "Clause": the clause number (e.g., "12.3.1 A1" or "DOR-S1.7.1").
  369. - "Topic": short label extracted from the clause heading.
  370. - "Acceptable Solution (A)" and "Performance Criteria (P)": quote briefly—no more than 1–2 lines each.
  371. - "Assessment": state clearly whether the proposal meets A, or relies on P. If unknown from CONTEXT, write "TBC".
  372. - "Source": filename + page (from CONTEXT).
  373. - Only include clauses actually present in CONTEXT; NEVER invent clause numbers or text.
  374. - After the table, add a one-paragraph summary noting any items assessed as TBC or non-compliant.
  375. """.strip()
  376. # ---- Codes overview list/table (optional future) ----
  377. if sid.startswith("code-"):
  378. return """
  379. FORMAT REQUIREMENTS:
  380. - Start with one sentence stating which Code and why it is triggered.
  381. - Then provide a short checklist or table of the relevant sub-clauses (A vs P), with Source for each.
  382. - Keep to 150–250 words + table.
  383. """.strip()
  384. # ---- Permit Overview (concise triggers) ----
  385. if sid == "permit-overview":
  386. return """
  387. FORMAT REQUIREMENTS:
  388. - Produce 3 blocks with headings:
  389. 1) "Project Context" – 3–5 bullet points (site, proposal, zone).
  390. 2) "Applicable Provisions" – bullets grouping TPS SPP, LPS (selected council), and triggered Codes.
  391. 3) "Assessment Path" – bullet list of key clauses to assess next.
  392. - Cite specific clause numbers ONLY if present in CONTEXT (include Source).
  393. """.strip()
  394. # ---- Default (no special formatting) ----
  395. return """
  396. FORMAT REQUIREMENTS:
  397. - Use concise Markdown with short paragraphs and bullets as needed.
  398. - Cite briefly (filename + page) when quoting a control.
  399. """.strip()
  400. # ---- Ask (GET + POST) ----
  401. class AskBody(BaseModel):
  402. # accept multiple keys from different frontends
  403. query: Optional[str] = None
  404. question: Optional[str] = None
  405. q: Optional[str] = None
  406. prompt: Optional[str] = None
  407. top_k: int = 10
  408. council: Optional[str] = None
  409. include_ncc: bool = False
  410. include_standards: bool = False
  411. source_contains: Optional[str] = None
  412. scope: Literal['state_plus_local','local_only','state_only','any'] = 'state_plus_local'
  413. section_id: Optional[str] = None
  414. # BYOK mode: return context blocks without calling Ollama.
  415. # The browser then calls its own LLM with the returned context + prompt.
  416. context_only: bool = False
  417. def _allowed(p: dict, scope: str, cslug: Optional[str]) -> bool:
  418. corp = (p.get("corpus") or "").lower()
  419. council = (p.get("council") or "").lower()
  420. if scope == "local_only":
  421. return corp == "lps" and cslug and council == cslug
  422. if scope == "state_only":
  423. return corp == "tps"
  424. if scope == "state_plus_local":
  425. return corp == "tps" or (corp == "lps" and cslug and council == cslug)
  426. return True
  427. def do_ask(
  428. query: str,
  429. top_k: int = 10,
  430. council: Optional[str] = None,
  431. include_ncc: bool = False,
  432. include_standards: bool = False,
  433. source_contains: Optional[str] = None,
  434. scope: str = "state_plus_local",
  435. section_id: Optional[str] = None,
  436. context_only: bool = False,
  437. ):
  438. vec = ollama_embed(query)
  439. cslug = slug(council) if council else None
  440. # Build allowed scopes based on scope param
  441. scopes: List[Tuple[str, qmodels.Filter]] = []
  442. if scope in ("state_only", "state_plus_local", "any"):
  443. scopes.append(("Tasmanian Planning Scheme (SPP)", filter_tps()))
  444. if scope in ("local_only", "state_plus_local", "any") and cslug:
  445. scopes.append((f"Local Provisions Schedule — {cslug}", filter_lps(cslug)))
  446. if include_ncc:
  447. scopes.append(("National Construction Code (NCC)", filter_ncc()))
  448. if include_standards:
  449. scopes.append(("Australian Standards (AS)", filter_as()))
  450. # Apply additional filename filter if requested (AND)
  451. scopes = [(name, with_source_contains(flt, source_contains)) for name, flt in scopes]
  452. # Allocate limits per scope
  453. per_spp = max(3, top_k // 3) if any(n.startswith("Tasmanian Planning Scheme") for n, _ in scopes) else 0
  454. per_lps = max(3, top_k // 3) if any(n.startswith("Local Provisions Schedule") for n, _ in scopes) else 0
  455. remaining = max(1, top_k - (per_spp + per_lps))
  456. extra_scopes = sum(1 for n, _ in scopes if not (n.startswith("Tasmanian Planning Scheme") or n.startswith("Local Provisions Schedule")))
  457. per_extra = max(1, remaining // max(1, extra_scopes)) if extra_scopes else 0
  458. limits: List[int] = []
  459. for name, _ in scopes:
  460. if name.startswith("Tasmanian Planning Scheme"):
  461. limits.append(per_spp)
  462. elif name.startswith("Local Provisions Schedule"):
  463. limits.append(per_lps)
  464. else:
  465. limits.append(per_extra)
  466. sections: List[Tuple[str, List[str]]] = []
  467. all_sources: List[dict] = []
  468. for (name, flt), lim in zip(scopes, limits):
  469. if lim <= 0:
  470. continue
  471. hits = q_search(vec, flt, lim)
  472. # Guardrail: drop any hit that violates scope/council
  473. hits = [h for h in hits if _allowed(h.payload or {}, scope, cslug)]
  474. blocks, sources = render_blocks(hits)
  475. sections.append((name, blocks))
  476. all_sources.extend(sources)
  477. context = combine_context(sections)
  478. #format_guide = _section_format_guide(section_id, section_title="(auto)", ctx={})
  479. format_guide = _section_format_guide(
  480. section_id,
  481. section_title="(auto)",
  482. ctx={
  483. "council": council, # from do_ask parameter
  484. "planning_zones": [], # populate if you have zone detection
  485. }
  486. )
  487. prompt = f"""
  488. You are a careful planning and building compliance assistant.
  489. ALWAYS follow this order of authority when forming an answer:
  490. 1) Tasmanian Planning Scheme — State Planning Provisions (SPP). Use as the base rule-set.
  491. 2) Local Provisions Schedule (LPS) for the selected council. If an LPS provision modifies or overrides an SPP control, apply the LPS outcome.
  492. 3) (Optional) National Construction Code (NCC) — building control (separate to planning).
  493. 4) (Optional) Australian Standards — cite when directly relevant.
  494. Use ONLY the information in CONTEXT. If a clause/section is visible, quote it briefly and always cite the source file + page.
  495. If something is not supported by the provided CONTEXT, say you don't know.
  496. CONTEXT:
  497. {context}
  498. SECTION FORMAT GUIDANCE:
  499. {format_guide}
  500. QUESTION: {query}
  501. Answer:
  502. """.strip()
  503. # BYOK mode: skip Ollama and return the context + prompt so the
  504. # browser can call its own LLM provider (Claude, GPT, Grok, etc.)
  505. if context_only:
  506. return {
  507. "context_only": True,
  508. "context": context,
  509. "prompt": prompt,
  510. "sources": all_sources,
  511. # Include the raw section blocks so the browser can inspect them
  512. "sections": [
  513. {"heading": name, "blocks": blocks}
  514. for name, blocks in sections
  515. ]
  516. }
  517. answer = ollama_chat(prompt)
  518. return {"answer": answer, "sources": all_sources}
  519. @app.get("/ask")
  520. @limiter.limit("20/minute")
  521. def ask_get(
  522. request: Request,
  523. query: str = Query(..., description="User question"),
  524. top_k: int = 10,
  525. council: Optional[str] = None,
  526. include_ncc: bool = False,
  527. include_standards: bool = False,
  528. source_contains: Optional[str] = None,
  529. scope: str = "state_plus_local",
  530. section_id: Optional[str] = None,
  531. context_only: bool = False,
  532. ):
  533. _verify_demo_token_if_needed(request)
  534. started = time.perf_counter()
  535. out = do_ask(query, top_k, council, include_ncc, include_standards, source_contains, scope, section_id, context_only)
  536. latency_ms = int((time.perf_counter() - started) * 1000)
  537. # Telemetry insert
  538. try:
  539. ip = request.client.host if request.client else "0.0.0.0"
  540. sid = request.headers.get("X-TPR-SID") or request.cookies.get("sid") or ""
  541. allow_tps = scope in ("state_only", "state_plus_local")
  542. topk = [{"id": f"{s.get('source_file')}#p{s.get('page')}", "score": s.get("score")} for s in (out.get("sources") or [])]
  543. with db() as conn:
  544. conn.execute("""
  545. INSERT INTO ask_logs
  546. (ts, sid, ip_hash, query, normalized, allow_tps, latency_ms, model, ok, topk_json, tokens_in, tokens_out)
  547. VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
  548. """, (
  549. datetime.utcnow().isoformat(),
  550. sid, ip_hash(ip), query, _normalize(query), int(allow_tps),
  551. latency_ms, CHAT_MODEL, 1, _json_dumps(topk), 0, 0
  552. ))
  553. conn.commit()
  554. except Exception as e:
  555. # Don't break the request if logging fails
  556. print("[telemetry] ask_get insert failed:", e)
  557. return out
  558. @app.post("/ask")
  559. @limiter.limit("20/minute")
  560. def ask_post(request: Request, body: AskBody):
  561. _verify_demo_token_if_needed(request)
  562. qtxt = (body.query or body.question or body.q or body.prompt or "").strip()
  563. if not qtxt:
  564. raise HTTPException(status_code=422, detail="Missing query/question")
  565. started = time.perf_counter()
  566. out = do_ask(
  567. query=qtxt,
  568. top_k=body.top_k,
  569. council=body.council,
  570. include_ncc=body.include_ncc,
  571. include_standards=body.include_standards,
  572. source_contains=body.source_contains,
  573. scope=body.scope,
  574. section_id=body.section_id,
  575. context_only=body.context_only,
  576. )
  577. latency_ms = int((time.perf_counter() - started) * 1000)
  578. # Telemetry insert
  579. try:
  580. ip = request.client.host if request.client else "0.0.0.0"
  581. sid = request.headers.get("X-TPR-SID") or request.cookies.get("sid") or ""
  582. allow_tps = body.scope in ("state_only", "state_plus_local")
  583. topk = [{"id": f"{s.get('source_file')}#p{s.get('page')}", "score": s.get("score")} for s in (out.get("sources") or [])]
  584. with db() as conn:
  585. conn.execute("""
  586. INSERT INTO ask_logs
  587. (ts, sid, ip_hash, query, normalized, allow_tps, latency_ms, model, ok, topk_json, tokens_in, tokens_out)
  588. VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
  589. """, (
  590. datetime.utcnow().isoformat(),
  591. sid, ip_hash(ip), qtxt, _normalize(qtxt), int(allow_tps),
  592. latency_ms, CHAT_MODEL, 1, _json_dumps(topk), 0, 0
  593. ))
  594. conn.commit()
  595. except Exception as e:
  596. print("[telemetry] ask_post insert failed:", e)
  597. return out