Khang1312 commited on
Commit
43e7de8
·
1 Parent(s): 4c57d06

Update web UI and evaluation workflow

Browse files
.gitignore CHANGED
Binary files a/.gitignore and b/.gitignore differ
 
LICENSE DELETED
File without changes
Makefile DELETED
File without changes
README.md CHANGED
@@ -1,10 +1,93 @@
1
- ---
2
- title: Legislation GraphRAG
3
- emoji: 🚀
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: docker
7
- ---
8
-
9
  # Legislation GraphRAG
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Legislation GraphRAG
2
 
3
+ ## Giới Thiệu Web
4
+
5
+ Legislation GraphRAG là web tra cứu và hỏi đáp văn bản pháp luật Việt Nam. Người dùng có thể mở văn bản trên giao diện, đọc nội dung tài liệu và đặt câu hỏi để hệ thống trả lời dựa trên ngữ cảnh được truy xuất từ kho văn bản.
6
+
7
+ Web tập trung vào các chức năng chính:
8
+
9
+ - Hiển thị 5 văn bản pháp luật ngẫu nhiên.
10
+ - Mở văn bản trong khung xem tài liệu.
11
+ - Phóng to, thu nhỏ và reset mức zoom khi xem tài liệu.
12
+ - Nhập câu hỏi pháp luật và nhận câu trả lời từ hệ thống RAG.
13
+ - Hiển thị hội thoại, số nguồn được dùng và thời gian xử lý.
14
+
15
+ ## Hướng Dẫn Dùng Web
16
+
17
+ Chạy các lệnh sau trong terminal từ thư mục dự án.
18
+
19
+ Tạo môi trường Python và cài thư viện:
20
+
21
+ ```bash
22
+ python -m venv .venv
23
+ .venv\Scripts\activate
24
+ pip install -e .
25
+ ```
26
+
27
+ Tạo file cấu hình môi trường:
28
+
29
+ ```bash
30
+ copy .env.example .env
31
+ ```
32
+
33
+ Mở `.env` và điền các giá trị cần thiết như `OPENAI_API_KEY`, `QDRANT_URL`, `QDRANT_API_KEY`, `QDRANT_COLLECTION`.
34
+
35
+ Nếu dùng Qdrant local, chạy:
36
+
37
+ ```bash
38
+ docker compose up -d qdrant
39
+ ```
40
+
41
+ Đưa dữ liệu vào Qdrant:
42
+
43
+ ```bash
44
+ python scripts/ingest.py --normalize
45
+ ```
46
+
47
+ Lệnh ingest sẽ chuẩn hóa dữ liệu từ `data/raw` sang `data/normalized`, chia chunk, tạo embedding và upsert vào Qdrant.
48
+
49
+ Sau đó chạy web:
50
+
51
+ ```bash
52
+ set PYTHONIOENCODING=utf-8
53
+ python -m uvicorn src.app.main:app --host 127.0.0.1 --port 8000
54
+ ```
55
+
56
+ Khi server khởi động, hệ thống sẽ tự build BM25 nếu chưa có và tự load graph snapshot. Nếu chưa có snapshot, hệ thống sẽ tự build graph từ `data/normalized` rồi lưu snapshot vào `outputs/runtime/runtime_graph_snapshot.json`.
57
+
58
+ Mở web tại:
59
+
60
+ ```text
61
+ http://127.0.0.1:8000/
62
+ ```
63
+
64
+ Cách sử dụng:
65
+
66
+ 1. Xem danh sách 5 văn bản pháp luật ngẫu nhiên ở cột trái.
67
+ 2. Bấm `Làm mới` nếu muốn đổi danh sách văn bản.
68
+ 3. Bấm vào tên một văn bản để mở nội dung trong khung xem ở giữa.
69
+ 4. Dùng `Thu nhỏ`, `Phóng to`, `Reset` để điều chỉnh khung xem.
70
+ 5. Nhập câu hỏi vào ô `Câu hỏi` trong phần `Tra cứu pháp luật`.
71
+ 6. Bấm `Gửi câu hỏi`.
72
+ 7. Xem câu trả lời trong phần `Hội thoại`.
73
+
74
+ Gợi ý khi đặt câu hỏi:
75
+
76
+ - Nếu hỏi theo một văn bản cụ thể, nên kèm tên hoặc tóm tắt tiêu đề văn bản.
77
+ - Với môi trường CPU-only, thời gian phản hồi có thể khoảng 30 giây hoặc hơn.
78
+
79
+ ## Evaluation
80
+
81
+ Evaluation được chạy bằng terminal thông qua file `run_all`. Lệnh này tự động chạy toàn bộ quy trình đánh giá: validate benchmark, chuẩn bị dữ liệu JSONL, thu RAG outputs, chạy RAGAS-lite và in báo cáo kết quả.
82
+
83
+ Chạy evaluation:
84
+
85
+ ```bash
86
+ python -m src.evaluation.run_all --input data/eval/legal_rag_benchmark_25.json
87
+ ```
88
+
89
+ Kết quả chính được lưu tại:
90
+
91
+ ```text
92
+ data/eval/ragas_lite_results.json
93
+ ```
pyproject.toml CHANGED
@@ -41,6 +41,14 @@ dependencies = [
41
  "tqdm>=4.62.0"
42
  ]
43
 
 
 
 
 
 
 
 
 
44
  [build-system]
45
  requires = ["setuptools>=61.0", "wheel"]
46
  build-backend = "setuptools.build_meta"
 
41
  "tqdm>=4.62.0"
42
  ]
43
 
44
+ [project.optional-dependencies]
45
+ vi = [
46
+ "pyvi>=0.1.1"
47
+ ]
48
+ agent = [
49
+ "langgraph>=0.0.40"
50
+ ]
51
+
52
  [build-system]
53
  requires = ["setuptools>=61.0", "wheel"]
54
  build-backend = "setuptools.build_meta"
src/app/api/admin.py DELETED
@@ -1,50 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import Any, Dict, Optional
4
-
5
- from fastapi import APIRouter, Query
6
-
7
- from src.app.runtime import (
8
- build_runtime_graph,
9
- ensure_runtime_graph,
10
- get_runtime_status,
11
- save_current_runtime_graph_snapshot,
12
- )
13
- from src.rag.legal_versioning import summarize_versioning
14
-
15
- router = APIRouter(prefix="/admin", tags=["admin"])
16
-
17
-
18
- @router.get("/status")
19
- def status() -> Dict[str, Any]:
20
- return get_runtime_status()
21
-
22
-
23
- @router.post("/reload-graph")
24
- def reload_graph(
25
- input_dir: Optional[str] = Query(default=None),
26
- glob_pattern: Optional[str] = Query(default=None),
27
- ) -> Dict[str, Any]:
28
- graph = build_runtime_graph(input_dir=input_dir, glob_pattern=glob_pattern)
29
- return {
30
- "graph_nodes": len(graph.get("nodes", [])),
31
- "graph_edges": len(graph.get("edges", [])),
32
- "status": get_runtime_status(),
33
- }
34
-
35
-
36
- @router.get("/versioning")
37
- def versioning_preview(limit: int = 20) -> Dict[str, Any]:
38
- graph = ensure_runtime_graph()
39
- rows = summarize_versioning(graph)
40
- return {
41
- "count": len(rows),
42
- "items": rows[:limit],
43
- }
44
-
45
-
46
- @router.post("/save-snapshot")
47
- def save_snapshot(force_build: bool = False) -> Dict[str, Any]:
48
- result = save_current_runtime_graph_snapshot(force_build=force_build)
49
- result["status"] = get_runtime_status()
50
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/benchmark.py DELETED
@@ -1,41 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import Any, Dict, List, Optional
4
-
5
- from fastapi import APIRouter
6
- from pydantic import BaseModel, Field
7
-
8
- from src.eval.benchmark_metrics import evaluate_rag_response
9
- from src.eval.performance_monitor import PerformanceMonitor
10
-
11
- router = APIRouter(prefix="/benchmark", tags=["benchmark"])
12
-
13
-
14
- class BenchmarkRequest(BaseModel):
15
- question: str = Field(..., min_length=1)
16
- answer: str = Field(..., min_length=1)
17
- contexts: List[str] = Field(default_factory=list)
18
- reference_answer: Optional[str] = None
19
- n_generated_questions: int = 3
20
-
21
-
22
- @router.post("/evaluate")
23
- def benchmark_evaluate(req: BenchmarkRequest) -> Dict[str, Any]:
24
- perf = PerformanceMonitor()
25
-
26
- perf.start("benchmark_total")
27
- perf.start("metrics")
28
-
29
- result = evaluate_rag_response(
30
- question=req.question,
31
- answer=req.answer,
32
- contexts=req.contexts,
33
- reference_answer=req.reference_answer,
34
- n_generated_questions=req.n_generated_questions,
35
- )
36
-
37
- perf.stop("metrics")
38
- perf.stop("benchmark_total")
39
-
40
- result["timings_ms"] = perf.report()
41
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/chat.py CHANGED
@@ -7,9 +7,12 @@ from typing import Any, Dict, Optional
7
  from fastapi import APIRouter
8
  from pydantic import BaseModel, Field
9
 
 
10
  from src.app.runtime import ensure_runtime_graph
 
11
  from src.rag.qa_engine import answer_with_rag
12
  from src.rag.retrieval_pipeline import retrieve_with_graph
 
13
 
14
  router = APIRouter(prefix="/chat", tags=["chat"])
15
  logger = logging.getLogger(__name__)
@@ -34,16 +37,31 @@ def chat(req: ChatRequestModel) -> Dict[str, Any]:
34
  graph = ensure_runtime_graph()
35
  t1 = time.perf_counter()
36
 
37
- retrieval_result = retrieve_with_graph(
38
- question=req.question,
39
- graph=graph,
40
- filters=req.filters,
41
- qdrant_top_k=req.qdrant_top_k,
42
- graph_hops=req.graph_hops,
43
- max_graph_nodes=req.max_graph_nodes,
44
- final_top_k=req.final_top_k,
45
- cross_top_k=req.cross_top_k,
46
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  t2 = time.perf_counter()
48
 
49
  response = answer_with_rag(
@@ -75,6 +93,8 @@ def chat(req: ChatRequestModel) -> Dict[str, Any]:
75
  "candidate_pool": retrieval_result.get("candidate_pool", []),
76
  "passages_count": len(retrieval_result.get("passages", []) or []),
77
  "insufficient_context": retrieval_result.get("insufficient_context", False),
 
 
78
  }
79
 
80
- return result
 
7
  from fastapi import APIRouter
8
  from pydantic import BaseModel, Field
9
 
10
+ from src.app.settings import settings
11
  from src.app.runtime import ensure_runtime_graph
12
+ from src.rag.context_grader import grade_context
13
  from src.rag.qa_engine import answer_with_rag
14
  from src.rag.retrieval_pipeline import retrieve_with_graph
15
+ from src.rag.retrieval_pipeline_simple import retrieve_with_graph_simple
16
 
17
  router = APIRouter(prefix="/chat", tags=["chat"])
18
  logger = logging.getLogger(__name__)
 
37
  graph = ensure_runtime_graph()
38
  t1 = time.perf_counter()
39
 
40
+ if str(getattr(settings, "retrieval_pipeline", "simple_rrf") or "").lower() in {"simple", "simple_rrf"}:
41
+ retrieval_result = retrieve_with_graph_simple(
42
+ question=req.question,
43
+ graph=graph,
44
+ filters=req.filters,
45
+ final_top_k=req.final_top_k,
46
+ )
47
+ context_grade = grade_context(
48
+ req.question,
49
+ dict(retrieval_result.get("query_profile") or {}),
50
+ list(retrieval_result.get("passages") or []),
51
+ )
52
+ retrieval_result["context_grade"] = context_grade
53
+ retrieval_result["insufficient_context"] = context_grade.get("status") == "insufficient"
54
+ else:
55
+ retrieval_result = retrieve_with_graph(
56
+ question=req.question,
57
+ graph=graph,
58
+ filters=req.filters,
59
+ qdrant_top_k=req.qdrant_top_k,
60
+ graph_hops=req.graph_hops,
61
+ max_graph_nodes=req.max_graph_nodes,
62
+ final_top_k=req.final_top_k,
63
+ cross_top_k=req.cross_top_k,
64
+ )
65
  t2 = time.perf_counter()
66
 
67
  response = answer_with_rag(
 
93
  "candidate_pool": retrieval_result.get("candidate_pool", []),
94
  "passages_count": len(retrieval_result.get("passages", []) or []),
95
  "insufficient_context": retrieval_result.get("insufficient_context", False),
96
+ "context_grade": retrieval_result.get("context_grade", {}),
97
+ "filter_info": retrieval_result.get("filter_info", {}),
98
  }
99
 
100
+ return result
src/app/api/router.py CHANGED
@@ -2,11 +2,9 @@ from __future__ import annotations
2
 
3
  from fastapi import APIRouter
4
 
5
- from src.app.api.benchmark import router as benchmark_router
6
  from src.app.api.chat import router as chat_router
7
  from src.app.api.documents import router as documents_router
8
 
9
  api_router = APIRouter()
10
- api_router.include_router(benchmark_router)
11
  api_router.include_router(chat_router)
12
  api_router.include_router(documents_router)
 
2
 
3
  from fastapi import APIRouter
4
 
 
5
  from src.app.api.chat import router as chat_router
6
  from src.app.api.documents import router as documents_router
7
 
8
  api_router = APIRouter()
 
9
  api_router.include_router(chat_router)
10
  api_router.include_router(documents_router)
src/app/settings.py CHANGED
@@ -46,6 +46,7 @@ class Settings:
46
  normalized_glob: str = os.getenv("NORMALIZED_GLOB", "*.*")
47
  graph_snapshot_path: str = os.getenv("GRAPH_SNAPSHOT_PATH", "outputs/runtime/runtime_graph_snapshot.json")
48
  bm25_stats_path: str = os.getenv("BM25_STATS_PATH", "outputs/bm25/bm25_stats.json")
 
49
 
50
  doc_top_k: int = _get_int("DOC_TOP_K", 3)
51
  content_top_k_per_doc: int = _get_int("CONTENT_TOP_K_PER_DOC", 3)
@@ -61,9 +62,11 @@ class Settings:
61
  answer_max_context_passages: int = _get_int("ANSWER_MAX_CONTEXT_PASSAGES", 5)
62
  answer_max_source_items: int = _get_int("ANSWER_MAX_SOURCE_ITEMS", 5)
63
 
64
- rerank_model: str = os.getenv("RERANK_MODEL", "BAAI/bge-reranker-v2-m3")
 
65
  rerank_device: str = os.getenv("RERANK_DEVICE", "cpu")
66
- rerank_top_n: int = _get_int("RERANK_TOP_N", 12)
 
67
 
68
  app_host: str = os.getenv("APP_HOST", "127.0.0.1")
69
  app_port: int = _get_int("APP_PORT", 8000)
 
46
  normalized_glob: str = os.getenv("NORMALIZED_GLOB", "*.*")
47
  graph_snapshot_path: str = os.getenv("GRAPH_SNAPSHOT_PATH", "outputs/runtime/runtime_graph_snapshot.json")
48
  bm25_stats_path: str = os.getenv("BM25_STATS_PATH", "outputs/bm25/bm25_stats.json")
49
+ retrieval_pipeline: str = os.getenv("RETRIEVAL_PIPELINE", "simple_rrf")
50
 
51
  doc_top_k: int = _get_int("DOC_TOP_K", 3)
52
  content_top_k_per_doc: int = _get_int("CONTENT_TOP_K_PER_DOC", 3)
 
62
  answer_max_context_passages: int = _get_int("ANSWER_MAX_CONTEXT_PASSAGES", 5)
63
  answer_max_source_items: int = _get_int("ANSWER_MAX_SOURCE_ITEMS", 5)
64
 
65
+ enable_reranker: bool = os.getenv("ENABLE_RERANKER", "0").strip().lower() in {"1", "true", "yes", "on"}
66
+ rerank_model: str = os.getenv("RERANK_MODEL", "cross-encoder/mmarco-mMiniLMv2-L12-H384-v1")
67
  rerank_device: str = os.getenv("RERANK_DEVICE", "cpu")
68
+ rerank_top_n: int = _get_int("RERANK_TOP_N", 5)
69
+ rerank_input_top_k: int = _get_int("RERANK_INPUT_TOP_K", 30)
70
 
71
  app_host: str = os.getenv("APP_HOST", "127.0.0.1")
72
  app_port: int = _get_int("APP_PORT", 8000)
src/app/statistic/index.html CHANGED
@@ -34,7 +34,6 @@
34
  padding: 14px;
35
  margin-top: 12px;
36
  }
