File size: 3,157 Bytes
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/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())