#!/usr/bin/env python3 """Interactive terminal client for the already-running Civic API.""" import json import os import sys import urllib.error import urllib.request API_URL = os.getenv( "CIVIC_API_URL", "http://127.0.0.1:8000/v1/civic/analyze" ) def analyze(query: str, trace: bool) -> dict: body = json.dumps({"query": query, "trace": trace}).encode("utf-8") request = urllib.request.Request( API_URL, data=body, headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(request, timeout=180) as response: return json.load(response) def print_answer(result: dict, show_json: bool) -> None: if show_json: print(json.dumps(result, ensure_ascii=False, indent=2)) return print(f"\nAI: {result.get('answer', '(khong co cau tra loi)')}") # `citations` la danh sach chuoi; URL nam trong `evidence`. urls = {} for ev in result.get("evidence") or []: if ev.get("url"): urls.setdefault(ev.get("citation") or "", ev["url"]) urls.setdefault(ev.get("title") or "", ev["url"]) citations = result.get("citations") or [] if citations: print("\nNguon tham khao:") for index, citation in enumerate(citations, 1): label = citation if isinstance(citation, str) else ( citation.get("citation") or citation.get("title") or "Nguon") print(f" [{index}] {label}") url = next((u for key, u in urls.items() if key and key in label), "") if url: print(f" {url}") engine = result.get("engine") or "?" print(f"\nEngine: {engine} | trang thai: {result.get('final_state')}") if result.get("engine_note"): print(f"Canh bao: {result['engine_note']}") print( "\nPhan loai: " f"domain={result.get('domain')} | intent={result.get('intent')} | " f"action={result.get('next_action')} | reason={result.get('reason_code')}" ) def main() -> int: show_json = False trace = False print("Civic AI live chat (dung API dang warm)") print("Lenh: /json, /trace, /thoat") while True: try: query = input("\nBan: ").strip() except (EOFError, KeyboardInterrupt): print("\nDa thoat.") return 0 if not query: continue if query in {"/thoat", "/exit", "/quit"}: print("Da thoat.") return 0 if query == "/json": show_json = not show_json print(f"JSON: {'bat' if show_json else 'tat'}") continue if query == "/trace": trace = not trace print(f"Trace: {'bat' if trace else 'tat'}") continue try: print("Dang xu ly...", flush=True) print_answer(analyze(query, trace), show_json) except urllib.error.URLError as exc: print(f"Khong ket noi duoc API: {exc}", file=sys.stderr) except Exception as exc: print(f"Loi: {exc}", file=sys.stderr) if __name__ == "__main__": raise SystemExit(main())