37
- .role-btns { display: flex; gap: 12px; flex-wrap: wrap; }
38
  button {
39
  border: 1px solid var(--border);
40
  background: #1f2a44;
@@ -105,18 +104,9 @@
105
  <body>
106
  <div class="container">
107
  <h1>Legislation GraphRAG</h1>
108
- <p class="subtitle">Chọn vai trò để vào giao diện phù hợp.</p>
109
 
110
- <div id="landing" class="card">
111
- <h2>Bạn là ai?</h2>
112
- <div class="role-btns">
113
- <button class="primary" onclick="openRole('user')">Vào trang User</button>
114
- <button onclick="openRole('admin')">Vào trang Admin</button>
115
- </div>
116
- <p class="subtitle" style="margin-top:12px;">User chỉ chat. Admin có đầy đủ công cụ vận hành.</p>
117
- </div>
118
-
119
- <div id="userPanel" class="hidden">
120
  <div class="user-layout">
121
  <div class="card side-card">
122
  <div class="row" style="justify-content:space-between; align-items:center;">
@@ -142,11 +132,7 @@
142
  <div class="chat-column">
143
  <div class="card">
144
  <div class="row" style="justify-content:space-between; align-items:center;">
145
- <h2>User Chat</h2>
146
- <div>
147
- <span class="tag">User mode</span>
148
- <button class="ghost" onclick="backToLanding()">← Quay lại chọn vai trò</button>
149
- </div>
150
  </div>
151
  <p class="subtitle">Hãy hỏi các câu hỏi pháp luật trong văn bản hiển thị. Khuyến cáo: Mỗi câu hỏi nên đi kèm tóm gọn tiêu đề của văn bản được hỏi.</p>
152
  <label for="userQuestion">Câu hỏi</label>
@@ -165,44 +151,6 @@
165
  </div>
166
  </div>
167
 
168
- <div id="adminPanel" class="hidden">
169
- <div class="card">
170
- <div class="row" style="justify-content:space-between; align-items:center;">
171
- <h2>Admin Console</h2>
172
- <div>
173
- <span class="tag">Admin mode</span>
174
- <button class="ghost" onclick="backToLanding()">← Quay lại chọn vai trò</button>
175
- </div>
176
- </div>
177
- <p class="subtitle">Admin dùng chat debug và benchmark để kiểm thử chất lượng phản hồi.</p>
178
- </div>
179
-
180
- <div class="card">
181
- <h3>Admin Chat (debug)</h3>
182
- <textarea id="adminQuestion" placeholder="Nhập câu hỏi để test retrieval + debug..."></textarea>
183
- <div class="row">
184
- <button class="primary" onclick="sendAdminChat()">Gửi /api/chat (debug)</button>
185
- </div>
186
- </div>
187
-
188
- <div class="card">
189
- <h3>Benchmark Evaluate</h3>
190
- <label>Câu hỏi</label>
191
- <input id="benchQuestion" placeholder="Câu hỏi benchmark" />
192
- <label>Answer</label>
193
- <textarea id="benchAnswer" placeholder="Câu trả lời từ hệ thống"></textarea>
194
- <label>Reference answer (optional)</label>
195
- <textarea id="benchRef" placeholder="Đáp án chuẩn (nếu có)"></textarea>
196
- <label>Contexts (mỗi dòng là 1 context)</label>
197
- <textarea id="benchContexts" placeholder="Context 1\nContext 2"></textarea>
198
- <button onclick="runBenchmark()">/api/benchmark/evaluate</button>
199
- </div>
200
-
201
- <div class="card">
202
- <h3>Admin Output</h3>
203
- <pre id="adminOutput"></pre>
204
- </div>
205
- </div>
206
  </div>
207
 
208
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
@@ -211,19 +159,6 @@
211
  let viewerZoom = 1;
212
  let activeViewerType = 'none';
213
 
214
- function openRole(role) {
215
- document.getElementById('landing').classList.add('hidden');
216
- document.getElementById('userPanel').classList.toggle('hidden', role !== 'user');
217
- document.getElementById('adminPanel').classList.toggle('hidden', role !== 'admin');
218
- if (role === 'user') loadRandomDocuments();
219
- }
220
-
221
- function backToLanding() {
222
- document.getElementById('landing').classList.remove('hidden');
223
- document.getElementById('userPanel').classList.add('hidden');
224
- document.getElementById('adminPanel').classList.add('hidden');
225
- }
226
-
227
  async function postJson(url, body) {
228
  const res = await fetch(url, {
229
  method: 'POST',
@@ -233,10 +168,6 @@
233
  return await res.json();
234
  }
235
 
236
- function printAdmin(data) {
237
- document.getElementById('adminOutput').textContent = JSON.stringify(data, null, 2);
238
- }
239
-
240
  function setViewerMode(mode) {
241
  const viewerEl = document.getElementById('docViewer');
242
  viewerEl.classList.remove('paper-mode');
@@ -314,46 +245,6 @@
314
  statusEl.textContent = `Lỗi tải danh sách file: ${err}`;
315
  }
316
 
317
- viewerEl.innerHTML = `
318
- <div class="docx-zoom-container">
319
- <div class="docx-zoom-content" id="docxZoomRoot">
320
- <div class="doc-html-viewer" id="docxRenderRoot"><h4>${escapeHtml(filename)}</h4><div>Đang render file DOCX...</div></div>
321
- </div>
322
- </div>
323
- `;
324
-
325
- const renderRoot = document.getElementById('docxRenderRoot');
326
- try {
327
- const fileRes = await fetch(fileUrl);
328
- if (!fileRes.ok) {
329
- throw new Error(`HTTP ${fileRes.status}`);
330
- }
331
-
332
- const fileBuffer = await fileRes.arrayBuffer();
333
- renderRoot.innerHTML = '';
334
- await window.docx.renderAsync(fileBuffer, renderRoot, null, {
335
- className: 'docx',
336
- inWrapper: false,
337
- ignoreWidth: false,
338
- ignoreHeight: false,
339
- renderHeaders: true,
340
- renderFooters: true,
341
- renderFootnotes: true,
342
- useBase64URL: true,
343
- });
344
- applyViewerZoom();
345
- } catch (error) {
346
- setViewerMode('default');
347
- activeViewerType = 'fallback';
348
- const htmlBody = escapeHtml(data.preview || '(Không có nội dung)').replaceAll('\n', '<br />');
349
- viewerEl.innerHTML = `
350
- <div class="doc-html-viewer">
351
- <h4>${escapeHtml(filename)}</h4>
352
- <p>Render DOCX lỗi (${escapeHtml(error)}), hiển thị fallback:</p>
353
- <div>${htmlBody}</div>
354
- </div>
355
- `;
356
- }
357
  }
358
 
359
  async function renderDocumentViewer(item, data) {
@@ -560,39 +451,7 @@
560
  thread.scrollTop = thread.scrollHeight;
561
  }
562
 
563
- async function sendAdminChat() {
564
- const question = document.getElementById('adminQuestion').value.trim();
565
- if (!question) return;
566
- const data = await postJson('/api/chat', {
567
- question,
568
- include_debug: true,
569
- });
570
- printAdmin(data);
571
- }
572
-
573
- async function runBenchmark() {
574
- const question = document.getElementById('benchQuestion').value.trim();
575
- const answer = document.getElementById('benchAnswer').value.trim();
576
- const reference_answer = document.getElementById('benchRef').value.trim();
577
- const contexts = document.getElementById('benchContexts').value
578
- .split('\n')
579
- .map(x => x.trim())
580
- .filter(Boolean);
581
-
582
- if (!question || !answer) {
583
- alert('Benchmark cần ít nhất question + answer');
584
- return;
585
- }
586
-
587
- const data = await postJson('/api/benchmark/evaluate', {
588
- question,
589
- answer,
590
- contexts,
591
- reference_answer: reference_answer || null,
592
- n_generated_questions: 3,
593
- });
594
- printAdmin(data);
595
- }
596
  </script>
597
  </body>
598
  </html>
 
34
  padding: 14px;
35
  margin-top: 12px;
36
  }
 
37
  button {
38
  border: 1px solid var(--border);
39
  background: #1f2a44;
 
104
  <body>
105
  <div class="container">
106
  <h1>Legislation GraphRAG</h1>
107
+ <p class="subtitle">Tra cứu văn bản pháp luật và hỏi đáp theo ngữ cảnh tài liệu.</p>
108
 
109
+ <div id="userPanel">
 
 
 
 
 
 
 
 
 
110
  <div class="user-layout">
111
  <div class="card side-card">
112
  <div class="row" style="justify-content:space-between; align-items:center;">
 
132
  <div class="chat-column">
133
  <div class="card">
134
  <div class="row" style="justify-content:space-between; align-items:center;">
135
+ <h2>Tra cứu pháp luật</h2>
 
 
 
 
136
  </div>
137
  <p class="subtitle">Hãy hỏi các câu hỏi pháp luật trong văn bản hiển thị. Khuyến cáo: Mỗi câu hỏi nên đi kèm tóm gọn tiêu đề của văn bản được hỏi.</p>
138
  <label for="userQuestion">Câu hỏi</label>
 
151
  </div>
152
  </div>
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  </div>
155
 
156
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
 
159
  let viewerZoom = 1;
160
  let activeViewerType = 'none';
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  async function postJson(url, body) {
163
  const res = await fetch(url, {
164
  method: 'POST',
 
168
  return await res.json();
169
  }
170
 
 
 
 
 
171
  function setViewerMode(mode) {
172
  const viewerEl = document.getElementById('docViewer');
173
  viewerEl.classList.remove('paper-mode');
 
245
  statusEl.textContent = `Lỗi tải danh sách file: ${err}`;
246
  }
247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  }
249
 
250
  async function renderDocumentViewer(item, data) {
 
451
  thread.scrollTop = thread.scrollHeight;
452
  }
453
 
454
+ document.addEventListener('DOMContentLoaded', loadRandomDocuments);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
  </script>
456
  </body>
457
  </html>
src/evaluation/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Custom RAGAS-lite evaluation utilities for the legal RAG project."""
src/evaluation/collect_rag_outputs.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List
7
+
8
+ from src.app.runtime import ensure_runtime_graph
9
+ from src.app.settings import settings
10
+ from src.evaluation.schemas import BENCHMARK_JSONL, RAG_OUTPUTS_JSONL, read_jsonl, write_jsonl
11
+ from src.evaluation.prepare_benchmark import prepare_benchmark
12
+ from src.rag.qa_engine import answer_with_rag
13
+
14
+
15
+ def _retrieve(question: str, graph: Dict[str, Any], top_k: int) -> Dict[str, Any]:
16
+ pipeline = str(getattr(settings, "retrieval_pipeline", "simple_rrf") or "simple_rrf").lower()
17
+ if pipeline in {"simple", "simple_rrf"}:
18
+ from src.rag.context_grader import grade_context
19
+ from src.rag.retrieval_pipeline_simple import retrieve_with_graph_simple
20
+
21
+ result = retrieve_with_graph_simple(question, graph, final_top_k=top_k)
22
+ context_grade = grade_context(question, dict(result.get("query_profile") or {}), list(result.get("passages") or []))
23
+ result["context_grade"] = context_grade
24
+ result["insufficient_context"] = context_grade.get("status") == "insufficient"
25
+ return result
26
+
27
+ from src.rag.retrieval_pipeline import retrieve_with_graph
28
+
29
+ return retrieve_with_graph(question=question, graph=graph, final_top_k=top_k)
30
+
31
+
32
+ def _context_text(passage: Dict[str, Any]) -> str:
33
+ for key in ("retrieval_text", "local_text", "text", "snippet"):
34
+ value = passage.get(key)
35
+ if value is not None and str(value).strip():
36
+ return " ".join(str(value).split()).strip()
37
+ return ""
38
+
39
+
40
+ def _metadata_for_context(passage: Dict[str, Any]) -> Dict[str, str]:
41
+ md = dict(passage.get("metadata") or {})
42
+ return {
43
+ "chunk_id": str(passage.get("chunk_id") or passage.get("node_id") or md.get("chunk_id") or md.get("node_id") or ""),
44
+ "doc_number": str(md.get("doc_number") or ""),
45
+ "law_type": str(md.get("law_type") or md.get("doc_type") or ""),
46
+ "year": str(md.get("year") or ""),
47
+ "article": str(md.get("article") or ""),
48
+ "clause": str(md.get("clause") or ""),
49
+ "point": str(md.get("point") or ""),
50
+ "source": str(md.get("source") or md.get("issuing_agency") or ""),
51
+ }
52
+
53
+
54
+ def collect_outputs(input_path: str = str(BENCHMARK_JSONL), output_path: str = str(RAG_OUTPUTS_JSONL), top_k: int = 5, limit: int | None = None) -> List[Dict[str, Any]]:
55
+ if not Path(input_path).exists() and Path(input_path) == BENCHMARK_JSONL:
56
+ prepare_benchmark(output_path=BENCHMARK_JSONL)
57
+ samples = read_jsonl(input_path)
58
+ if limit is not None:
59
+ samples = samples[: max(0, int(limit))]
60
+ graph = ensure_runtime_graph()
61
+
62
+ rows: List[Dict[str, Any]] = []
63
+ for sample in samples:
64
+ question = str(sample.get("question") or "")
65
+ t0 = time.perf_counter()
66
+ retrieval_result = _retrieve(question, graph, top_k=top_k)
67
+ response = answer_with_rag(question, retrieval_result)
68
+ latency_ms = round((time.perf_counter() - t0) * 1000, 2)
69
+
70
+ contexts: List[str] = []
71
+ context_metadata: List[Dict[str, str]] = []
72
+ seen = set()
73
+ for passage in list(retrieval_result.get("passages") or [])[:top_k]:
74
+ text = _context_text(dict(passage))
75
+ if not text or text in seen:
76
+ continue
77
+ seen.add(text)
78
+ contexts.append(text)
79
+ context_metadata.append(_metadata_for_context(dict(passage)))
80
+
81
+ rows.append(
82
+ {
83
+ "id": sample.get("id"),
84
+ "question": question,
85
+ "answer": response.answer,
86
+ "ground_truth": sample.get("ground_truth", ""),
87
+ "reference": sample.get("reference", sample.get("ground_truth", "")),
88
+ "contexts": contexts,
89
+ "context_metadata": context_metadata,
90
+ "expected_context_refs": list(sample.get("expected_context_refs") or []),
91
+ "source_excerpt": sample.get("source_excerpt", ""),
92
+ "latency_ms": latency_ms,
93
+ }
94
+ )
95
+
96
+ write_jsonl(output_path, rows)
97
+ return rows
98
+
99
+
100
+ def main() -> None:
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument("--input", default=str(BENCHMARK_JSONL))
103
+ parser.add_argument("--output", default=str(RAG_OUTPUTS_JSONL))
104
+ parser.add_argument("--top-k", type=int, default=5)
105
+ parser.add_argument("--limit", type=int, default=None)
106
+ args = parser.parse_args()
107
+
108
+ rows = collect_outputs(args.input, args.output, top_k=args.top_k, limit=args.limit)
109
+ print(f"Collected {len(rows)} RAG outputs -> {args.output}")
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()
src/evaluation/metrics_report.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List
7
+
8
+ from src.evaluation.schemas import RAGAS_LITE_RESULTS
9
+
10
+ LOWEST_METRICS = [
11
+ "answer_correctness_lite",
12
+ "faithfulness_lite",
13
+ "context_precision_lite",
14
+ "context_recall_lite",
15
+ "context_sufficiency_lite",
16
+ "retrieval_ref_match_lite",
17
+ ]
18
+
19
+
20
+ def _score(sample: Dict[str, Any], metric: str) -> float:
21
+ value = sample.get("metrics", {}).get(metric, {}).get("score")
22
+ if isinstance(value, (int, float)):
23
+ return float(value)
24
+ return 999.0
25
+
26
+
27
+ def _reason(sample: Dict[str, Any], metric: str) -> str:
28
+ result = dict(sample.get("metrics", {}).get(metric, {}) or {})
29
+ return str(result.get("reason") or result.get("error") or "")[:180]
30
+
31
+
32
+ def render_report(path: str = str(RAGAS_LITE_RESULTS)) -> str:
33
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
34
+ summary = dict(data.get("summary") or {})
35
+ metrics = dict(summary.get("metrics") or {})
36
+ samples = [dict(x) for x in list(data.get("samples") or [])]
37
+
38
+ lines: List[str] = []
39
+ lines.append(f"{'Metric':30} Mean")
40
+ for name, value in metrics.items():
41
+ rendered = "n/a" if value is None else f"{float(value):.2f}"
42
+ lines.append(f"{name:30} {rendered}")
43
+
44
+ latencies = [float(s.get("latency_ms")) for s in samples if isinstance(s.get("latency_ms"), (int, float))]
45
+ if latencies:
46
+ lines.append("")
47
+ lines.append(f"Average latency_ms: {sum(latencies) / len(latencies):.1f}")
48
+
49
+ no_context = [s for s in samples if not s.get("metrics", {}).get("context_sufficiency_lite") and not s.get("answer")]
50
+ empty_contexts = [
51
+ s
52
+ for s in samples
53
+ if s.get("metrics", {}).get("context_sufficiency_lite", {}).get("score") == 0.0
54
+ ]
55
+ if empty_contexts:
56
+ lines.append("")
57
+ lines.append(f"WARNING: {len(empty_contexts)} samples have insufficient or empty context.")
58
+
59
+ for metric in LOWEST_METRICS:
60
+ if metric not in metrics:
61
+ continue
62
+ ranked = sorted(samples, key=lambda sample: _score(sample, metric))[:5]
63
+ lines.append("")
64
+ lines.append(f"Lowest {metric}:")
65
+ for sample in ranked:
66
+ score = sample.get("metrics", {}).get(metric, {}).get("score")
67
+ rendered = "n/a" if score is None else f"{float(score):.2f}"
68
+ suffix = ""
69
+ if metric == "retrieval_ref_match_lite":
70
+ suffix = f", question={str(sample.get('question') or '')[:80]}"
71
+ reason = _reason(sample, metric)
72
+ lines.append(f"- {sample.get('id')}: score={rendered}{suffix}, reason={reason}")
73
+
74
+ return "\n".join(lines)
75
+
76
+
77
+ def main() -> None:
78
+ parser = argparse.ArgumentParser()
79
+ parser.add_argument("--input", default=str(RAGAS_LITE_RESULTS))
80
+ args = parser.parse_args()
81
+ print(render_report(args.input))
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
src/evaluation/prepare_benchmark.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List
7
+
8
+ from src.evaluation.schemas import BENCHMARK_INPUT, BENCHMARK_JSONL, expected_ref_from_sample, resolve_benchmark_input, write_jsonl
9
+
10
+
11
+ def prepare_samples(data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
12
+ out: List[Dict[str, Any]] = []
13
+ for idx, raw in enumerate(data, start=1):
14
+ sample = dict(raw)
15
+ sample_id = str(sample.get("id") or f"q{idx:03d}")
16
+ out.append(
17
+ {
18
+ "id": sample_id,
19
+ "question": str(sample.get("question") or ""),
20
+ "ground_truth": str(sample.get("ground_truth") or ""),
21
+ "reference": str(sample.get("reference") or sample.get("ground_truth") or ""),
22
+ "expected_context_refs": [expected_ref_from_sample(sample)],
23
+ "source_excerpt": str(sample.get("source_excerpt") or ""),
24
+ }
25
+ )
26
+ return out
27
+
28
+
29
+ def prepare_benchmark(input_path: str | Path = BENCHMARK_INPUT, output_path: str | Path = BENCHMARK_JSONL) -> List[Dict[str, Any]]:
30
+ resolved_input = resolve_benchmark_input(input_path)
31
+ data = json.loads(resolved_input.read_text(encoding="utf-8"))
32
+ if not isinstance(data, list):
33
+ raise ValueError("Benchmark input must be a JSON array.")
34
+ samples = prepare_samples([dict(item) for item in data])
35
+ write_jsonl(output_path, samples)
36
+ return samples
37
+
38
+
39
+ def main() -> None:
40
+ parser = argparse.ArgumentParser()
41
+ parser.add_argument("--input", default=str(BENCHMARK_INPUT))
42
+ parser.add_argument("--output", default=str(BENCHMARK_JSONL))
43
+ args = parser.parse_args()
44
+
45
+ resolved_input = resolve_benchmark_input(args.input)
46
+ samples = prepare_benchmark(resolved_input, args.output)
47
+ if str(resolved_input) != str(Path(args.input)):
48
+ print(f"Using benchmark input: {resolved_input}")
49
+ print(f"Prepared {len(samples)} samples -> {args.output}")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
src/evaluation/ragas_lite_judge.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any, Dict, Optional
8
+
9
+ from langchain_core.messages import HumanMessage
10
+
11
+ from src.evaluation.schemas import JUDGE_CACHE, ensure_parent
12
+ from src.rag.openai_clients import get_llm
13
+
14
+
15
+ def safe_json_loads(text: str) -> dict:
16
+ raw = str(text or "").strip()
17
+ if raw.startswith("```"):
18
+ raw = re.sub(r"^```(?:json)?\s*", "", raw, flags=re.IGNORECASE)
19
+ raw = re.sub(r"\s*```$", "", raw).strip()
20
+ try:
21
+ data = json.loads(raw)
22
+ except Exception:
23
+ match = re.search(r"\{.*\}", raw, flags=re.DOTALL)
24
+ if not match:
25
+ raise
26
+ data = json.loads(match.group(0))
27
+ if not isinstance(data, dict):
28
+ raise ValueError("Judge response must be a JSON object.")
29
+ return data
30
+
31
+
32
+ def load_cache(path: str | Path = JUDGE_CACHE) -> Dict[str, Any]:
33
+ fp = Path(path)
34
+ if not fp.exists():
35
+ return {}
36
+ try:
37
+ return dict(json.loads(fp.read_text(encoding="utf-8")))
38
+ except Exception:
39
+ return {}
40
+
41
+
42
+ def save_cache(cache: Dict[str, Any], path: str | Path = JUDGE_CACHE) -> None:
43
+ out = ensure_parent(path)
44
+ out.write_text(json.dumps(cache, ensure_ascii=False, indent=2), encoding="utf-8")
45
+
46
+
47
+ def cache_key(metric_name: str, sample: Dict[str, Any]) -> str:
48
+ payload = {
49
+ "metric_name": metric_name,
50
+ "question": sample.get("question", ""),
51
+ "answer": sample.get("answer", ""),
52
+ "contexts": sample.get("contexts", []),
53
+ "ground_truth": sample.get("ground_truth", ""),
54
+ }
55
+ return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest()
56
+
57
+
58
+ def judge_with_llm(metric_name: str, prompt: str, cache: dict | None = None, *, key: Optional[str] = None, use_cache: bool = True) -> dict:
59
+ if use_cache and cache is not None and key and key in cache:
60
+ cached = dict(cache[key])
61
+ parsed = dict(cached.get("parsed_response") or {})
62
+ parsed.setdefault("cached", True)
63
+ return parsed
64
+
65
+ try:
66
+ llm = get_llm()
67
+ resp = llm.invoke([HumanMessage(content=prompt)])
68
+ raw = str(getattr(resp, "content", "") or "")
69
+ parsed = safe_json_loads(raw)
70
+ parsed.setdefault("score", None)
71
+ parsed["raw_response"] = raw
72
+ if cache is not None and key:
73
+ cache[key] = {
74
+ "metric_name": metric_name,
75
+ "raw_response": raw,
76
+ "parsed_response": {k: v for k, v in parsed.items() if k != "raw_response"},
77
+ }
78
+ return parsed
79
+ except Exception as exc:
80
+ result = {"score": None, "error": str(exc), "reason": f"Judge failed: {exc}"}
81
+ if cache is not None and key:
82
+ cache[key] = {"metric_name": metric_name, "raw_response": "", "parsed_response": result}
83
+ return result
84
+
85
+
86
+ def _contexts_text(sample: Dict[str, Any]) -> str:
87
+ contexts = list(sample.get("contexts") or [])
88
+ return "\n\n".join(f"[Context {idx}] {ctx}" for idx, ctx in enumerate(contexts, start=1))
89
+
90
+
91
+ def faithfulness_lite(sample: dict, use_cache: bool = True, cache: dict | None = None) -> dict:
92
+ metric = "faithfulness_lite"
93
+ prompt = f"""
94
+ Bạn là bộ đánh giá RAG pháp luật Việt Nam.
95
+
96
+ Nhiệm vụ: chấm Faithfulness.
97
+ Chỉ kiểm tra câu trả lời có được hỗ trợ bởi contexts hay không.
98
+
99
+ Không dùng kiến thức bên ngoài.
100
+ Không tự suy luận thêm.
101
+ Nếu answer có thông tin không xuất hiện hoặc không suy ra trực tiếp từ contexts, coi là unsupported.
102
+
103
+ Trả về JSON hợp lệ, không markdown:
104
+
105
+ {{
106
+ "score": 0.0 đến 1.0,
107
+ "unsupported_claims": ["..."],
108
+ "reason": "..."
109
+ }}
110
+
111
+ Cách chấm:
112
+ 1.0 = mọi claim quan trọng đều được context hỗ trợ.
113
+ 0.8 = hầu hết đúng, thiếu chi tiết nhỏ.
114
+ 0.5 = có nhiều ý chưa được context hỗ trợ.
115
+ 0.2 = phần lớn câu trả lời không có căn cứ.
116
+ 0.0 = answer gần như bịa hoặc trái context.
117
+
118
+ Question:
119
+ {sample.get("question", "")}
120
+
121
+ Answer:
122
+ {sample.get("answer", "")}
123
+
124
+ Contexts:
125
+ {_contexts_text(sample)}
126
+ """.strip()
127
+ return judge_with_llm(metric, prompt, cache, key=cache_key(metric, sample), use_cache=use_cache)
128
+
129
+
130
+ def answer_relevancy_lite(sample: dict, use_cache: bool = True, cache: dict | None = None) -> dict:
131
+ metric = "answer_relevancy_lite"
132
+ prompt = f"""
133
+ Bạn là bộ đánh giá RAG pháp luật Việt Nam.
134
+
135
+ Nhiệm vụ: chấm Answer Relevancy.
136
+ Kiểm tra answer có trả lời đúng trọng tâm question không.
137
+
138
+ Không cần kiểm tra đúng/sai pháp lý ở metric này.
139
+ Chỉ đánh giá mức độ liên quan, trực tiếp và không lan man.
140
+
141
+ Trả về JSON hợp lệ:
142
+
143
+ {{
144
+ "score": 0.0 đến 1.0,
145
+ "reason": "..."
146
+ }}
147
+
148
+ Cách chấm:
149
+ 1.0 = trả lời trực tiếp đúng câu hỏi.
150
+ 0.8 = trả lời đúng trọng tâm nhưng còn hơi thiếu.
151
+ 0.5 = có liên quan nhưng lan man hoặc thiếu trọng tâm.
152
+ 0.2 = chỉ liên quan rất ít.
153
+ 0.0 = không trả lời câu hỏi.
154
+
155
+ Question:
156
+ {sample.get("question", "")}
157
+
158
+ Answer:
159
+ {sample.get("answer", "")}
160
+ """.strip()
161
+ return judge_with_llm(metric, prompt, cache, key=cache_key(metric, sample), use_cache=use_cache)
162
+
163
+
164
+ def answer_correctness_lite(sample: dict, use_cache: bool = True, cache: dict | None = None) -> dict:
165
+ metric = "answer_correctness_lite"
166
+ prompt = f"""
167
+ Bạn là bộ đánh giá RAG pháp luật Việt Nam.
168
+
169
+ Nhiệm vụ: chấm Answer Correctness.
170
+ So sánh answer với ground_truth.
171
+
172
+ Chỉ dùng ground_truth làm đáp án chuẩn.
173
+ Không dùng kiến thức bên ngoài.
174
+ Không phạt nếu wording khác nhưng cùng nghĩa.
175
+ Phạt nặng nếu sai văn bản, sai điều/khoản/điểm, sai đối tượng, sai thời hạn, sai điều kiện, sai trách nhiệm hoặc sai nội dung pháp lý chính.
176
+
177
+ Trả về JSON hợp lệ:
178
+
179
+ {{
180
+ "score": 0.0 đến 1.0,
181
+ "missing_points": ["..."],
182
+ "incorrect_points": ["..."],
183
+ "reason": "..."
184
+ }}
185
+
186
+ Cách chấm:
187
+ 1.0 = đúng đầy đủ.
188
+ 0.8 = đúng ý chính, thiếu chi tiết nhỏ.
189
+ 0.5 = đúng một phần nhưng thiếu hoặc sai đáng kể.
190
+ 0.2 = phần lớn sai.
191
+ 0.0 = hoàn toàn sai hoặc không trả lời.
192
+
193
+ Question:
194
+ {sample.get("question", "")}
195
+
196
+ Ground truth:
197
+ {sample.get("ground_truth", "")}
198
+
199
+ Answer:
200
+ {sample.get("answer", "")}
201
+ """.strip()
202
+ return judge_with_llm(metric, prompt, cache, key=cache_key(metric, sample), use_cache=use_cache)
src/evaluation/rule_metrics.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any, Dict, List, Set
5
+
6
+ from src.evaluation.schemas import REFERENCE_FIELDS, norm_key, norm_text
7
+
8
+ DOC_NUMBER_RE = re.compile(r"\b\d{1,4}/\d{4}/[A-ZĐ\-]+|\b\d{1,4}/VBHN-[A-ZĐ\-]+", re.IGNORECASE)
9
+ ARTICLE_RE = re.compile(r"điều\s+(\d+)", re.IGNORECASE)
10
+ CLAUSE_RE = re.compile(r"khoản\s+(\d+)", re.IGNORECASE)
11
+ POINT_RE = re.compile(r"điểm\s+([a-zđ])", re.IGNORECASE)
12
+
13
+ WEIGHTS = {
14
+ "doc_number": 0.40,
15
+ "law_type": 0.10,
16
+ "year": 0.10,
17
+ "article": 0.20,
18
+ "clause": 0.15,
19
+ "point": 0.05,
20
+ }
21
+
22
+ STOPWORDS = {
23
+ "và",
24
+ "của",
25
+ "các",
26
+ "những",
27
+ "trong",
28
+ "cho",
29
+ "về",
30
+ "theo",
31
+ "là",
32
+ "có",
33
+ "được",
34
+ "phải",
35
+ "này",
36
+ "đó",
37
+ "với",
38
+ "một",
39
+ "hoặc",
40
+ "để",
41
+ "tại",
42
+ }
43
+
44
+
45
+ def _expected_refs(sample: Dict[str, Any]) -> List[Dict[str, Any]]:
46
+ return [dict(x) for x in list(sample.get("expected_context_refs") or []) if isinstance(x, dict)]
47
+
48
+
49
+ def _context_metadata(sample: Dict[str, Any]) -> List[Dict[str, Any]]:
50
+ return [dict(x) for x in list(sample.get("context_metadata") or []) if isinstance(x, dict)]
51
+
52
+
53
+ def _norm_doc_number(value: Any) -> str:
54
+ raw = norm_text(value).upper().replace("Đ", "D")
55
+ parts = raw.split("/")
56
+ if parts and parts[0].isdigit():
57
+ parts[0] = str(int(parts[0]))
58
+ return "/".join(parts)
59
+
60
+
61
+ def _tokens(value: Any) -> Set[str]:
62
+ words = re.findall(r"\w+", norm_key(value), flags=re.UNICODE)
63
+ return {word for word in words if len(word) >= 3 and word not in STOPWORDS}
64
+
65
+
66
+ def _gold_text(sample: Dict[str, Any]) -> str:
67
+ return "\n".join(
68
+ norm_text(sample.get(key))
69
+ for key in ("ground_truth", "reference", "source_excerpt")
70
+ if norm_text(sample.get(key))
71
+ )
72
+
73
+
74
+ def _field_match(expected: Dict[str, Any], context_metadata: List[Dict[str, Any]], field: str) -> bool:
75
+ value = norm_key(expected.get(field))
76
+ if not value:
77
+ return True
78
+ for md in context_metadata:
79
+ if field == "doc_number" and _norm_doc_number(md.get(field)) == _norm_doc_number(expected.get(field)):
80
+ return True
81
+ actual = norm_key(md.get(field))
82
+ if actual == value:
83
+ return True
84
+ if field == "law_type" and norm_key(md.get("doc_type")) == value:
85
+ return True
86
+ return False
87
+
88
+
89
+ def context_sufficiency_lite(sample: dict) -> dict:
90
+ contexts = list(sample.get("contexts") or [])
91
+ if not contexts:
92
+ return {"score": 0.0, "matched_fields": [], "missing_fields": [], "warnings": ["No contexts."]}
93
+
94
+ refs = _expected_refs(sample)
95
+ expected_fields = []
96
+ for ref in refs:
97
+ expected_fields.extend([field for field in REFERENCE_FIELDS if norm_text(ref.get(field))])
98
+ expected_fields = list(dict.fromkeys(expected_fields))
99
+ if not expected_fields:
100
+ return {
101
+ "score": None,
102
+ "matched_fields": [],
103
+ "missing_fields": [],
104
+ "warnings": ["No non-empty expected_context_refs fields."],
105
+ }
106
+
107
+ metadata = _context_metadata(sample)
108
+ matched: List[str] = []
109
+ missing: List[str] = []
110
+ for field in expected_fields:
111
+ if any(_field_match(ref, metadata, field) for ref in refs):
112
+ matched.append(field)
113
+ else:
114
+ missing.append(field)
115
+ return {
116
+ "score": len(matched) / max(1, len(expected_fields)),
117
+ "matched_fields": matched,
118
+ "missing_fields": missing,
119
+ "warnings": [],
120
+ }
121
+
122
+
123
+ def retrieval_ref_match_lite(sample: dict) -> dict:
124
+ refs = _expected_refs(sample)
125
+ metadata = _context_metadata(sample)
126
+ expected_fields = []
127
+ for ref in refs:
128
+ expected_fields.extend([field for field in REFERENCE_FIELDS if norm_text(ref.get(field))])
129
+ expected_fields = list(dict.fromkeys(expected_fields))
130
+ if not expected_fields:
131
+ return {"score": None, "matched": {field: None for field in REFERENCE_FIELDS}, "reason": "No expected fields."}
132
+
133
+ total_weight = sum(WEIGHTS[field] for field in expected_fields)
134
+ score = 0.0
135
+ matched: Dict[str, Any] = {field: None for field in REFERENCE_FIELDS}
136
+ for field in expected_fields:
137
+ ok = any(_field_match(ref, metadata, field) for ref in refs)
138
+ matched[field] = ok
139
+ if ok:
140
+ score += WEIGHTS[field]
141
+ normalized = score / max(total_weight, 1e-9)
142
+ hit = [field for field, ok in matched.items() if ok is True]
143
+ miss = [field for field, ok in matched.items() if ok is False]
144
+ return {
145
+ "score": normalized,
146
+ "matched": matched,
147
+ "reason": f"Matched {', '.join(hit) or 'none'}; missing {', '.join(miss) or 'none'}.",
148
+ }
149
+
150
+
151
+ def _context_matches_expected_ref(context_md: Dict[str, Any], refs: List[Dict[str, Any]]) -> bool:
152
+ if not refs:
153
+ return False
154
+ for ref in refs:
155
+ expected_fields = [field for field in REFERENCE_FIELDS if norm_text(ref.get(field))]
156
+ if not expected_fields:
157
+ continue
158
+ if all(_field_match({field: ref.get(field)}, [context_md], field) for field in expected_fields):
159
+ return True
160
+ return False
161
+
162
+
163
+ def context_precision_lite(sample: dict) -> dict:
164
+ contexts = [norm_text(ctx) for ctx in list(sample.get("contexts") or []) if norm_text(ctx)]
165
+ if not contexts:
166
+ return {"score": 0.0, "relevant_contexts": 0, "total_contexts": 0, "warnings": ["No contexts."]}
167
+
168
+ refs = _expected_refs(sample)
169
+ metadata = _context_metadata(sample)
170
+ gold_tokens = _tokens(_gold_text(sample))
171
+ relevant = 0
172
+ details: List[Dict[str, Any]] = []
173
+
174
+ for idx, context in enumerate(contexts):
175
+ md = metadata[idx] if idx < len(metadata) else {}
176
+ metadata_hit = _context_matches_expected_ref(md, refs)
177
+ context_tokens = _tokens(context)
178
+ token_hits = len(context_tokens & gold_tokens)
179
+ overlap = token_hits / max(1, len(gold_tokens)) if gold_tokens else 0.0
180
+ is_relevant = metadata_hit or (token_hits >= 2 and overlap >= 0.18)
181
+ if is_relevant:
182
+ relevant += 1
183
+ details.append(
184
+ {
185
+ "index": idx + 1,
186
+ "relevant": is_relevant,
187
+ "metadata_hit": metadata_hit,
188
+ "gold_token_hits": token_hits,
189
+ "gold_token_overlap": round(overlap, 4),
190
+ }
191
+ )
192
+
193
+ return {
194
+ "score": relevant / max(1, len(contexts)),
195
+ "relevant_contexts": relevant,
196
+ "total_contexts": len(contexts),
197
+ "details": details,
198
+ "warnings": [] if gold_tokens or refs else ["No ground_truth/reference/source_excerpt or expected refs."],
199
+ }
200
+
201
+
202
+ def context_recall_lite(sample: dict) -> dict:
203
+ contexts = [norm_text(ctx) for ctx in list(sample.get("contexts") or []) if norm_text(ctx)]
204
+ if not contexts:
205
+ return {"score": 0.0, "token_recall": 0.0, "metadata_recall": 0.0, "warnings": ["No contexts."]}
206
+
207
+ combined_context = "\n".join(contexts)
208
+ gold_tokens = _tokens(_gold_text(sample))
209
+ if gold_tokens:
210
+ token_recall = len(gold_tokens & _tokens(combined_context)) / max(1, len(gold_tokens))
211
+ else:
212
+ token_recall = None
213
+
214
+ sufficiency = context_sufficiency_lite(sample)
215
+ metadata_recall = sufficiency.get("score")
216
+
217
+ parts = [value for value in (token_recall, metadata_recall) if isinstance(value, (int, float))]
218
+ score = sum(float(value) for value in parts) / len(parts) if parts else None
219
+ return {
220
+ "score": score,
221
+ "token_recall": token_recall,
222
+ "metadata_recall": metadata_recall,
223
+ "warnings": [] if parts else ["No ground truth tokens or expected refs."],
224
+ }
225
+
226
+
227
+ def _extract_answer_refs(answer: str) -> List[str]:
228
+ refs: List[str] = []
229
+ for m in DOC_NUMBER_RE.finditer(answer or ""):
230
+ refs.append(m.group(0).upper())
231
+ for m in ARTICLE_RE.finditer(answer or ""):
232
+ refs.append(f"Điều {m.group(1)}")
233
+ for m in CLAUSE_RE.finditer(answer or ""):
234
+ refs.append(f"Khoản {m.group(1)}")
235
+ for m in POINT_RE.finditer(answer or ""):
236
+ refs.append(f"Điểm {m.group(1).lower()}")
237
+ return list(dict.fromkeys(refs))
238
+
239
+
240
+ def _metadata_supports(ref: str, metadata: List[Dict[str, Any]]) -> bool:
241
+ ref_norm = norm_key(ref)
242
+ for md in metadata:
243
+ if "/" in ref and _norm_doc_number(md.get("doc_number")) == _norm_doc_number(ref):
244
+ return True
245
+ values = [
246
+ md.get("doc_number"),
247
+ md.get("article"),
248
+ md.get("clause"),
249
+ md.get("point"),
250
+ ]
251
+ if any(norm_key(value) == ref_norm for value in values):
252
+ return True
253
+ return False
254
+
255
+
256
+ def citation_support_lite(answer: str, context_metadata: list[dict]) -> dict:
257
+ refs = _extract_answer_refs(answer)
258
+ if not refs:
259
+ return {
260
+ "score": 0.5,
261
+ "supported_references": [],
262
+ "unsupported_references": [],
263
+ "warnings": ["Answer has no explicit citation."],
264
+ }
265
+ metadata = [dict(x) for x in context_metadata if isinstance(x, dict)]
266
+ supported = [ref for ref in refs if _metadata_supports(ref, metadata)]
267
+ unsupported = [ref for ref in refs if ref not in supported]
268
+ return {
269
+ "score": len(supported) / max(1, len(refs)),
270
+ "supported_references": supported,
271
+ "unsupported_references": unsupported,
272
+ "warnings": [],
273
+ }
src/evaluation/run_all.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+ from typing import Any, Dict
6
+
7
+ from src.evaluation.collect_rag_outputs import collect_outputs
8
+ from src.evaluation.metrics_report import render_report
9
+ from src.evaluation.prepare_benchmark import prepare_benchmark
10
+ from src.evaluation.run_ragas_lite import DEFAULT_METRICS, _parse_metrics, run_ragas_lite
11
+ from src.evaluation.schemas import (
12
+ BENCHMARK_INPUT,
13
+ BENCHMARK_JSONL,
14
+ JUDGE_CACHE,
15
+ RAG_OUTPUTS_JSONL,
16
+ RAGAS_LITE_RESULTS,
17
+ resolve_benchmark_input,
18
+ )
19
+ from src.evaluation.validate_benchmark import validate_benchmark
20
+
21
+
22
+ def _print_validation(warnings: list[str], errors: list[str]) -> None:
23
+ for warning in warnings:
24
+ print(f"WARNING: {warning}")
25
+ for error in errors:
26
+ print(f"ERROR: {error}")
27
+
28
+
29
+ def run_all(
30
+ *,
31
+ input_path: str = str(BENCHMARK_INPUT),
32
+ benchmark_jsonl_path: str = str(BENCHMARK_JSONL),
33
+ rag_outputs_path: str = str(RAG_OUTPUTS_JSONL),
34
+ results_path: str = str(RAGAS_LITE_RESULTS),
35
+ top_k: int = 5,
36
+ limit: int | None = None,
37
+ metrics: str = ",".join(DEFAULT_METRICS),
38
+ use_cache: bool = True,
39
+ cache_path: str = str(JUDGE_CACHE),
40
+ ) -> Dict[str, Any]:
41
+ resolved_input = resolve_benchmark_input(input_path)
42
+
43
+ print("[1/5] Validate benchmark")
44
+ ok, errors, warnings = validate_benchmark(resolved_input)
45
+ _print_validation(warnings, errors)
46
+ if not ok:
47
+ raise SystemExit(1)
48
+ print(f"Benchmark valid: {resolved_input}")
49
+
50
+ print("[2/5] Prepare benchmark JSONL")
51
+ samples = prepare_benchmark(resolved_input, benchmark_jsonl_path)
52
+ print(f"Prepared {len(samples)} samples -> {benchmark_jsonl_path}")
53
+
54
+ print("[3/5] Collect RAG outputs")
55
+ rows = collect_outputs(
56
+ benchmark_jsonl_path,
57
+ rag_outputs_path,
58
+ top_k=top_k,
59
+ limit=limit,
60
+ )
61
+ print(f"Collected {len(rows)} RAG outputs -> {rag_outputs_path}")
62
+
63
+ print("[4/5] Run RAGAS-lite")
64
+ result = run_ragas_lite(
65
+ rag_outputs_path,
66
+ results_path,
67
+ limit=None,
68
+ metrics=_parse_metrics(metrics),
69
+ use_cache=use_cache,
70
+ cache_path=cache_path,
71
+ )
72
+ print(f"Evaluated {result['summary']['num_samples']} samples -> {results_path}")
73
+
74
+ print("[5/5] Report")
75
+ report = render_report(results_path)
76
+ print(report)
77
+
78
+ return {
79
+ "benchmark_input": str(Path(resolved_input)),
80
+ "benchmark_jsonl": benchmark_jsonl_path,
81
+ "rag_outputs": rag_outputs_path,
82
+ "results": results_path,
83
+ "num_prepared": len(samples),
84
+ "num_collected": len(rows),
85
+ "num_evaluated": result["summary"]["num_samples"],
86
+ }
87
+
88
+
89
+ def main() -> None:
90
+ parser = argparse.ArgumentParser()
91
+ parser.add_argument("--input", default=str(BENCHMARK_INPUT))
92
+ parser.add_argument("--benchmark-jsonl", default=str(BENCHMARK_JSONL))
93
+ parser.add_argument("--rag-outputs", default=str(RAG_OUTPUTS_JSONL))
94
+ parser.add_argument("--output", default=str(RAGAS_LITE_RESULTS))
95
+ parser.add_argument("--top-k", type=int, default=5)
96
+ parser.add_argument("--limit", type=int, default=None)
97
+ parser.add_argument("--metrics", default=",".join(DEFAULT_METRICS))
98
+ parser.add_argument("--cache", default=str(JUDGE_CACHE))
99
+ parser.add_argument("--no-cache", action="store_true")
100
+ args = parser.parse_args()
101
+
102
+ run_all(
103
+ input_path=args.input,
104
+ benchmark_jsonl_path=args.benchmark_jsonl,
105
+ rag_outputs_path=args.rag_outputs,
106
+ results_path=args.output,
107
+ top_k=args.top_k,
108
+ limit=args.limit,
109
+ metrics=args.metrics,
110
+ use_cache=not args.no_cache,
111
+ cache_path=args.cache,
112
+ )
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
src/evaluation/run_ragas_lite.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Callable, Dict, List
7
+
8
+ from src.evaluation.ragas_lite_judge import (
9
+ answer_correctness_lite,
10
+ answer_relevancy_lite,
11
+ faithfulness_lite,
12
+ load_cache,
13
+ save_cache,
14
+ )
15
+ from src.evaluation.rule_metrics import (
16
+ citation_support_lite,
17
+ context_precision_lite,
18
+ context_recall_lite,
19
+ context_sufficiency_lite,
20
+ retrieval_ref_match_lite,
21
+ )
22
+ from src.evaluation.schemas import JUDGE_CACHE, RAG_OUTPUTS_JSONL, RAGAS_LITE_RESULTS, ensure_parent, read_jsonl
23
+
24
+ LLM_METRICS: Dict[str, Callable[..., dict]] = {
25
+ "faithfulness": faithfulness_lite,
26
+ "answer_relevancy": answer_relevancy_lite,
27
+ "answer_correctness": answer_correctness_lite,
28
+ }
29
+
30
+ RULE_METRICS = {
31
+ "context_precision": context_precision_lite,
32
+ "context_recall": context_recall_lite,
33
+ "context_sufficiency": context_sufficiency_lite,
34
+ "citation_support": lambda sample: citation_support_lite(str(sample.get("answer") or ""), list(sample.get("context_metadata") or [])),
35
+ "retrieval_ref_match": retrieval_ref_match_lite,
36
+ }
37
+
38
+ METRIC_OUTPUT_NAMES = {
39
+ "faithfulness": "faithfulness_lite",
40
+ "answer_relevancy": "answer_relevancy_lite",
41
+ "answer_correctness": "answer_correctness_lite",
42
+ "context_precision": "context_precision_lite",
43
+ "context_recall": "context_recall_lite",
44
+ "context_sufficiency": "context_sufficiency_lite",
45
+ "citation_support": "citation_support_lite",
46
+ "retrieval_ref_match": "retrieval_ref_match_lite",
47
+ }
48
+
49
+ DEFAULT_METRICS = list(METRIC_OUTPUT_NAMES.keys())
50
+
51
+
52
+ def _parse_metrics(raw: str) -> List[str]:
53
+ if not raw:
54
+ return DEFAULT_METRICS
55
+ metrics = [part.strip() for part in raw.split(",") if part.strip()]
56
+ unknown = [metric for metric in metrics if metric not in METRIC_OUTPUT_NAMES]
57
+ if unknown:
58
+ raise ValueError(f"Unknown metrics: {', '.join(unknown)}")
59
+ return metrics
60
+
61
+
62
+ def _mean(values: List[Any]) -> float | None:
63
+ nums = [float(v) for v in values if isinstance(v, (int, float))]
64
+ if not nums:
65
+ return None
66
+ return sum(nums) / len(nums)
67
+
68
+
69
+ def run_ragas_lite(
70
+ input_path: str = str(RAG_OUTPUTS_JSONL),
71
+ output_path: str = str(RAGAS_LITE_RESULTS),
72
+ *,
73
+ limit: int | None = 25,
74
+ metrics: List[str] | None = None,
75
+ use_cache: bool = False,
76
+ cache_path: str = str(JUDGE_CACHE),
77
+ ) -> Dict[str, Any]:
78
+ selected = metrics or DEFAULT_METRICS
79
+ samples = read_jsonl(input_path)
80
+ if limit is not None:
81
+ samples = samples[: max(0, int(limit))]
82
+
83
+ cache = load_cache(cache_path) if use_cache else {}
84
+ result_samples: List[Dict[str, Any]] = []
85
+
86
+ for sample in samples:
87
+ metric_results: Dict[str, Dict[str, Any]] = {}
88
+ for metric in selected:
89
+ out_name = METRIC_OUTPUT_NAMES[metric]
90
+ try:
91
+ if metric in LLM_METRICS:
92
+ metric_results[out_name] = LLM_METRICS[metric](sample, use_cache=use_cache, cache=cache)
93
+ else:
94
+ metric_results[out_name] = RULE_METRICS[metric](sample)
95
+ except Exception as exc:
96
+ metric_results[out_name] = {"score": None, "error": str(exc), "reason": f"Metric failed: {exc}"}
97
+
98
+ result_samples.append(
99
+ {
100
+ "id": sample.get("id"),
101
+ "question": sample.get("question", ""),
102
+ "answer": sample.get("answer", ""),
103
+ "ground_truth": sample.get("ground_truth", ""),
104
+ "latency_ms": sample.get("latency_ms"),
105
+ "metrics": metric_results,
106
+ }
107
+ )
108
+ if use_cache:
109
+ save_cache(cache, cache_path)
110
+
111
+ summary_metrics: Dict[str, Any] = {}
112
+ for metric in selected:
113
+ out_name = METRIC_OUTPUT_NAMES[metric]
114
+ summary_metrics[out_name] = _mean([s["metrics"].get(out_name, {}).get("score") for s in result_samples])
115
+
116
+ output = {
117
+ "summary": {
118
+ "num_samples": len(result_samples),
119
+ "metrics": summary_metrics,
120
+ },
121
+ "samples": result_samples,
122
+ }
123
+ ensure_parent(output_path).write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding="utf-8")
124
+ return output
125
+
126
+
127
+ def main() -> None:
128
+ parser = argparse.ArgumentParser()
129
+ parser.add_argument("--input", default=str(RAG_OUTPUTS_JSONL))
130
+ parser.add_argument("--output", default=str(RAGAS_LITE_RESULTS))
131
+ parser.add_argument("--limit", type=int, default=25)
132
+ parser.add_argument("--use-cache", action="store_true")
133
+ parser.add_argument("--cache", default=str(JUDGE_CACHE))
134
+ parser.add_argument("--metrics", default=",".join(DEFAULT_METRICS))
135
+ args = parser.parse_args()
136
+
137
+ result = run_ragas_lite(
138
+ args.input,
139
+ args.output,
140
+ limit=args.limit,
141
+ metrics=_parse_metrics(args.metrics),
142
+ use_cache=args.use_cache,
143
+ cache_path=args.cache,
144
+ )
145
+ print(f"Evaluated {result['summary']['num_samples']} samples -> {args.output}")
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()
src/evaluation/schemas.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Dict, Iterable, List
5
+
6
+ BENCHMARK_INPUT = Path("data/eval/legal_rag_benchmark_25.json")
7
+ BENCHMARK_INPUT_FALLBACKS = [
8
+ Path("outputs/benchmark/ragas_gold_25_manual.json"),
9
+ Path("outputs/benchmark/ragas_gold_25.json"),
10
+ ]
11
+ BENCHMARK_JSONL = Path("data/eval/legal_benchmark_25.jsonl")
12
+ RAG_OUTPUTS_JSONL = Path("data/eval/rag_outputs.jsonl")
13
+ RAGAS_LITE_RESULTS = Path("data/eval/ragas_lite_results.json")
14
+ JUDGE_CACHE = Path("data/eval/judge_cache.json")
15
+
16
+ REQUIRED_BENCHMARK_FIELDS = [
17
+ "question",
18
+ "ground_truth",
19
+ "reference",
20
+ "expected_doc_number",
21
+ "expected_law_type",
22
+ "expected_year",
23
+ "source_excerpt",
24
+ ]
25
+
26
+ OPTIONAL_REFERENCE_FIELDS = [
27
+ "expected_article",
28
+ "expected_clause",
29
+ "expected_point",
30
+ ]
31
+
32
+ REFERENCE_FIELDS = [
33
+ "doc_number",
34
+ "law_type",
35
+ "year",
36
+ "article",
37
+ "clause",
38
+ "point",
39
+ ]
40
+
41
+ PLACEHOLDER_PATTERNS = [
42
+ "Câu hỏi benchmark số",
43
+ "Đáp án chuẩn cho câu hỏi benchmark số",
44
+ "Trích đoạn nguồn cho câu hỏi benchmark số",
45
+ ]
46
+
47
+
48
+ def ensure_parent(path: str | Path) -> Path:
49
+ out = Path(path)
50
+ out.parent.mkdir(parents=True, exist_ok=True)
51
+ return out
52
+
53
+
54
+ def resolve_benchmark_input(path: str | Path = BENCHMARK_INPUT) -> Path:
55
+ requested = Path(path)
56
+ if requested.exists():
57
+ return requested
58
+ if requested == BENCHMARK_INPUT:
59
+ for fallback in BENCHMARK_INPUT_FALLBACKS:
60
+ if fallback.exists():
61
+ return fallback
62
+ return requested
63
+
64
+
65
+ def norm_text(value: Any) -> str:
66
+ return " ".join(str(value or "").split()).strip()
67
+
68
+
69
+ def norm_key(value: Any) -> str:
70
+ return norm_text(value).lower()
71
+
72
+
73
+ def read_jsonl(path: str | Path) -> List[Dict[str, Any]]:
74
+ items: List[Dict[str, Any]] = []
75
+ with Path(path).open("r", encoding="utf-8") as f:
76
+ for line in f:
77
+ line = line.strip()
78
+ if line:
79
+ items.append(dict(__import__("json").loads(line)))
80
+ return items
81
+
82
+
83
+ def write_jsonl(path: str | Path, items: Iterable[Dict[str, Any]]) -> None:
84
+ import json
85
+
86
+ out = ensure_parent(path)
87
+ with out.open("w", encoding="utf-8") as f:
88
+ for item in items:
89
+ f.write(json.dumps(item, ensure_ascii=False) + "\n")
90
+
91
+
92
+ def expected_ref_from_sample(sample: Dict[str, Any]) -> Dict[str, str]:
93
+ return {
94
+ "doc_number": norm_text(sample.get("expected_doc_number")),
95
+ "law_type": norm_text(sample.get("expected_law_type")),
96
+ "year": norm_text(sample.get("expected_year")),
97
+ "article": norm_text(sample.get("expected_article")),
98
+ "clause": norm_text(sample.get("expected_clause")),
99
+ "point": norm_text(sample.get("expected_point")),
100
+ }
src/evaluation/validate_benchmark.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Tuple
7
+
8
+ from src.evaluation.schemas import (
9
+ BENCHMARK_INPUT,
10
+ OPTIONAL_REFERENCE_FIELDS,
11
+ PLACEHOLDER_PATTERNS,
12
+ REQUIRED_BENCHMARK_FIELDS,
13
+ norm_text,
14
+ resolve_benchmark_input,
15
+ )
16
+
17
+
18
+ def validate_benchmark(path: str | Path = BENCHMARK_INPUT) -> Tuple[bool, List[str], List[str]]:
19
+ errors: List[str] = []
20
+ warnings: List[str] = []
21
+ fp = resolve_benchmark_input(path)
22
+ try:
23
+ data = json.loads(fp.read_text(encoding="utf-8"))
24
+ except Exception as exc:
25
+ return False, [f"Failed to read JSON: {exc}"], warnings
26
+
27
+ if not isinstance(data, list):
28
+ return False, ["Benchmark input must be a JSON array."], warnings
29
+ if not data:
30
+ errors.append("Benchmark must contain at least 1 sample.")
31
+
32
+ for idx, item in enumerate(data, start=1):
33
+ if not isinstance(item, dict):
34
+ errors.append(f"Sample {idx} must be an object.")
35
+ continue
36
+ for field in REQUIRED_BENCHMARK_FIELDS:
37
+ if field not in item:
38
+ errors.append(f"Sample {idx} missing required field: {field}")
39
+ elif norm_text(item.get(field)) == "":
40
+ errors.append(f"Sample {idx} has empty required field: {field}")
41
+ for field in OPTIONAL_REFERENCE_FIELDS:
42
+ if field not in item:
43
+ warnings.append(f"Sample {idx} missing optional field: {field}; treating as empty.")
44
+ joined = "\n".join(str(item.get(k) or "") for k in item)
45
+ for pattern in PLACEHOLDER_PATTERNS:
46
+ if pattern in joined:
47
+ warnings.append(f"Sample {idx} appears to contain placeholder text: {pattern}")
48
+
49
+ return not errors, errors, warnings
50
+
51
+
52
+ def main() -> None:
53
+ parser = argparse.ArgumentParser()
54
+ parser.add_argument("--input", default=str(BENCHMARK_INPUT))
55
+ args = parser.parse_args()
56
+
57
+ resolved = resolve_benchmark_input(args.input)
58
+ ok, errors, warnings = validate_benchmark(resolved)
59
+ for warning in warnings:
60
+ print(f"WARNING: {warning}")
61
+ if not ok:
62
+ for error in errors:
63
+ print(f"ERROR: {error}")
64
+ raise SystemExit(1)
65
+ if str(resolved) != str(Path(args.input)):
66
+ print(f"Using benchmark input: {resolved}")
67
+ data = json.loads(resolved.read_text(encoding="utf-8"))
68
+ sample_count = len(data) if isinstance(data, list) else 0
69
+ print(f"Benchmark valid: {sample_count} samples.")
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()
src/rag/agent/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Agent workflow helpers for the simple RRF legal RAG pipeline."""
src/rag/agent/nodes.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict
4
+
5
+ from src.rag.citation_validator import validate_citations
6
+ from src.rag.context_grader import grade_context
7
+ from src.rag.qa_engine import answer_with_rag
8
+ from src.rag.retrieval_pipeline_simple import analyze_query, retrieve_with_graph_simple
9
+
10
+
11
+ def analyze_question(state: Dict[str, Any]) -> Dict[str, Any]:
12
+ return {"query_profile": analyze_query(str(state.get("question") or ""))}
13
+
14
+
15
+ def retrieve_simple_rrf(state: Dict[str, Any]) -> Dict[str, Any]:
16
+ result = retrieve_with_graph_simple(
17
+ question=str(state.get("question") or ""),
18
+ graph=dict(state.get("graph") or {}),
19
+ filters=dict(state.get("filters") or {}),
20
+ )
21
+ return {
22
+ "retrieval_result": result,
23
+ "passages": list(result.get("passages") or []),
24
+ "query_profile": dict(result.get("query_profile") or state.get("query_profile") or {}),
25
+ }
26
+
27
+
28
+ def grade_context_node(state: Dict[str, Any]) -> Dict[str, Any]:
29
+ context_grade = grade_context(
30
+ question=str(state.get("question") or ""),
31
+ query_profile=dict(state.get("query_profile") or {}),
32
+ passages=list(state.get("passages") or []),
33
+ )
34
+ retrieval_result = dict(state.get("retrieval_result") or {})
35
+ retrieval_result["context_grade"] = context_grade
36
+ retrieval_result["insufficient_context"] = context_grade.get("status") == "insufficient"
37
+ return {"context_grade": context_grade, "retrieval_result": retrieval_result}
38
+
39
+
40
+ def generate_or_refuse(state: Dict[str, Any]) -> Dict[str, Any]:
41
+ context_grade = dict(state.get("context_grade") or {})
42
+ if context_grade.get("status") == "insufficient":
43
+ return {
44
+ "answer": "Ngữ cảnh truy xuất hiện tại chưa đủ căn cứ để trả lời chính xác câu hỏi này.",
45
+ "sources": [],
46
+ }
47
+ response = answer_with_rag(
48
+ question=str(state.get("question") or ""),
49
+ retrieval_result=dict(state.get("retrieval_result") or {}),
50
+ )
51
+ return {
52
+ "answer": response.answer,
53
+ "sources": [source.model_dump() for source in response.sources],
54
+ }
55
+
56
+
57
+ def validate_citation_node(state: Dict[str, Any]) -> Dict[str, Any]:
58
+ sources = list(state.get("passages") or state.get("sources") or [])
59
+ validation = validate_citations(str(state.get("answer") or ""), sources)
60
+ return {"citation_validation": validation}
src/rag/agent/state.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, List, Optional, TypedDict
4
+
5
+
6
+ class LegalRagState(TypedDict, total=False):
7
+ question: str
8
+ graph: Dict[str, Any]
9
+ filters: Dict[str, Any]
10
+ query_profile: Dict[str, Any]
11
+ retrieval_result: Dict[str, Any]
12
+ passages: List[Dict[str, Any]]
13
+ context_grade: Dict[str, Any]
14
+ answer: str
15
+ sources: List[Dict[str, Any]]
16
+ citation_validation: Dict[str, Any]
17
+ error: Optional[str]
src/rag/agent/workflow.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from src.rag.agent.nodes import (
4
+ analyze_question,
5
+ generate_or_refuse,
6
+ grade_context_node,
7
+ retrieve_simple_rrf,
8
+ validate_citation_node,
9
+ )
10
+ from src.rag.agent.state import LegalRagState
11
+
12
+
13
+ def build_workflow():
14
+ from langgraph.graph import END, START, StateGraph
15
+
16
+ graph = StateGraph(LegalRagState)
17
+ graph.add_node("analyze_question", analyze_question)
18
+ graph.add_node("retrieve_simple_rrf", retrieve_simple_rrf)
19
+ graph.add_node("grade_context", grade_context_node)
20
+ graph.add_node("generate_or_refuse", generate_or_refuse)
21
+ graph.add_node("validate_citation", validate_citation_node)
22
+
23
+ graph.add_edge(START, "analyze_question")
24
+ graph.add_edge("analyze_question", "retrieve_simple_rrf")
25
+ graph.add_edge("retrieve_simple_rrf", "grade_context")
26
+ graph.add_edge("grade_context", "generate_or_refuse")
27
+ graph.add_edge("generate_or_refuse", "validate_citation")
28
+ graph.add_edge("validate_citation", END)
29
+ return graph.compile()
src/rag/bm25_corpus.py CHANGED
@@ -6,7 +6,7 @@ from pathlib import Path
6
  from typing import Any, Dict, List
7
 
8
  from src.rag.chunking_legal import legal_chunk
9
- from src.rag.hybrid import tokenize
10
  from src.utils.loader import load_document
11
 
12
 
@@ -52,7 +52,7 @@ def build_bm25_stats_from_texts(texts: List[str]) -> Dict[str, Any]:
52
  df: Dict[str, int] = {}
53
 
54
  for text in texts:
55
- tokens = tokenize(text)
56
  if not tokens:
57
  continue
58
  tokenized_docs.append(tokens)
 
6
  from typing import Any, Dict, List
7
 
8
  from src.rag.chunking_legal import legal_chunk
9
+ from src.rag.hybrid import tokenize_vi
10
  from src.utils.loader import load_document
11
 
12
 
 
52
  df: Dict[str, int] = {}
53
 
54
  for text in texts:
55
+ tokens = tokenize_vi(text)
56
  if not tokens:
57
  continue
58
  tokenized_docs.append(tokens)
src/rag/citation_validator.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any, Dict, List
5
+
6
+ _ARTICLE_RE = re.compile(r"điều\s+(\d+)", re.IGNORECASE)
7
+ _CLAUSE_RE = re.compile(r"khoản\s+(\d+)", re.IGNORECASE)
8
+ _POINT_RE = re.compile(r"điểm\s+([a-zđ])", re.IGNORECASE)
9
+ _DOC_NUMBER_RE = re.compile(r"\b\d{1,4}/\d{4}/[A-ZĐ\-]+\b", re.IGNORECASE)
10
+
11
+
12
+ def _norm_space(text: Any) -> str:
13
+ return " ".join(str(text or "").split()).strip()
14
+
15
+
16
+ def _norm_key(text: Any) -> str:
17
+ return _norm_space(text).lower()
18
+
19
+
20
+ def _source_values(sources: List[Dict[str, Any]], key: str) -> set[str]:
21
+ aliases = {
22
+ "doc_number": ("doc_number",),
23
+ "article": ("article",),
24
+ "clause": ("clause",),
25
+ "point": ("point",),
26
+ }
27
+ values: set[str] = set()
28
+ for source in sources:
29
+ md = dict(source.get("metadata") or {})
30
+ merged = {**md, **source}
31
+ for candidate_key in aliases.get(key, (key,)):
32
+ value = merged.get(candidate_key)
33
+ if value not in (None, ""):
34
+ values.add(_norm_key(value))
35
+ return values
36
+
37
+
38
+ def _refs_from_answer(answer: str) -> Dict[str, List[str]]:
39
+ text = _norm_space(answer)
40
+ return {
41
+ "article": [f"Điều {m.group(1)}" for m in _ARTICLE_RE.finditer(text)],
42
+ "clause": [f"Khoản {m.group(1)}" for m in _CLAUSE_RE.finditer(text)],
43
+ "point": [f"Điểm {m.group(1).lower()}" for m in _POINT_RE.finditer(text)],
44
+ "doc_number": [m.group(0).upper() for m in _DOC_NUMBER_RE.finditer(text)],
45
+ }
46
+
47
+
48
+ def validate_citations(answer: str, sources: List[Dict[str, Any]]) -> Dict[str, Any]:
49
+ refs = _refs_from_answer(answer)
50
+ unsupported: List[Dict[str, str]] = []
51
+ warnings: List[str] = []
52
+
53
+ for key, labels in refs.items():
54
+ source_values = _source_values(sources, key)
55
+ for label in labels:
56
+ if _norm_key(label) not in source_values:
57
+ unsupported.append({"type": key, "reference": label})
58
+
59
+ if unsupported:
60
+ warnings.append("Answer references legal citations not present in source metadata.")
61
+
62
+ return {
63
+ "valid": not unsupported,
64
+ "warnings": warnings,
65
+ "unsupported_references": unsupported,
66
+ }
src/rag/context_grader.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any, Dict, List
5
+
6
+ from src.rag.retrieval_pipeline_simple import analyze_query
7
+
8
+ _LEGAL_REASONING_CUES = [
9
+ "ai có lỗi",
10
+ "bên nào sai",
11
+ "ai chịu trách nhiệm",
12
+ "trách nhiệm thuộc về ai",
13
+ "lỗi trong va chạm",
14
+ ]
15
+ _RELEVANCE_TERMS = [
16
+ "mức phạt",
17
+ "xử phạt",
18
+ "thủ tục",
19
+ "điều kiện",
20
+ "trách nhiệm",
21
+ "hiệu lực",
22
+ "không chấp hành",
23
+ "tín hiệu giao thông",
24
+ "đèn đỏ",
25
+ "va chạm",
26
+ ]
27
+
28
+
29
+ def _norm_space(text: Any) -> str:
30
+ return " ".join(str(text or "").split()).strip()
31
+
32
+
33
+ def _norm_key(text: Any) -> str:
34
+ return _norm_space(text).lower()
35
+
36
+
37
+ def _source_text(passages: List[Dict[str, Any]]) -> str:
38
+ return "\n".join(_norm_space(p.get("text") or p.get("local_text") or p.get("snippet") or "") for p in passages).lower()
39
+
40
+
41
+ def _metadata_matches(passages: List[Dict[str, Any]], key: str, expected: Any) -> bool:
42
+ if expected in (None, ""):
43
+ return True
44
+ aliases = {
45
+ "law_type": ("law_type", "doc_type"),
46
+ "doc_number": ("doc_number",),
47
+ "article": ("article",),
48
+ "clause": ("clause",),
49
+ "point": ("point",),
50
+ }
51
+ for passage in passages:
52
+ md = dict(passage.get("metadata") or {})
53
+ for candidate_key in aliases.get(key, (key,)):
54
+ value = md.get(candidate_key)
55
+ if value in (None, ""):
56
+ continue
57
+ if _norm_key(value) == _norm_key(expected):
58
+ return True
59
+ return False
60
+
61
+
62
+ def _has_relevant_text(question: str, passages: List[Dict[str, Any]]) -> bool:
63
+ hay = _source_text(passages)
64
+ q = _norm_key(question)
65
+ if not hay:
66
+ return False
67
+ if any(term in hay for term in _RELEVANCE_TERMS if term in q or term in hay):
68
+ return True
69
+ tokens = [tok for tok in re.findall(r"\w+", q, flags=re.UNICODE) if len(tok) >= 4]
70
+ if not tokens:
71
+ return bool(hay)
72
+ hits = sum(1 for tok in set(tokens) if tok in hay)
73
+ return hits >= max(1, min(3, len(set(tokens)) // 4))
74
+
75
+
76
+ def _needs_legal_reasoning(question: str) -> bool:
77
+ q = _norm_key(question)
78
+ return any(cue in q for cue in _LEGAL_REASONING_CUES)
79
+
80
+
81
+ def grade_context(question: str, query_profile: Dict[str, Any], passages: List[Dict[str, Any]]) -> Dict[str, Any]:
82
+ if not query_profile:
83
+ query_profile = analyze_query(question)
84
+
85
+ base = {
86
+ "status": "insufficient",
87
+ "reason": "",
88
+ "matched_doc_number": False,
89
+ "matched_article": False,
90
+ "matched_clause": False,
91
+ "matched_point": False,
92
+ "has_relevant_text": False,
93
+ "allow_reasoning": False,
94
+ }
95
+
96
+ if not passages:
97
+ base["reason"] = "no_passages"
98
+ return base
99
+
100
+ base["matched_doc_number"] = _metadata_matches(passages, "doc_number", query_profile.get("doc_number"))
101
+ base["matched_article"] = _metadata_matches(passages, "article", query_profile.get("article"))
102
+ base["matched_clause"] = _metadata_matches(passages, "clause", query_profile.get("clause"))
103
+ base["matched_point"] = _metadata_matches(passages, "point", query_profile.get("point"))
104
+ base["has_relevant_text"] = _has_relevant_text(question, passages)
105
+
106
+ if query_profile.get("doc_number") and not base["matched_doc_number"]:
107
+ base["reason"] = "requested_doc_number_not_found"
108
+ return base
109
+ if query_profile.get("article") and not base["matched_article"]:
110
+ base["reason"] = "requested_article_not_found"
111
+ return base
112
+ if query_profile.get("clause") and not base["matched_clause"]:
113
+ base["reason"] = "requested_clause_not_found"
114
+ return base
115
+ if query_profile.get("point") and not base["matched_point"]:
116
+ base["reason"] = "requested_point_not_found"
117
+ return base
118
+
119
+ if _needs_legal_reasoning(question) and base["has_relevant_text"]:
120
+ base["status"] = "needs_reasoning"
121
+ base["allow_reasoning"] = True
122
+ base["reason"] = "situation_question_with_relevant_rules"
123
+ return base
124
+
125
+ if base["has_relevant_text"]:
126
+ base["status"] = "sufficient"
127
+ base["allow_reasoning"] = False
128
+ base["reason"] = "matched_retrieved_context"
129
+ return base
130
+
131
+ base["status"] = "insufficient"
132
+ base["reason"] = "no_relevant_text"
133
+ return base
src/rag/hybrid.py CHANGED
@@ -43,11 +43,52 @@ def _ngrams(tokens: List[str], n: int) -> List[str]:
43
  return [" ".join(tokens[i:i+n]) for i in range(len(tokens) - n + 1)]
44
 
45
 
46
- def tokenize(text: str) -> List[str]:
47
  raw = _norm_space(text).lower()
48
- base = [tok for tok in TOKEN_RE.findall(raw) if tok.strip()]
49
- grams = _ngrams(base, 2) + _ngrams(base, 3)
50
- return base + grams + _legal_reference_tokens(raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
 
53
  def extract_topic_phrases(question: str) -> List[str]:
 
43
  return [" ".join(tokens[i:i+n]) for i in range(len(tokens) - n + 1)]
44
 
45
 
46
+ def regex_tokenize(text: str) -> List[str]:
47
  raw = _norm_space(text).lower()
48
+ return [tok for tok in TOKEN_RE.findall(raw) if tok.strip()]
49
+
50
+
51
+ def _pyvi_tokenize(raw: str) -> Optional[List[str]]:
52
+ try:
53
+ from pyvi import ViTokenizer # type: ignore
54
+ except Exception:
55
+ return None
56
+ try:
57
+ segmented = ViTokenizer.tokenize(raw)
58
+ except Exception:
59
+ return None
60
+ tokens = [tok.strip() for tok in segmented.split() if tok.strip()]
61
+ return tokens or None
62
+
63
+
64
+ def _selected_ngrams(tokens: List[str]) -> List[str]:
65
+ clean = [tok for tok in tokens if tok and tok not in STOPWORDS]
66
+ if not clean:
67
+ return []
68
+ grams: List[str] = []
69
+ for gram in _ngrams(clean, 2):
70
+ if any("_" in part for part in gram.split()):
71
+ continue
72
+ grams.append(gram)
73
+ for gram in _ngrams(clean, 3):
74
+ parts = gram.split()
75
+ if any("_" in part for part in parts):
76
+ continue
77
+ if len([p for p in parts if p not in STOPWORDS]) >= 2:
78
+ grams.append(gram)
79
+ return grams
80
+
81
+
82
+ def tokenize_vi(text: str) -> List[str]:
83
+ raw = _norm_space(text).lower()
84
+ if not raw:
85
+ return []
86
+ base = _pyvi_tokenize(raw) or regex_tokenize(raw)
87
+ return base + _legal_reference_tokens(raw) + _selected_ngrams(base)
88
+
89
+
90
+ def tokenize(text: str) -> List[str]:
91
+ return tokenize_vi(text)
92
 
93
 
94
  def extract_topic_phrases(question: str) -> List[str]:
src/rag/qa_engine.py CHANGED
@@ -22,6 +22,26 @@ Nguyên tắc bắt buộc:
22
  - Khi có thể, nêu căn cứ theo văn bản, điều, khoản, điểm hoặc vị trí tương ứng.
23
  """.strip()
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  DOC_SCOPE_SUMMARY_TRIGGERS = [
26
  "quy định về vấn đề gì",
27
  "quy định về gì",
@@ -245,8 +265,9 @@ Nếu có thể, nêu căn cứ theo văn bản và vị trí tương ứng.
245
  def answer_with_rag(question: str, retrieval_result: Dict[str, Any]) -> ChatResponse:
246
  passages = list(retrieval_result.get("passages") or [])
247
  insufficient = bool(retrieval_result.get("insufficient_context"))
 
248
 
249
- if insufficient or not passages:
250
  return ChatResponse(
251
  answer="Ngữ cảnh truy xuất hiện tại chưa đủ căn cứ để trả lời chính xác câu hỏi này.",
252
  sources=[],
@@ -258,7 +279,11 @@ def answer_with_rag(question: str, retrieval_result: Dict[str, Any]) -> ChatResp
258
  llm = get_llm()
259
  resp = llm.invoke(
260
  [
261
- SystemMessage(content=BASE_SYSTEM_PROMPT),
 
 
 
 
262
  HumanMessage(content=user_prompt),
263
  ]
264
  )
 
22
  - Khi có thể, nêu căn cứ theo văn bản, điều, khoản, điểm hoặc vị trí tương ứng.
23
  """.strip()
24
 
25
+ LEGAL_REASONING_SYSTEM_PROMPT = """
26
+ Bạn là trợ lý trả lời pháp luật Việt Nam.
27
+
28
+ Nguyên tắc bắt buộc:
29
+ - Chỉ sử dụng context đã truy xuất.
30
+ - Không bịa số tiền phạt, điều/khoản/điểm, mức trừ điểm, thời hạn hoặc thủ tục nếu context không có.
31
+ - Nếu context không đủ, nói rõ phần nào chưa đủ căn cứ.
32
+ - Được phép suy luận pháp lý thận trọng khi câu hỏi yêu cầu đánh giá tình huống.
33
+ - Với câu hỏi ai có lỗi, bên nào sai hoặc ai chịu trách nhiệm trong va chạm: liệt kê hành vi từng bên từ câu hỏi, đối chiếu từng hành vi với quy định được truy xuất, kết luận lỗi có thể là lỗi đơn hoặc lỗi hỗn hợp, và lưu ý tỷ lệ lỗi/trách nhiệm cuối cùng do cơ quan có thẩm quyền xác định.
34
+ - Không kết luận chắc chắn nếu context chỉ hỗ trợ một phần.
35
+ - Nếu có nhiều khả năng, trình bày theo dạng nếu... thì...
36
+ - Khi trả lời, nêu căn cứ theo văn bản/Điều/Khoản/Điểm nếu source có metadata.
37
+ - Nếu answer cần citation nhưng sources không có citation rõ, nói “chưa đủ căn cứ trong dữ liệu truy xuất”.
38
+ - Không dùng kiến thức ngoài context để thêm mức phạt hoặc điều luật.
39
+ - Không tự tạo văn bản pháp luật không có trong sources.
40
+ - Không tự suy ra số điều/khoản/điểm.
41
+ - Không trả lời lan man ngoài câu hỏi.
42
+ - Ưu tiên trả lời ngắn gọn, trực tiếp, có căn cứ.
43
+ """.strip()
44
+
45
  DOC_SCOPE_SUMMARY_TRIGGERS = [
46
  "quy định về vấn đề gì",
47
  "quy định về gì",
 
265
  def answer_with_rag(question: str, retrieval_result: Dict[str, Any]) -> ChatResponse:
266
  passages = list(retrieval_result.get("passages") or [])
267
  insufficient = bool(retrieval_result.get("insufficient_context"))
268
+ context_grade = dict(retrieval_result.get("context_grade") or {})
269
 
270
+ if insufficient or context_grade.get("status") == "insufficient" or not passages:
271
  return ChatResponse(
272
  answer="Ngữ cảnh truy xuất hiện tại chưa đủ căn cứ để trả lời chính xác câu hỏi này.",
273
  sources=[],
 
279
  llm = get_llm()
280
  resp = llm.invoke(
281
  [
282
+ SystemMessage(
283
+ content=LEGAL_REASONING_SYSTEM_PROMPT
284
+ if context_grade.get("status") == "needs_reasoning"
285
+ else BASE_SYSTEM_PROMPT
286
+ ),
287
  HumanMessage(content=user_prompt),
288
  ]
289
  )
src/rag/rerank_cross.py CHANGED
@@ -4,22 +4,32 @@ import logging
4
  import re
5
  from typing import Any, Dict, List
6
 
7
- from sentence_transformers import CrossEncoder
8
-
9
  from src.app.settings import settings
10
 
11
  logger = logging.getLogger(__name__)
12
- _ce: CrossEncoder | None = None
 
13
 
14
 
15
- def get_cross_encoder() -> CrossEncoder:
16
- global _ce
 
 
 
 
17
  if _ce is None:
18
- _ce = CrossEncoder(
19
- settings.rerank_model,
20
- device=settings.rerank_device,
21
- max_length=512,
22
- )
 
 
 
 
 
 
 
23
  return _ce
24
 
25
 
@@ -58,19 +68,27 @@ def cross_rerank(question: str, passages: List[Dict[str, Any]], top_n: int) -> L
58
 
59
  question = _norm_space(question)
60
  ce = get_cross_encoder()
 
 
61
 
62
  pairs = []
63
- for p in passages:
 
 
64
  rerank_text = build_anchor_rerank_text(p)
65
  pairs.append((question, rerank_text))
66
 
67
- scores = ce.predict(pairs)
 
 
 
 
68
 
69
  rescored: List[Dict[str, Any]] = []
70
- for p, score in zip(passages, scores):
71
  item = dict(p)
72
  item["cross_score"] = float(score)
73
  rescored.append(item)
74
 
75
  rescored.sort(key=lambda x: float(x.get("cross_score", 0.0)), reverse=True)
76
- return rescored[: max(1, int(top_n or 1))]
 
4
  import re
5
  from typing import Any, Dict, List
6
 
 
 
7
  from src.app.settings import settings
8
 
9
  logger = logging.getLogger(__name__)
10
+ _ce: Any = None
11
+ _load_failed = False
12
 
13
 
14
+ def get_cross_encoder() -> Any:
15
+ global _ce, _load_failed
16
+ if not bool(getattr(settings, "enable_reranker", False)):
17
+ return None
18
+ if _load_failed:
19
+ return None
20
  if _ce is None:
21
+ try:
22
+ from sentence_transformers import CrossEncoder
23
+
24
+ _ce = CrossEncoder(
25
+ settings.rerank_model,
26
+ device=settings.rerank_device,
27
+ max_length=512,
28
+ )
29
+ except Exception as exc:
30
+ _load_failed = True
31
+ logger.warning("Reranker disabled after model load failure: %s", exc)
32
+ return None
33
  return _ce
34
 
35
 
 
68
 
69
  question = _norm_space(question)
70
  ce = get_cross_encoder()
71
+ if ce is None:
72
+ return passages[: max(1, int(top_n or len(passages)))]
73
 
74
  pairs = []
75
+ input_top_k = max(1, int(getattr(settings, "rerank_input_top_k", 30) or 30))
76
+ working = passages[:input_top_k]
77
+ for p in working:
78
  rerank_text = build_anchor_rerank_text(p)
79
  pairs.append((question, rerank_text))
80
 
81
+ try:
82
+ scores = ce.predict(pairs)
83
+ except Exception as exc:
84
+ logger.warning("Reranker disabled for this request after predict failure: %s", exc)
85
+ return passages[: max(1, int(top_n or len(passages)))]
86
 
87
  rescored: List[Dict[str, Any]] = []
88
+ for p, score in zip(working, scores):
89
  item = dict(p)
90
  item["cross_score"] = float(score)
91
  rescored.append(item)
92
 
93
  rescored.sort(key=lambda x: float(x.get("cross_score", 0.0)), reverse=True)
94
+ return rescored[: max(1, int(top_n or 1))]
src/rag/retrieval_pipeline.py CHANGED
@@ -543,8 +543,8 @@ def _score_candidates(
543
  phrase_score, matched_phrases = _phrase_signal(question, text)
544
  md = dict(item.get("metadata") or {})
545
  doc = docs_by_id.get(str(item.get("doc_id") or ""), {})
546
- metadata_prior = _metadata_prior(query_signals, doc)
547
- structure_bonus = _structure_bonus(query_profile, md)
548
  reference_bonus = _reference_bonus(question, md)
549
  reference_exact = _reference_exact_match_score(md, filters)
550
 
 
543
  phrase_score, matched_phrases = _phrase_signal(question, text)
544
  md = dict(item.get("metadata") or {})
545
  doc = docs_by_id.get(str(item.get("doc_id") or ""), {})
546
+ metadata_prior = _metadata_prior(query_signals, doc) #Xem document có khớp với tín hiệu câu hỏi không
547
+ structure_bonus = _structure_bonus(query_profile, md) #Điểm thưởng nếu candidate nằm đúng phần cấu trúc mà câu hỏi cần.
548
  reference_bonus = _reference_bonus(question, md)
549
  reference_exact = _reference_exact_match_score(md, filters)
550
 
src/rag/retrieval_pipeline_simple.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import logging
5
+ import math
6
+ import re
7
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
8
+
9
+ from src.app.settings import settings
10
+ from src.rag.auto_filter import infer_query_profile
11
+ from src.rag.bm25_corpus import load_bm25_stats
12
+ from src.rag.hybrid import bm25_score, tokenize_vi
13
+ from src.rag.rerank_cross import cross_rerank
14
+ from src.storage.qdrant_store import get_qdrant_client, ensure_payload_indexes, search_qdrant
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ _QUESTION_EMBED_CACHE: Dict[str, List[float]] = {}
19
+ _TOKEN_CACHE: Dict[str, List[str]] = {}
20
+ _BM25_RUNTIME: Optional[Dict[str, Any]] = None
21
+
22
+ _CROSS_REF_RE = re.compile(
23
+ r"(?:(điểm)\s+([a-zđ])\s+)?(?:(khoản)\s+(\d+)\s+)?(điều)\s+(\d+)",
24
+ re.IGNORECASE,
25
+ )
26
+ _DOC_NUMBER_RE = re.compile(r"\b\d{1,4}/\d{4}/[A-ZĐ\-]+\b", re.IGNORECASE)
27
+ _DOC_NUMBER_SHORT_RE = re.compile(r"\b\d{1,4}/[A-ZĐ\-]+\b", re.IGNORECASE)
28
+
29
+
30
+ def _norm_space(text: Any) -> str:
31
+ return " ".join(str(text or "").split()).strip()
32
+
33
+
34
+ def _norm_key(text: Any) -> str:
35
+ return _norm_space(text).lower()
36
+
37
+
38
+ def _norm_doc_number(text: Any) -> str:
39
+ raw = _norm_space(text).upper().replace("Đ", "D")
40
+ parts = raw.split("/")
41
+ if parts and parts[0].isdigit():
42
+ parts[0] = str(int(parts[0]))
43
+ return "/".join(parts)
44
+
45
+
46
+ def _node_index(graph: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
47
+ idx = graph.get("node_index", {}) or {}
48
+ if idx:
49
+ return idx
50
+ out: Dict[str, Dict[str, Any]] = {}
51
+ for node in list(graph.get("nodes") or []):
52
+ node_id = str(node.get("node_id") or "").strip()
53
+ if node_id:
54
+ out[node_id] = node
55
+ graph["node_index"] = out
56
+ return out
57
+
58
+
59
+ def _node_metadata(node: Dict[str, Any]) -> Dict[str, Any]:
60
+ md = dict(node.get("metadata") or {})
61
+ for key in ("node_id", "parent_id", "children_ids", "node_type", "text", "retrieval_text"):
62
+ if key in node and key not in md:
63
+ md[key] = node.get(key)
64
+ return md
65
+
66
+
67
+ def _node_text(node: Dict[str, Any]) -> str:
68
+ return _norm_space(node.get("retrieval_text") or node.get("text") or "")
69
+
70
+
71
+ def _candidate_id(item: Dict[str, Any]) -> str:
72
+ return str(item.get("id") or item.get("node_id") or item.get("chunk_id") or "").strip()
73
+
74
+
75
+ def _text_cache_key(text: str) -> str:
76
+ return hashlib.sha1(_norm_space(text).encode("utf-8")).hexdigest()
77
+
78
+
79
+ def _tokens_for(text: str) -> List[str]:
80
+ key = _text_cache_key(text)
81
+ if key not in _TOKEN_CACHE:
82
+ _TOKEN_CACHE[key] = tokenize_vi(text)
83
+ return _TOKEN_CACHE[key]
84
+
85
+
86
+ def _cosine(a: List[float], b: List[float]) -> float:
87
+ if not a or not b or len(a) != len(b):
88
+ return 0.0
89
+ dot = sum(float(x) * float(y) for x, y in zip(a, b))
90
+ na = sum(float(x) * float(x) for x in a)
91
+ nb = sum(float(y) * float(y) for y in b)
92
+ if na <= 0.0 or nb <= 0.0:
93
+ return 0.0
94
+ return float(dot / (math.sqrt(na) * math.sqrt(nb)))
95
+
96
+
97
+ def _question_embedding(question: str) -> List[float]:
98
+ from src.rag.openai_clients import get_embedings
99
+
100
+ key = _text_cache_key(question)
101
+ if key not in _QUESTION_EMBED_CACHE:
102
+ _QUESTION_EMBED_CACHE[key] = list(get_embedings().embed_query(_norm_space(question)))
103
+ return _QUESTION_EMBED_CACHE[key]
104
+
105
+
106
+ def _get_bm25_runtime() -> Dict[str, Any]:
107
+ global _BM25_RUNTIME
108
+ if _BM25_RUNTIME is not None:
109
+ return _BM25_RUNTIME
110
+ path = str(getattr(settings, "bm25_stats_path", "") or "").strip()
111
+ if not path:
112
+ _BM25_RUNTIME = {"idf": {}, "avgdl": 0.0}
113
+ return _BM25_RUNTIME
114
+ try:
115
+ _BM25_RUNTIME = load_bm25_stats(path)
116
+ except Exception as exc:
117
+ logger.warning("Failed to load BM25 stats from %s: %s", path, exc)
118
+ _BM25_RUNTIME = {"idf": {}, "avgdl": 0.0}
119
+ return _BM25_RUNTIME
120
+
121
+
122
+ def _iter_graph_candidates(graph: Dict[str, Any]) -> List[Dict[str, Any]]:
123
+ out: List[Dict[str, Any]] = []
124
+ for node_id, node in _node_index(graph).items():
125
+ md = _node_metadata(node)
126
+ text = _node_text(node)
127
+ if not text:
128
+ continue
129
+ artifact = str(md.get("artifact_type") or "evidence").strip().lower()
130
+ node_type = str(md.get("node_type") or node.get("node_type") or "").strip().lower()
131
+ if artifact not in {"evidence", "article_bundle", "section_bundle", "doc_sketch"} and node_type not in {
132
+ "article",
133
+ "clause",
134
+ "point",
135
+ "section",
136
+ "item",
137
+ "bullet",
138
+ }:
139
+ continue
140
+ out.append(
141
+ {
142
+ "id": node_id,
143
+ "node_id": node_id,
144
+ "chunk_id": str(md.get("chunk_id") or node_id),
145
+ "doc_id": str(md.get("doc_id") or ""),
146
+ "doc_key": str(md.get("doc_id") or ""),
147
+ "text": text,
148
+ "retrieval_text": _norm_space(node.get("retrieval_text") or text),
149
+ "rerank_text_short": _norm_space(node.get("rerank_text") or node.get("retrieval_text") or text)[:1500],
150
+ "metadata": md,
151
+ }
152
+ )
153
+ return out
154
+
155
+
156
+ def analyze_query(question: str) -> Dict[str, Any]:
157
+ profile = infer_query_profile(question) or {}
158
+ filters = dict(profile.get("filters") or {})
159
+ if not filters.get("doc_number"):
160
+ m_short = _DOC_NUMBER_SHORT_RE.search(_norm_space(question).upper())
161
+ if m_short:
162
+ filters["doc_number"] = m_short.group(0).upper()
163
+ query_type = "explicit_legal_reference" if profile.get("explicit_reference") else str(profile.get("route") or "factoid")
164
+ out: Dict[str, Any] = {
165
+ "question": _norm_space(question),
166
+ "doc_number": filters.get("doc_number"),
167
+ "law_type": filters.get("law_type"),
168
+ "year": str(filters.get("year")) if filters.get("year") not in (None, "") else None,
169
+ "article": filters.get("article"),
170
+ "clause": filters.get("clause"),
171
+ "point": filters.get("point"),
172
+ "heading_terms": list(profile.get("heading_terms") or []),
173
+ "change_terms": list(profile.get("change_terms") or []),
174
+ "explicit_reference": bool(profile.get("explicit_reference")),
175
+ "query_type": query_type,
176
+ "route": profile.get("route"),
177
+ "filters": filters,
178
+ }
179
+ return out
180
+
181
+
182
+ def _metadata_value(md: Dict[str, Any], key: str) -> Any:
183
+ aliases = {
184
+ "law_type": ("law_type", "doc_type"),
185
+ "doc_number": ("doc_number",),
186
+ "year": ("year",),
187
+ "article": ("article",),
188
+ "clause": ("clause",),
189
+ "point": ("point",),
190
+ }
191
+ for candidate_key in aliases.get(key, (key,)):
192
+ value = md.get(candidate_key)
193
+ if value not in (None, ""):
194
+ return value
195
+ return None
196
+
197
+
198
+ def _matches_filter(item: Dict[str, Any], key: str, expected: Any) -> bool:
199
+ if expected in (None, ""):
200
+ return True
201
+ md = dict(item.get("metadata") or {})
202
+ actual = _metadata_value(md, key)
203
+ if actual in (None, ""):
204
+ return False
205
+ if key == "doc_number":
206
+ return _norm_doc_number(actual) == _norm_doc_number(expected)
207
+ if key == "year":
208
+ return str(actual) == str(expected)
209
+ return _norm_key(actual) == _norm_key(expected)
210
+
211
+
212
+ def apply_metadata_filter(candidates: List[Dict[str, Any]], query_profile: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
213
+ before_count = len(candidates)
214
+ filters = dict(query_profile.get("filters") or {})
215
+ for key in ("doc_number", "law_type", "year", "article", "clause", "point"):
216
+ if query_profile.get(key) not in (None, ""):
217
+ filters.setdefault(key, query_profile.get(key))
218
+
219
+ qualifiers = [key for key in ("law_type", "year") if filters.get(key) not in (None, "")]
220
+ levels: List[Tuple[str, List[str]]] = []
221
+ if filters.get("doc_number"):
222
+ for name, keys in (
223
+ ("doc_number_article_clause_point", ["doc_number", "article", "clause", "point"]),
224
+ ("doc_number_article_clause", ["doc_number", "article", "clause"]),
225
+ ("doc_number_article", ["doc_number", "article"]),
226
+ ("doc_number", ["doc_number"]),
227
+ ):
228
+ required = [key for key in keys if filters.get(key) not in (None, "")]
229
+ levels.append((name, required))
230
+ for name, keys in (
231
+ ("article_clause_point", qualifiers + ["article", "clause", "point"]),
232
+ ("article_clause", qualifiers + ["article", "clause"]),
233
+ ("article", qualifiers + ["article"]),
234
+ ("law_type_year", qualifiers),
235
+ ):
236
+ required = [key for key in keys if filters.get(key) not in (None, "")]
237
+ if required:
238
+ levels.append((name, required))
239
+
240
+ seen_levels = set()
241
+ deduped_levels: List[Tuple[str, List[str]]] = []
242
+ for name, keys in levels:
243
+ sig = tuple(keys)
244
+ if not keys or sig in seen_levels:
245
+ continue
246
+ seen_levels.add(sig)
247
+ deduped_levels.append((name, keys))
248
+
249
+ for name, keys in deduped_levels:
250
+ filtered = [item for item in candidates if all(_matches_filter(item, key, filters.get(key)) for key in keys)]
251
+ if filtered:
252
+ return filtered, {
253
+ "applied_filters": keys,
254
+ "fallback_level": name,
255
+ "before_count": before_count,
256
+ "after_count": len(filtered),
257
+ }
258
+
259
+ return candidates, {
260
+ "applied_filters": [],
261
+ "fallback_level": "no_hard_filter",
262
+ "before_count": before_count,
263
+ "after_count": len(candidates),
264
+ }
265
+
266
+
267
+ def _qdrant_payload_to_passage(point: Any) -> Dict[str, Any]:
268
+ payload = dict(getattr(point, "payload", None) or (point.get("payload", {}) if isinstance(point, dict) else {}) or {})
269
+ md = dict(payload.get("metadata") or {})
270
+ for key, value in payload.items():
271
+ if key not in {"metadata", "vector"} and key not in md:
272
+ md[key] = value
273
+ point_id = str(getattr(point, "id", "") or (point.get("id", "") if isinstance(point, dict) else ""))
274
+ node_id = str(payload.get("node_id") or md.get("node_id") or payload.get("chunk_id") or md.get("chunk_id") or point_id)
275
+ text = _norm_space(payload.get("retrieval_text") or payload.get("text") or md.get("retrieval_text") or md.get("text") or "")
276
+ score = float(getattr(point, "score", 0.0) or (point.get("score", 0.0) if isinstance(point, dict) else 0.0) or 0.0)
277
+ return {
278
+ "id": node_id,
279
+ "node_id": node_id,
280
+ "chunk_id": str(payload.get("chunk_id") or md.get("chunk_id") or node_id),
281
+ "doc_id": str(payload.get("doc_id") or md.get("doc_id") or ""),
282
+ "doc_key": str(payload.get("doc_id") or md.get("doc_id") or ""),
283
+ "text": text,
284
+ "retrieval_text": text,
285
+ "rerank_text_short": _norm_space(payload.get("rerank_text") or md.get("rerank_text") or text)[:1500],
286
+ "metadata": md,
287
+ "dense_score": score,
288
+ }
289
+
290
+
291
+ def _qdrant_filters_from_query(query_profile: Dict[str, Any], filter_info: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
292
+ filters = dict(query_profile.get("filters") or {})
293
+ applied = list((filter_info or {}).get("applied_filters") or [])
294
+ if not applied:
295
+ applied = [key for key in ("doc_number", "law_type", "year", "article", "clause", "point") if filters.get(key) not in (None, "")]
296
+ return {key: filters[key] for key in applied if filters.get(key) not in (None, "")}
297
+
298
+
299
+ def dense_search(
300
+ question: str,
301
+ candidates: Optional[List[Dict[str, Any]]] = None,
302
+ top_k: int = 50,
303
+ *,
304
+ query_profile: Optional[Dict[str, Any]] = None,
305
+ filter_info: Optional[Dict[str, Any]] = None,
306
+ ) -> List[Dict[str, Any]]:
307
+ del candidates
308
+ try:
309
+ q_vec = _question_embedding(question)
310
+ qdrant_filters = _qdrant_filters_from_query(query_profile or {}, filter_info)
311
+ client = get_qdrant_client()
312
+ if qdrant_filters:
313
+ ensure_payload_indexes(client)
314
+ points = search_qdrant(client, q_vec, top_k=top_k, filters=qdrant_filters)
315
+ except Exception as exc:
316
+ logger.warning("Dense search skipped after Qdrant/OpenAI failure: %s", exc)
317
+ return []
318
+
319
+ ranked: List[Dict[str, Any]] = []
320
+ for point in points:
321
+ ranked.append(_qdrant_payload_to_passage(point))
322
+ ranked.sort(key=lambda x: float(x.get("dense_score", 0.0)), reverse=True)
323
+ for rank, item in enumerate(ranked[:top_k], start=1):
324
+ item["rank"] = rank
325
+ return ranked[:top_k]
326
+
327
+
328
+ def bm25_search_vi(question: str, candidates: List[Dict[str, Any]], top_k: int = 50) -> List[Dict[str, Any]]:
329
+ if not candidates:
330
+ return []
331
+ stats = _get_bm25_runtime()
332
+ query_tokens = _tokens_for(question)
333
+ ranked: List[Dict[str, Any]] = []
334
+ for item in candidates:
335
+ text = str(item.get("retrieval_text") or item.get("text") or "")
336
+ scored = dict(item)
337
+ scored["bm25_score"] = bm25_score(
338
+ query_tokens,
339
+ _tokens_for(text),
340
+ idf_map=dict(stats.get("idf") or {}),
341
+ avgdl=float(stats.get("avgdl") or 0.0),
342
+ )
343
+ ranked.append(scored)
344
+ ranked.sort(key=lambda x: float(x.get("bm25_score", 0.0)), reverse=True)
345
+ for rank, item in enumerate(ranked[:top_k], start=1):
346
+ item["rank"] = rank
347
+ return ranked[:top_k]
348
+
349
+
350
+ def rrf_fusion(
351
+ rank_lists: List[List[Dict[str, Any]]],
352
+ rrf_k: int = 60,
353
+ top_k: int = 30,
354
+ *,
355
+ dense_weight: float = 1.0,
356
+ bm25_weight: float = 1.0,
357
+ ) -> List[Dict[str, Any]]:
358
+ weights = [dense_weight, bm25_weight] + [1.0] * max(0, len(rank_lists) - 2)
359
+ buckets: Dict[str, Dict[str, Any]] = {}
360
+ scores: Dict[str, float] = {}
361
+ ranks_by_source: Dict[str, Dict[str, int]] = {}
362
+
363
+ for list_idx, rank_list in enumerate(rank_lists):
364
+ weight = float(weights[list_idx] if list_idx < len(weights) else 1.0)
365
+ for fallback_rank, item in enumerate(rank_list, start=1):
366
+ item_id = _candidate_id(item)
367
+ if not item_id:
368
+ continue
369
+ rank = int(item.get("rank") or fallback_rank)
370
+ buckets.setdefault(item_id, dict(item))
371
+ scores[item_id] = scores.get(item_id, 0.0) + weight * (1.0 / (float(rrf_k) + rank))
372
+ source_key = "dense_rank" if list_idx == 0 else "bm25_rank" if list_idx == 1 else f"rank_{list_idx}"
373
+ ranks_by_source.setdefault(item_id, {})[source_key] = rank
374
+
375
+ fused: List[Dict[str, Any]] = []
376
+ for item_id, item in buckets.items():
377
+ out = dict(item)
378
+ out["rrf_score"] = float(scores.get(item_id, 0.0))
379
+ out.update(ranks_by_source.get(item_id, {}))
380
+ fused.append(out)
381
+ fused.sort(key=lambda x: float(x.get("rrf_score", 0.0)), reverse=True)
382
+ for rank, item in enumerate(fused[:top_k], start=1):
383
+ item["rank"] = rank
384
+ return fused[:top_k]
385
+
386
+
387
+ def _passage_from_node(node: Dict[str, Any], *, expansion_type: str, expanded_from: str, matched_reference: str = "") -> Dict[str, Any]:
388
+ node_id = str(node.get("node_id") or "")
389
+ md = _node_metadata(node)
390
+ text = _node_text(node)
391
+ out = {
392
+ "id": node_id,
393
+ "node_id": node_id,
394
+ "chunk_id": str(md.get("chunk_id") or node_id),
395
+ "doc_id": str(md.get("doc_id") or ""),
396
+ "doc_key": str(md.get("doc_id") or ""),
397
+ "text": text,
398
+ "local_text": text,
399
+ "shared_text": "",
400
+ "snippet": text[:700],
401
+ "retrieval_text": _norm_space(node.get("retrieval_text") or text),
402
+ "rerank_text_short": _norm_space(node.get("rerank_text") or node.get("retrieval_text") or text)[:1500],
403
+ "metadata": md,
404
+ "expansion_type": expansion_type,
405
+ "expanded_from": expanded_from,
406
+ }
407
+ if matched_reference:
408
+ out["matched_reference"] = matched_reference
409
+ return out
410
+
411
+
412
+ def expand_siblings(passages: List[Dict[str, Any]], graph: Dict[str, Any], window: int = 2, max_expanded: int = 20) -> List[Dict[str, Any]]:
413
+ node_idx = _node_index(graph)
414
+ out = [dict(p) for p in passages]
415
+ seen = {_candidate_id(p) for p in out}
416
+ expanded = 0
417
+
418
+ for passage in passages:
419
+ if expanded >= max_expanded:
420
+ break
421
+ node_id = str(passage.get("node_id") or "")
422
+ node = node_idx.get(node_id)
423
+ if not node:
424
+ continue
425
+ md = _node_metadata(node)
426
+ parent_id = str(md.get("parent_id") or node.get("parent_id") or "").strip()
427
+ siblings: List[Dict[str, Any]] = []
428
+ if parent_id and parent_id in node_idx:
429
+ parent_md = _node_metadata(node_idx[parent_id])
430
+ child_ids = [str(x) for x in (parent_md.get("children_ids") or node_idx[parent_id].get("children_ids") or []) if str(x)]
431
+ siblings = [node_idx[x] for x in child_ids if x in node_idx]
432
+ if not siblings:
433
+ article = _norm_key(md.get("article"))
434
+ doc_id = _norm_key(md.get("doc_id"))
435
+ siblings = [
436
+ candidate
437
+ for candidate in node_idx.values()
438
+ if _norm_key(_node_metadata(candidate).get("doc_id")) == doc_id
439
+ and _norm_key(_node_metadata(candidate).get("article")) == article
440
+ ]
441
+ if not siblings:
442
+ continue
443
+ siblings.sort(key=lambda n: int(_node_metadata(n).get("order_index") or 0))
444
+ pos = next((idx for idx, candidate in enumerate(siblings) if str(candidate.get("node_id") or "") == node_id), -1)
445
+ if pos < 0:
446
+ continue
447
+ for sibling in siblings[max(0, pos - window) : pos + window + 1]:
448
+ sibling_id = str(sibling.get("node_id") or "")
449
+ if not sibling_id or sibling_id in seen or sibling_id == node_id:
450
+ continue
451
+ text = _node_text(sibling)
452
+ if not text:
453
+ continue
454
+ out.append(_passage_from_node(sibling, expansion_type="sibling", expanded_from=node_id))
455
+ seen.add(sibling_id)
456
+ expanded += 1
457
+ if expanded >= max_expanded:
458
+ break
459
+ return out
460
+
461
+
462
+ def _extract_cross_refs(text: str) -> List[Dict[str, str]]:
463
+ refs: List[Dict[str, str]] = []
464
+ for match in _CROSS_REF_RE.finditer(_norm_space(text).lower()):
465
+ point = match.group(2)
466
+ clause = match.group(4)
467
+ article = match.group(6)
468
+ label_parts: List[str] = []
469
+ if point:
470
+ label_parts.append(f"Điểm {point}")
471
+ if clause:
472
+ label_parts.append(f"Khoản {clause}")
473
+ label_parts.append(f"Điều {article}")
474
+ refs.append(
475
+ {
476
+ "article": f"Điều {article}",
477
+ "clause": f"Khoản {clause}" if clause else "",
478
+ "point": f"Điểm {point}" if point else "",
479
+ "label": " ".join(label_parts),
480
+ }
481
+ )
482
+ return refs
483
+
484
+
485
+ def _resolve_reference(ref: Dict[str, str], graph: Dict[str, Any], source_md: Dict[str, Any]) -> Optional[Dict[str, Any]]:
486
+ doc_number = _norm_key(source_md.get("doc_number"))
487
+ doc_id = _norm_key(source_md.get("doc_id"))
488
+ candidates: List[Tuple[int, Dict[str, Any]]] = []
489
+ for node in _node_index(graph).values():
490
+ md = _node_metadata(node)
491
+ if doc_number and _norm_key(md.get("doc_number")) not in {"", doc_number}:
492
+ continue
493
+ if not doc_number and doc_id and _norm_key(md.get("doc_id")) != doc_id:
494
+ continue
495
+ if ref.get("article") and _norm_key(md.get("article")) != _norm_key(ref.get("article")):
496
+ continue
497
+ if ref.get("clause") and _norm_key(md.get("clause")) != _norm_key(ref.get("clause")):
498
+ continue
499
+ if ref.get("point") and _norm_key(md.get("point")) != _norm_key(ref.get("point")):
500
+ continue
501
+ specificity = int(bool(ref.get("article"))) + int(bool(ref.get("clause"))) + int(bool(ref.get("point")))
502
+ candidates.append((specificity, node))
503
+ if not candidates:
504
+ return None
505
+ candidates.sort(key=lambda x: (x[0], int(_node_metadata(x[1]).get("order_index") or 0)), reverse=True)
506
+ return candidates[0][1]
507
+
508
+
509
+ def expand_cross_refs(passages: List[Dict[str, Any]], graph: Dict[str, Any], max_refs: int = 10) -> List[Dict[str, Any]]:
510
+ out = [dict(p) for p in passages]
511
+ seen = {_candidate_id(p) for p in out}
512
+ expanded = 0
513
+ for passage in passages:
514
+ if expanded >= max_refs:
515
+ break
516
+ source_id = str(passage.get("node_id") or "")
517
+ source_md = dict(passage.get("metadata") or {})
518
+ refs = _extract_cross_refs(str(passage.get("text") or passage.get("local_text") or ""))
519
+ for ref in refs:
520
+ node = _resolve_reference(ref, graph, source_md)
521
+ if not node:
522
+ continue
523
+ node_id = str(node.get("node_id") or "")
524
+ if not node_id or node_id in seen:
525
+ continue
526
+ out.append(
527
+ _passage_from_node(
528
+ node,
529
+ expansion_type="cross_ref",
530
+ expanded_from=source_id,
531
+ matched_reference=str(ref.get("label") or ""),
532
+ )
533
+ )
534
+ seen.add(node_id)
535
+ expanded += 1
536
+ if expanded >= max_refs:
537
+ break
538
+ return out
539
+
540
+
541
+ def graph_expansion_sibling_crossref(passages: List[Dict[str, Any]], graph: Dict[str, Any]) -> List[Dict[str, Any]]:
542
+ expanded = expand_siblings(passages, graph, window=2, max_expanded=20)
543
+ return expand_cross_refs(expanded, graph, max_refs=10)
544
+
545
+
546
+ def optional_cpu_rerank(question: str, passages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
547
+ if not bool(getattr(settings, "enable_reranker", False)):
548
+ return passages
549
+ input_top_k = max(1, int(getattr(settings, "rerank_input_top_k", 30) or 30))
550
+ top_n = max(1, int(getattr(settings, "rerank_top_n", 5) or 5))
551
+ reranked_head = cross_rerank(question, passages[:input_top_k], top_n=min(top_n, len(passages[:input_top_k])))
552
+ remaining = [p for p in passages if _candidate_id(p) not in {_candidate_id(x) for x in reranked_head}]
553
+ return reranked_head + remaining
554
+
555
+
556
+ def retrieve_with_graph_simple(
557
+ question: str,
558
+ graph: Dict[str, Any],
559
+ filters: Optional[Dict[str, Any]] = None,
560
+ *,
561
+ dense_top_k: int = 50,
562
+ bm25_top_k: int = 50,
563
+ fusion_top_k: int = 30,
564
+ final_top_k: Optional[int] = None,
565
+ ) -> Dict[str, Any]:
566
+ query_profile = analyze_query(question)
567
+ if filters:
568
+ merged = dict(query_profile.get("filters") or {})
569
+ merged.update({key: value for key, value in filters.items() if value not in (None, "", [], {})})
570
+ query_profile["filters"] = merged
571
+ for key, value in merged.items():
572
+ query_profile[key] = value
573
+
574
+ candidates = _iter_graph_candidates(graph)
575
+ filtered_candidates, filter_info = apply_metadata_filter(candidates, query_profile)
576
+ dense_results = dense_search(
577
+ question,
578
+ top_k=dense_top_k,
579
+ query_profile=query_profile,
580
+ filter_info=filter_info,
581
+ )
582
+ bm25_results = bm25_search_vi(question, filtered_candidates, top_k=bm25_top_k)
583
+ fused = rrf_fusion(
584
+ [dense_results, bm25_results],
585
+ rrf_k=int(getattr(settings, "rrf_k", 60) or 60),
586
+ top_k=fusion_top_k,
587
+ )
588
+ expanded = graph_expansion_sibling_crossref(fused, graph)
589
+ passages = optional_cpu_rerank(question, expanded)
590
+ limit = int(final_top_k or getattr(settings, "final_top_k", 5) or 5)
591
+ passages = passages[: max(1, limit)]
592
+
593
+ return {
594
+ "mode": "simple_rrf",
595
+ "query_profile": query_profile,
596
+ "filter_info": filter_info,
597
+ "candidate_count": len(candidates),
598
+ "filtered_candidate_count": len(filtered_candidates),
599
+ "dense_results_count": len(dense_results),
600
+ "bm25_results_count": len(bm25_results),
601
+ "passages": passages,
602
+ "reranker_enabled": bool(getattr(settings, "enable_reranker", False)),
603
+ "insufficient_context": not bool(passages),
604
+ }
src/storage/qdrant_store.py CHANGED
@@ -32,6 +32,41 @@ def ensure_collection(client: QdrantClient, vector_size: int = DEFAULT_VECTOR_SI
32
  )
33
 
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def build_filter(filters: Dict[str, Any]) -> Optional[qm.Filter]:
36
  if not filters:
37
  return None
 
32
  )
33
 
34
 
35
+ def ensure_payload_indexes(client: QdrantClient) -> None:
36
+ keyword_fields = [
37
+ "doc_number",
38
+ "law_type",
39
+ "doc_type",
40
+ "article",
41
+ "clause",
42
+ "point",
43
+ "doc_id",
44
+ "chunk_id",
45
+ "node_id",
46
+ ]
47
+ integer_fields = ["year"]
48
+
49
+ for field in keyword_fields:
50
+ try:
51
+ client.create_payload_index(
52
+ collection_name=settings.qdrant_collection,
53
+ field_name=field,
54
+ field_schema=qm.PayloadSchemaType.KEYWORD,
55
+ )
56
+ except Exception:
57
+ pass
58
+
59
+ for field in integer_fields:
60
+ try:
61
+ client.create_payload_index(
62
+ collection_name=settings.qdrant_collection,
63
+ field_name=field,
64
+ field_schema=qm.PayloadSchemaType.INTEGER,
65
+ )
66
+ except Exception:
67
+ pass
68
+
69
+
70
  def build_filter(filters: Dict[str, Any]) -> Optional[qm.Filter]:
71
  if not filters:
72
  return None
tests/test_citation_validator.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.rag.citation_validator import validate_citations
2
+
3
+
4
+ def test_citation_validator_flags_unsupported_article():
5
+ result = validate_citations(
6
+ "Theo Điều 6, người vi phạm bị xử lý.",
7
+ [{"metadata": {"article": "Điều 5"}}],
8
+ )
9
+
10
+ assert result["valid"] is False
11
+ assert result["unsupported_references"]
tests/test_context_grader.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.rag.context_grader import grade_context
2
+ from src.rag.retrieval_pipeline_simple import analyze_query
3
+
4
+
5
+ def test_context_grader_explicit_reference_requires_matching_metadata():
6
+ question = "Điểm a khoản 3 Điều 6 quy định gì?"
7
+ profile = analyze_query(question)
8
+ wrong_passages = [
9
+ {
10
+ "text": "Một quy định liên quan.",
11
+ "metadata": {"article": "Điều 5", "clause": "Khoản 3", "point": "Điểm a"},
12
+ }
13
+ ]
14
+
15
+ assert grade_context(question, profile, wrong_passages)["status"] == "insufficient"
16
+
17
+ right_passages = [
18
+ {
19
+ "text": "Điểm a khoản 3 Điều 6 quy định về việc không chấp hành tín hiệu giao thông.",
20
+ "metadata": {"article": "Điều 6", "clause": "Khoản 3", "point": "Điểm a"},
21
+ }
22
+ ]
23
+
24
+ assert grade_context(question, profile, right_passages)["status"] == "sufficient"
25
+
26
+
27
+ def test_context_grader_needs_reasoning_for_fault_question_with_relevant_rules():
28
+ question = "Xe A vượt đèn đỏ va chạm xe B, ai có lỗi?"
29
+ profile = analyze_query(question)
30
+ passages = [
31
+ {
32
+ "text": "Người điều khiển phương tiện phải chấp hành tín hiệu giao thông; không được vượt đèn đỏ.",
33
+ "metadata": {"article": "Điều 6"},
34
+ }
35
+ ]
36
+
37
+ result = grade_context(question, profile, passages)
38
+
39
+ assert result["status"] == "needs_reasoning"
40
+ assert result["allow_reasoning"] is True
tests/test_eval_prepare_benchmark.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+
4
+ from src.evaluation.prepare_benchmark import prepare_benchmark
5
+
6
+
7
+ def test_prepare_benchmark_converts_json_array_to_jsonl(tmp_path: Path):
8
+ input_path = tmp_path / "benchmark.json"
9
+ output_path = tmp_path / "benchmark.jsonl"
10
+ input_path.write_text(
11
+ json.dumps(
12
+ [
13
+ {
14
+ "question": "Điều 1 quy định gì?",
15
+ "ground_truth": "Điều 1 quy định phạm vi.",
16
+ "reference": "Điều 1 quy định phạm vi.",
17
+ "expected_doc_number": "01/2026/TT-NHNN",
18
+ "expected_law_type": "Thông tư",
19
+ "expected_year": "2026",
20
+ "expected_article": "Điều 1",
21
+ "expected_clause": "",
22
+ "expected_point": "",
23
+ "source_excerpt": "Điều 1. Phạm vi điều chỉnh",
24
+ }
25
+ ],
26
+ ensure_ascii=False,
27
+ ),
28
+ encoding="utf-8",
29
+ )
30
+
31
+ samples = prepare_benchmark(input_path, output_path)
32
+ lines = output_path.read_text(encoding="utf-8").splitlines()
33
+ payload = json.loads(lines[0])
34
+
35
+ assert len(samples) == 1
36
+ assert payload["id"] == "q001"
37
+ assert payload["expected_context_refs"][0]["doc_number"] == "01/2026/TT-NHNN"
38
+ assert payload["expected_context_refs"][0]["article"] == "Điều 1"
tests/test_eval_rule_metrics.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.evaluation.ragas_lite_judge import safe_json_loads
2
+ from src.evaluation.rule_metrics import (
3
+ citation_support_lite,
4
+ context_precision_lite,
5
+ context_recall_lite,
6
+ context_sufficiency_lite,
7
+ retrieval_ref_match_lite,
8
+ )
9
+
10
+
11
+ def test_context_sufficiency_lite_counts_field_matches():
12
+ sample = {
13
+ "contexts": ["context"],
14
+ "expected_context_refs": [
15
+ {
16
+ "doc_number": "01/2026/TT-NHNN",
17
+ "law_type": "Thông tư",
18
+ "year": "2026",
19
+ "article": "Điều 1",
20
+ "clause": "Khoản 2",
21
+ "point": "",
22
+ }
23
+ ],
24
+ "context_metadata": [
25
+ {
26
+ "doc_number": "01/2026/TT-NHNN",
27
+ "law_type": "Thông tư",
28
+ "year": "2026",
29
+ "article": "Điều 1",
30
+ "clause": "",
31
+ }
32
+ ],
33
+ }
34
+
35
+ result = context_sufficiency_lite(sample)
36
+
37
+ assert result["score"] == 0.8
38
+ assert "clause" in result["missing_fields"]
39
+
40
+
41
+ def test_retrieval_ref_match_lite_normalizes_when_expected_fields_empty():
42
+ sample = {
43
+ "expected_context_refs": [
44
+ {
45
+ "doc_number": "01/2026/TT-NHNN",
46
+ "law_type": "",
47
+ "year": "",
48
+ "article": "Điều 1",
49
+ "clause": "",
50
+ "point": "",
51
+ }
52
+ ],
53
+ "context_metadata": [{"doc_number": "01/2026/TT-NHNN", "article": ""}],
54
+ }
55
+
56
+ result = retrieval_ref_match_lite(sample)
57
+
58
+ assert round(result["score"], 4) == round(0.40 / (0.40 + 0.20), 4)
59
+ assert result["matched"]["law_type"] is None
60
+
61
+
62
+ def test_citation_support_lite_flags_unsupported_citation():
63
+ result = citation_support_lite(
64
+ "Theo Điều 6 và Khoản 4, nội dung này được áp dụng.",
65
+ [{"article": "Điều 6"}],
66
+ )
67
+
68
+ assert result["score"] == 0.5
69
+ assert "Điều 6" in result["supported_references"]
70
+ assert "Khoản 4" in result["unsupported_references"]
71
+
72
+
73
+ def test_context_precision_and_recall_lite_use_contexts_against_gold():
74
+ sample = {
75
+ "ground_truth": "Bảo hiểm tiền gửi Việt Nam không được cung cấp thông tin cho bên thứ ba.",
76
+ "reference": "Bảo hiểm tiền gửi Việt Nam không được cung cấp thông tin cho bên thứ ba.",
77
+ "source_excerpt": "Bảo hiểm tiền gửi Việt Nam không được cung cấp thông tin cho bên thứ ba.",
78
+ "contexts": [
79
+ "Bảo hiểm tiền gửi Việt Nam không được cung cấp thông tin cho bên thứ ba.",
80
+ "Một đoạn không liên quan về giao thông đường bộ.",
81
+ ],
82
+ "expected_context_refs": [{"doc_number": "01/2026/TT-NHNN", "article": "Điều 4"}],
83
+ "context_metadata": [
84
+ {"doc_number": "01/2026/TT-NHNN", "article": "Điều 4"},
85
+ {"doc_number": "99/2026/TT-BTC", "article": "Điều 9"},
86
+ ],
87
+ }
88
+
89
+ precision = context_precision_lite(sample)
90
+ recall = context_recall_lite(sample)
91
+
92
+ assert precision["score"] == 0.5
93
+ assert recall["score"] > 0.9
94
+
95
+
96
+ def test_safe_json_loads_parses_markdown_code_block():
97
+ parsed = safe_json_loads(
98
+ """```json
99
+ {"score": 0.8, "reason": "ok"}
100
+ ```"""
101
+ )
102
+
103
+ assert parsed["score"] == 0.8
tests/test_rrf_fusion.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.rag.retrieval_pipeline_simple import rrf_fusion
2
+
3
+
4
+ def test_rrf_prefers_item_present_in_both_rank_lists():
5
+ dense = [
6
+ {"id": "dense-only", "rank": 1, "text": "dense"},
7
+ {"id": "shared", "rank": 2, "text": "shared"},
8
+ ]
9
+ bm25 = [
10
+ {"id": "bm25-only", "rank": 1, "text": "bm25"},
11
+ {"id": "shared", "rank": 2, "text": "shared"},
12
+ ]
13
+
14
+ fused = rrf_fusion([dense, bm25], rrf_k=60, top_k=3)
15
+ ids = [item["id"] for item in fused]
16
+
17
+ assert ids[0] == "shared"
tests/test_tokenize_vi.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.rag.hybrid import tokenize_vi
2
+
3
+
4
+ def test_tokenize_vi_segments_or_falls_back_without_crashing():
5
+ tokens = tokenize_vi("vượt đèn đỏ không chấp hành tín hiệu giao thông")
6
+
7
+ assert tokens
8
+ assert any("đèn" in token for token in tokens)
9
+ assert any("giao" in token for token in tokens)
10
+
11
+
12
+ def test_legal_reference_tokens_are_preserved():
13
+ tokens = tokenize_vi("điểm a khoản 3 điều 6")
14
+
15
+ assert "điểm_a" in tokens
16
+ assert "khoản_3" in tokens
17
+ assert "điều_6" in tokens