ok ban nay on nhat
Browse files- src/app/main.py +7 -3
- src/app/runtime.py +306 -17
- src/rag/openai_clients.py +45 -3
- src/rag/qa_engine.py +28 -16
- src/rag/retrieval_pipeline.py +771 -1173
src/app/main.py
CHANGED
|
@@ -7,7 +7,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 7 |
from fastapi.responses import FileResponse, RedirectResponse
|
| 8 |
|
| 9 |
from src.app.api.router import api_router
|
| 10 |
-
from src.app.runtime import
|
| 11 |
from src.app.settings import settings
|
| 12 |
|
| 13 |
app = FastAPI(title="Legislation RAG", version="0.2.0")
|
|
@@ -41,5 +41,9 @@ def health():
|
|
| 41 |
|
| 42 |
|
| 43 |
@app.on_event("startup")
|
| 44 |
-
def
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from fastapi.responses import FileResponse, RedirectResponse
|
| 8 |
|
| 9 |
from src.app.api.router import api_router
|
| 10 |
+
from src.app.runtime import preload_runtime_on_startup
|
| 11 |
from src.app.settings import settings
|
| 12 |
|
| 13 |
app = FastAPI(title="Legislation RAG", version="0.2.0")
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
@app.on_event("startup")
|
| 44 |
+
async def startup_event():
|
| 45 |
+
preload_runtime_on_startup(
|
| 46 |
+
preload_graph_snapshot=True,
|
| 47 |
+
build_graph_if_missing=True,
|
| 48 |
+
warm_services=True,
|
| 49 |
+
)
|
src/app/runtime.py
CHANGED
|
@@ -1,19 +1,19 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
-
import copy
|
| 4 |
import json
|
| 5 |
import logging
|
| 6 |
import re
|
| 7 |
import time
|
| 8 |
from collections import defaultdict
|
| 9 |
from pathlib import Path
|
|
|
|
| 10 |
from typing import Any, Dict, List, Optional
|
| 11 |
|
| 12 |
from src.app.settings import settings
|
| 13 |
from src.rag.chunking_legal import legal_chunk
|
| 14 |
from src.rag.document_header import extract_document_header
|
| 15 |
from src.rag.ingestion import upsert_chunks
|
| 16 |
-
from src.rag.openai_clients import get_embedings
|
| 17 |
from src.storage.qdrant_store import ensure_collection, get_qdrant_client
|
| 18 |
from src.utils.loader import load_document
|
| 19 |
|
|
@@ -22,6 +22,11 @@ try:
|
|
| 22 |
except Exception:
|
| 23 |
semantic_merge_safe = None
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
_RUNTIME: Dict[str, Any] = {
|
| 27 |
"graph": None,
|
|
@@ -30,9 +35,20 @@ _RUNTIME: Dict[str, Any] = {
|
|
| 30 |
"last_graph_build_seconds": None,
|
| 31 |
"last_reindex_seconds": None,
|
| 32 |
"graph_build_in_progress": False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
}
|
| 34 |
|
| 35 |
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def _norm_space(text: str) -> str:
|
|
@@ -109,7 +125,6 @@ def _node_aliases(node: Dict[str, Any]) -> List[str]:
|
|
| 109 |
val = str(raw or "").strip()
|
| 110 |
if val:
|
| 111 |
aliases.append(val)
|
| 112 |
-
# Dedup while preserving order
|
| 113 |
seen = set()
|
| 114 |
out: List[str] = []
|
| 115 |
for alias in aliases:
|
|
@@ -128,6 +143,16 @@ def _build_alias_index(nodes: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]
|
|
| 128 |
return alias_index
|
| 129 |
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
def _save_graph_snapshot(graph: Dict[str, Any]) -> Path:
|
| 132 |
p = _snapshot_path()
|
| 133 |
p.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -150,12 +175,13 @@ def _load_graph_snapshot() -> Optional[Dict[str, Any]]:
|
|
| 150 |
except Exception as exc:
|
| 151 |
logger.warning("Cannot read graph snapshot %s: %s", p, exc)
|
| 152 |
return None
|
|
|
|
| 153 |
nodes = list(raw.get("nodes", []))
|
| 154 |
edges = list(raw.get("edges", []))
|
| 155 |
if not nodes:
|
| 156 |
return None
|
|
|
|
| 157 |
doc_index = dict(raw.get("doc_index", {}))
|
| 158 |
-
# Rebuild parent/sibling metadata if missing
|
| 159 |
parent_to_children: Dict[str, List[str]] = defaultdict(list)
|
| 160 |
for n in nodes:
|
| 161 |
md = dict(n.get("metadata") or {})
|
|
@@ -185,17 +211,15 @@ def _load_graph_snapshot() -> Optional[Dict[str, Any]]:
|
|
| 185 |
node_id = str(n.get("node_id") or "")
|
| 186 |
md["children_ids"] = parent_to_children.get(node_id, md.get("children_ids", []))
|
| 187 |
md["sibling_ids"] = sibling_map.get(node_id, md.get("sibling_ids", []))
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
return {
|
| 191 |
"nodes": nodes,
|
| 192 |
"edges": edges,
|
| 193 |
-
"node_index": node_index,
|
| 194 |
-
"alias_index": alias_index,
|
| 195 |
"doc_index": doc_index,
|
| 196 |
-
"adjacency": _build_adjacency(edges),
|
| 197 |
-
"reverse_adjacency": _build_reverse_adjacency(edges),
|
| 198 |
}
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
|
| 201 |
def _apply_runtime_graph(graph: Dict[str, Any], built_seconds: float) -> Dict[str, Any]:
|
|
@@ -251,6 +275,259 @@ def _build_sibling_map(parent_to_children: Dict[str, List[str]]) -> Dict[str, Li
|
|
| 251 |
return sibling_map
|
| 252 |
|
| 253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
def build_runtime_graph(
|
| 255 |
input_dir: Optional[str] = None,
|
| 256 |
glob_pattern: Optional[str] = None,
|
|
@@ -323,21 +600,18 @@ def build_runtime_graph(
|
|
| 323 |
for key, val in doc_index[doc_id].items():
|
| 324 |
if md.get(key) in (None, "") and val not in (None, ""):
|
| 325 |
md[key] = val
|
| 326 |
-
alias_index = _build_alias_index(nodes)
|
| 327 |
graph = {
|
| 328 |
"nodes": nodes,
|
| 329 |
"edges": edges,
|
| 330 |
-
"node_index": node_index,
|
| 331 |
-
"alias_index": alias_index,
|
| 332 |
"doc_index": doc_index,
|
| 333 |
-
"adjacency": _build_adjacency(edges),
|
| 334 |
-
"reverse_adjacency": _build_reverse_adjacency(edges),
|
| 335 |
}
|
|
|
|
|
|
|
| 336 |
_apply_runtime_graph(graph, built_seconds=time.perf_counter() - start)
|
| 337 |
_save_graph_snapshot(graph)
|
| 338 |
logger.info(
|
| 339 |
"Graph build finished: docs=%s nodes=%s edges=%s aliases=%s took=%.2fs",
|
| 340 |
-
len(doc_index), len(nodes), len(edges), len(alias_index), _RUNTIME["last_graph_build_seconds"]
|
| 341 |
)
|
| 342 |
return graph
|
| 343 |
finally:
|
|
@@ -354,6 +628,12 @@ def ensure_runtime_graph() -> Dict[str, Any]:
|
|
| 354 |
|
| 355 |
def get_runtime_status() -> Dict[str, Any]:
|
| 356 |
graph = _RUNTIME["graph"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
return {
|
| 358 |
"graph_loaded": graph is not None,
|
| 359 |
"graph_loaded_at": _RUNTIME["graph_loaded_at"],
|
|
@@ -361,11 +641,19 @@ def get_runtime_status() -> Dict[str, Any]:
|
|
| 361 |
"graph_node_count": len((graph or {}).get("nodes", [])),
|
| 362 |
"graph_edge_count": len((graph or {}).get("edges", [])),
|
| 363 |
"graph_alias_count": len((graph or {}).get("alias_index", {})),
|
|
|
|
| 364 |
"last_graph_build_seconds": _RUNTIME["last_graph_build_seconds"],
|
| 365 |
"last_reindex_seconds": _RUNTIME["last_reindex_seconds"],
|
| 366 |
"graph_build_in_progress": _RUNTIME["graph_build_in_progress"],
|
| 367 |
"graph_snapshot_path": str(_snapshot_path()),
|
| 368 |
"graph_snapshot_exists": _snapshot_path().exists(),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
}
|
| 370 |
|
| 371 |
|
|
@@ -382,6 +670,7 @@ def save_current_runtime_graph_snapshot(force_build: bool = False) -> Dict[str,
|
|
| 382 |
"graph_nodes": len(graph.get("nodes", [])),
|
| 383 |
"graph_edges": len(graph.get("edges", [])),
|
| 384 |
"graph_aliases": len(graph.get("alias_index", {})),
|
|
|
|
| 385 |
}
|
| 386 |
|
| 387 |
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import json
|
| 4 |
import logging
|
| 5 |
import re
|
| 6 |
import time
|
| 7 |
from collections import defaultdict
|
| 8 |
from pathlib import Path
|
| 9 |
+
from threading import Lock
|
| 10 |
from typing import Any, Dict, List, Optional
|
| 11 |
|
| 12 |
from src.app.settings import settings
|
| 13 |
from src.rag.chunking_legal import legal_chunk
|
| 14 |
from src.rag.document_header import extract_document_header
|
| 15 |
from src.rag.ingestion import upsert_chunks
|
| 16 |
+
from src.rag.openai_clients import get_embedings, get_llm
|
| 17 |
from src.storage.qdrant_store import ensure_collection, get_qdrant_client
|
| 18 |
from src.utils.loader import load_document
|
| 19 |
|
|
|
|
| 22 |
except Exception:
|
| 23 |
semantic_merge_safe = None
|
| 24 |
|
| 25 |
+
try:
|
| 26 |
+
from src.rag.rerank_cross import get_cross_encoder
|
| 27 |
+
except Exception:
|
| 28 |
+
get_cross_encoder = None
|
| 29 |
+
|
| 30 |
|
| 31 |
_RUNTIME: Dict[str, Any] = {
|
| 32 |
"graph": None,
|
|
|
|
| 35 |
"last_graph_build_seconds": None,
|
| 36 |
"last_reindex_seconds": None,
|
| 37 |
"graph_build_in_progress": False,
|
| 38 |
+
"services_warmed_up": False,
|
| 39 |
+
"services_warmup_in_progress": False,
|
| 40 |
+
"last_services_warmup_seconds": None,
|
| 41 |
+
"startup_preload_completed": False,
|
| 42 |
+
"startup_preload_at": None,
|
| 43 |
+
"last_startup_preload_seconds": None,
|
| 44 |
+
"warmup_last_error": None,
|
| 45 |
}
|
| 46 |
|
| 47 |
logger = logging.getLogger(__name__)
|
| 48 |
+
_RUNTIME_LOCK = Lock()
|
| 49 |
+
|
| 50 |
+
SUMMARY_EDGE = "HAS_CHILD_SUMMARY"
|
| 51 |
+
SUMMARIZES_EDGE = "SUMMARIZES"
|
| 52 |
|
| 53 |
|
| 54 |
def _norm_space(text: str) -> str:
|
|
|
|
| 125 |
val = str(raw or "").strip()
|
| 126 |
if val:
|
| 127 |
aliases.append(val)
|
|
|
|
| 128 |
seen = set()
|
| 129 |
out: List[str] = []
|
| 130 |
for alias in aliases:
|
|
|
|
| 143 |
return alias_index
|
| 144 |
|
| 145 |
|
| 146 |
+
def _rebuild_runtime_maps(graph: Dict[str, Any]) -> Dict[str, Any]:
|
| 147 |
+
nodes = list(graph.get("nodes", []))
|
| 148 |
+
edges = list(graph.get("edges", []))
|
| 149 |
+
graph["node_index"] = {str(n["node_id"]): n for n in nodes if n.get("node_id")}
|
| 150 |
+
graph["alias_index"] = _build_alias_index(nodes)
|
| 151 |
+
graph["adjacency"] = _build_adjacency(edges)
|
| 152 |
+
graph["reverse_adjacency"] = _build_reverse_adjacency(edges)
|
| 153 |
+
return graph
|
| 154 |
+
|
| 155 |
+
|
| 156 |
def _save_graph_snapshot(graph: Dict[str, Any]) -> Path:
|
| 157 |
p = _snapshot_path()
|
| 158 |
p.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 175 |
except Exception as exc:
|
| 176 |
logger.warning("Cannot read graph snapshot %s: %s", p, exc)
|
| 177 |
return None
|
| 178 |
+
|
| 179 |
nodes = list(raw.get("nodes", []))
|
| 180 |
edges = list(raw.get("edges", []))
|
| 181 |
if not nodes:
|
| 182 |
return None
|
| 183 |
+
|
| 184 |
doc_index = dict(raw.get("doc_index", {}))
|
|
|
|
| 185 |
parent_to_children: Dict[str, List[str]] = defaultdict(list)
|
| 186 |
for n in nodes:
|
| 187 |
md = dict(n.get("metadata") or {})
|
|
|
|
| 211 |
node_id = str(n.get("node_id") or "")
|
| 212 |
md["children_ids"] = parent_to_children.get(node_id, md.get("children_ids", []))
|
| 213 |
md["sibling_ids"] = sibling_map.get(node_id, md.get("sibling_ids", []))
|
| 214 |
+
|
| 215 |
+
graph = {
|
|
|
|
| 216 |
"nodes": nodes,
|
| 217 |
"edges": edges,
|
|
|
|
|
|
|
| 218 |
"doc_index": doc_index,
|
|
|
|
|
|
|
| 219 |
}
|
| 220 |
+
graph = _augment_graph_with_runtime_summaries(graph)
|
| 221 |
+
graph = _rebuild_runtime_maps(graph)
|
| 222 |
+
return graph
|
| 223 |
|
| 224 |
|
| 225 |
def _apply_runtime_graph(graph: Dict[str, Any], built_seconds: float) -> Dict[str, Any]:
|
|
|
|
| 275 |
return sibling_map
|
| 276 |
|
| 277 |
|
| 278 |
+
def _graph_has_summary_nodes(graph: Dict[str, Any], *, doc_id: Optional[str] = None) -> bool:
|
| 279 |
+
for node in graph.get("nodes", []) or []:
|
| 280 |
+
md = node.get("metadata", {}) or {}
|
| 281 |
+
if md.get("artifact_type") != "summary":
|
| 282 |
+
continue
|
| 283 |
+
if doc_id is None or str(md.get("doc_id") or "") == str(doc_id):
|
| 284 |
+
return True
|
| 285 |
+
return False
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _candidate_doc_summary(doc_id: str, graph: Dict[str, Any], doc_meta: Dict[str, Any]) -> str:
|
| 289 |
+
for node in graph.get("nodes", []) or []:
|
| 290 |
+
md = node.get("metadata", {}) or {}
|
| 291 |
+
if str(md.get("doc_id") or "") != doc_id:
|
| 292 |
+
continue
|
| 293 |
+
text = _norm_space(str(md.get("doc_summary") or ""))
|
| 294 |
+
if text:
|
| 295 |
+
return text
|
| 296 |
+
parts = [
|
| 297 |
+
str(doc_meta.get("doc_type") or doc_meta.get("law_type") or "").strip(),
|
| 298 |
+
str(doc_meta.get("official_title") or doc_meta.get("law_name") or "").strip(),
|
| 299 |
+
]
|
| 300 |
+
fallback = " ".join(part for part in parts if part)
|
| 301 |
+
return _norm_space(fallback)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _summary_text_from_evidence(node: Dict[str, Any]) -> str:
|
| 305 |
+
return _norm_space(
|
| 306 |
+
str(node.get("retrieval_text") or node.get("rerank_text") or node.get("text") or "")
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _augment_graph_with_runtime_summaries(graph: Dict[str, Any]) -> Dict[str, Any]:
|
| 311 |
+
existing_nodes = list(graph.get("nodes", []))
|
| 312 |
+
existing_edges = list(graph.get("edges", []))
|
| 313 |
+
doc_index = dict(graph.get("doc_index", {}))
|
| 314 |
+
|
| 315 |
+
evidence_by_doc: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
|
| 316 |
+
for node in existing_nodes:
|
| 317 |
+
md = node.get("metadata", {}) or {}
|
| 318 |
+
if md.get("artifact_type") == "summary":
|
| 319 |
+
continue
|
| 320 |
+
doc_id = str(md.get("doc_id") or "").strip()
|
| 321 |
+
if doc_id:
|
| 322 |
+
evidence_by_doc[doc_id].append(node)
|
| 323 |
+
|
| 324 |
+
new_nodes: List[Dict[str, Any]] = []
|
| 325 |
+
new_edges: List[Dict[str, Any]] = []
|
| 326 |
+
|
| 327 |
+
for doc_id, evidence_nodes in evidence_by_doc.items():
|
| 328 |
+
if _graph_has_summary_nodes(graph, doc_id=doc_id):
|
| 329 |
+
continue
|
| 330 |
+
|
| 331 |
+
doc_meta = dict(doc_index.get(doc_id) or {})
|
| 332 |
+
evidence_ids = {str(n.get("node_id")) for n in evidence_nodes if n.get("node_id")}
|
| 333 |
+
summary_id_map: Dict[str, str] = {}
|
| 334 |
+
|
| 335 |
+
for node in evidence_nodes:
|
| 336 |
+
node_id = str(node.get("node_id") or "").strip()
|
| 337 |
+
if not node_id:
|
| 338 |
+
continue
|
| 339 |
+
summary_id_map[node_id] = f"{node_id}::summary"
|
| 340 |
+
|
| 341 |
+
root_summary_ids: List[str] = []
|
| 342 |
+
for node in evidence_nodes:
|
| 343 |
+
node_id = str(node.get("node_id") or "").strip()
|
| 344 |
+
if not node_id:
|
| 345 |
+
continue
|
| 346 |
+
md = dict(node.get("metadata") or {})
|
| 347 |
+
summary_id = summary_id_map[node_id]
|
| 348 |
+
parent_id = str(md.get("parent_id") or "").strip()
|
| 349 |
+
child_ids = [
|
| 350 |
+
summary_id_map[str(cid)]
|
| 351 |
+
for cid in (md.get("children_ids") or [])
|
| 352 |
+
if str(cid) in summary_id_map
|
| 353 |
+
]
|
| 354 |
+
if not parent_id or parent_id not in evidence_ids:
|
| 355 |
+
root_summary_ids.append(summary_id)
|
| 356 |
+
|
| 357 |
+
summary_md = {
|
| 358 |
+
**md,
|
| 359 |
+
"doc_id": doc_id,
|
| 360 |
+
"artifact_type": "summary",
|
| 361 |
+
"summary_level": str(node.get("node_type") or md.get("node_type") or "text").strip().lower() or "text",
|
| 362 |
+
"source_node_ids": [node_id],
|
| 363 |
+
"child_summary_ids": child_ids,
|
| 364 |
+
"title": md.get("path_title") or md.get("title") or md.get("article") or md.get("clause") or md.get("point") or md.get("section") or md.get("subsection") or node_id,
|
| 365 |
+
"law_name": md.get("law_name") or md.get("official_title") or doc_meta.get("official_title") or doc_meta.get("law_name") or "",
|
| 366 |
+
"law_type": md.get("law_type") or md.get("doc_type") or doc_meta.get("doc_type") or doc_meta.get("law_type") or "Unknown",
|
| 367 |
+
}
|
| 368 |
+
new_nodes.append(
|
| 369 |
+
{
|
| 370 |
+
"node_id": summary_id,
|
| 371 |
+
"node_type": "summary",
|
| 372 |
+
"text": _summary_text_from_evidence(node),
|
| 373 |
+
"retrieval_text": _summary_text_from_evidence(node),
|
| 374 |
+
"rerank_text": _summary_text_from_evidence(node),
|
| 375 |
+
"metadata": summary_md,
|
| 376 |
+
}
|
| 377 |
+
)
|
| 378 |
+
new_edges.append(
|
| 379 |
+
{
|
| 380 |
+
"source_id": summary_id,
|
| 381 |
+
"target_id": node_id,
|
| 382 |
+
"relation_type": SUMMARIZES_EDGE,
|
| 383 |
+
}
|
| 384 |
+
)
|
| 385 |
+
if parent_id and parent_id in summary_id_map:
|
| 386 |
+
new_edges.append(
|
| 387 |
+
{
|
| 388 |
+
"source_id": summary_id_map[parent_id],
|
| 389 |
+
"target_id": summary_id,
|
| 390 |
+
"relation_type": SUMMARY_EDGE,
|
| 391 |
+
}
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
doc_summary_text = _candidate_doc_summary(doc_id, graph, doc_meta)
|
| 395 |
+
if doc_summary_text:
|
| 396 |
+
doc_summary_id = f"{doc_id}::summary::document"
|
| 397 |
+
doc_title = _norm_space(
|
| 398 |
+
str(doc_meta.get("official_title") or doc_meta.get("law_name") or doc_meta.get("file_name") or doc_id)
|
| 399 |
+
)
|
| 400 |
+
doc_summary_md = {
|
| 401 |
+
**doc_meta,
|
| 402 |
+
"doc_id": doc_id,
|
| 403 |
+
"artifact_type": "summary",
|
| 404 |
+
"summary_level": "document",
|
| 405 |
+
"title": doc_title or doc_id,
|
| 406 |
+
"document_title": doc_title or doc_id,
|
| 407 |
+
"law_name": doc_meta.get("official_title") or doc_meta.get("law_name") or doc_title or doc_id,
|
| 408 |
+
"law_type": doc_meta.get("doc_type") or doc_meta.get("law_type") or "Unknown",
|
| 409 |
+
"child_summary_ids": sorted(set(root_summary_ids)),
|
| 410 |
+
"source_node_ids": [],
|
| 411 |
+
}
|
| 412 |
+
new_nodes.append(
|
| 413 |
+
{
|
| 414 |
+
"node_id": doc_summary_id,
|
| 415 |
+
"node_type": "summary",
|
| 416 |
+
"text": doc_summary_text,
|
| 417 |
+
"retrieval_text": doc_summary_text,
|
| 418 |
+
"rerank_text": doc_summary_text,
|
| 419 |
+
"metadata": doc_summary_md,
|
| 420 |
+
}
|
| 421 |
+
)
|
| 422 |
+
for child_summary_id in sorted(set(root_summary_ids)):
|
| 423 |
+
new_edges.append(
|
| 424 |
+
{
|
| 425 |
+
"source_id": doc_summary_id,
|
| 426 |
+
"target_id": child_summary_id,
|
| 427 |
+
"relation_type": SUMMARY_EDGE,
|
| 428 |
+
}
|
| 429 |
+
)
|
| 430 |
+
doc_index.setdefault(doc_id, {})["doc_summary_node_id"] = doc_summary_id
|
| 431 |
+
|
| 432 |
+
if not new_nodes and not new_edges:
|
| 433 |
+
return _rebuild_runtime_maps(graph)
|
| 434 |
+
|
| 435 |
+
graph["nodes"] = _dedup_nodes(existing_nodes + new_nodes)
|
| 436 |
+
graph["edges"] = _dedup_edges(existing_edges + new_edges)
|
| 437 |
+
graph["doc_index"] = doc_index
|
| 438 |
+
return _rebuild_runtime_maps(graph)
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def warmup_runtime_services(force: bool = False) -> Dict[str, Any]:
|
| 442 |
+
if _RUNTIME.get("services_warmed_up") and not force:
|
| 443 |
+
return {
|
| 444 |
+
"services_warmed_up": True,
|
| 445 |
+
"seconds": _RUNTIME.get("last_services_warmup_seconds"),
|
| 446 |
+
"error": _RUNTIME.get("warmup_last_error"),
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
with _RUNTIME_LOCK:
|
| 450 |
+
if _RUNTIME.get("services_warmed_up") and not force:
|
| 451 |
+
return {
|
| 452 |
+
"services_warmed_up": True,
|
| 453 |
+
"seconds": _RUNTIME.get("last_services_warmup_seconds"),
|
| 454 |
+
"error": _RUNTIME.get("warmup_last_error"),
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
start = time.perf_counter()
|
| 458 |
+
_RUNTIME["services_warmup_in_progress"] = True
|
| 459 |
+
error_messages: List[str] = []
|
| 460 |
+
warmed = {"llm": False, "embeddings": False, "cross_encoder": False}
|
| 461 |
+
|
| 462 |
+
try:
|
| 463 |
+
get_llm()
|
| 464 |
+
warmed["llm"] = True
|
| 465 |
+
except Exception as exc:
|
| 466 |
+
logger.warning("LLM warmup failed: %s", exc)
|
| 467 |
+
error_messages.append(f"llm: {exc}")
|
| 468 |
+
|
| 469 |
+
try:
|
| 470 |
+
get_embedings()
|
| 471 |
+
warmed["embeddings"] = True
|
| 472 |
+
except Exception as exc:
|
| 473 |
+
logger.warning("Embeddings warmup failed: %s", exc)
|
| 474 |
+
error_messages.append(f"embeddings: {exc}")
|
| 475 |
+
|
| 476 |
+
if get_cross_encoder is not None:
|
| 477 |
+
try:
|
| 478 |
+
get_cross_encoder()
|
| 479 |
+
warmed["cross_encoder"] = True
|
| 480 |
+
except Exception as exc:
|
| 481 |
+
logger.warning("Cross-encoder warmup failed: %s", exc)
|
| 482 |
+
error_messages.append(f"cross_encoder: {exc}")
|
| 483 |
+
|
| 484 |
+
seconds = time.perf_counter() - start
|
| 485 |
+
_RUNTIME["last_services_warmup_seconds"] = seconds
|
| 486 |
+
_RUNTIME["services_warmed_up"] = any(warmed.values()) and not error_messages
|
| 487 |
+
_RUNTIME["warmup_last_error"] = "; ".join(error_messages) if error_messages else None
|
| 488 |
+
_RUNTIME["services_warmup_in_progress"] = False
|
| 489 |
+
return {
|
| 490 |
+
"services_warmed_up": _RUNTIME["services_warmed_up"],
|
| 491 |
+
"seconds": seconds,
|
| 492 |
+
"details": warmed,
|
| 493 |
+
"error": _RUNTIME["warmup_last_error"],
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def preload_runtime_on_startup(
|
| 498 |
+
*,
|
| 499 |
+
preload_graph_snapshot: bool = True,
|
| 500 |
+
build_graph_if_missing: bool = False,
|
| 501 |
+
warm_services: bool = True,
|
| 502 |
+
) -> Dict[str, Any]:
|
| 503 |
+
start = time.perf_counter()
|
| 504 |
+
graph_loaded = False
|
| 505 |
+
built_graph = False
|
| 506 |
+
warmup_info: Optional[Dict[str, Any]] = None
|
| 507 |
+
|
| 508 |
+
if warm_services:
|
| 509 |
+
warmup_info = warmup_runtime_services()
|
| 510 |
+
|
| 511 |
+
if preload_graph_snapshot:
|
| 512 |
+
graph_loaded = preload_runtime_graph_from_snapshot()
|
| 513 |
+
|
| 514 |
+
if not graph_loaded and build_graph_if_missing:
|
| 515 |
+
build_runtime_graph()
|
| 516 |
+
graph_loaded = True
|
| 517 |
+
built_graph = True
|
| 518 |
+
|
| 519 |
+
seconds = time.perf_counter() - start
|
| 520 |
+
_RUNTIME["startup_preload_completed"] = True
|
| 521 |
+
_RUNTIME["startup_preload_at"] = time.time()
|
| 522 |
+
_RUNTIME["last_startup_preload_seconds"] = seconds
|
| 523 |
+
return {
|
| 524 |
+
"graph_loaded": graph_loaded,
|
| 525 |
+
"graph_built": built_graph,
|
| 526 |
+
"warmup": warmup_info,
|
| 527 |
+
"seconds": seconds,
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
|
| 531 |
def build_runtime_graph(
|
| 532 |
input_dir: Optional[str] = None,
|
| 533 |
glob_pattern: Optional[str] = None,
|
|
|
|
| 600 |
for key, val in doc_index[doc_id].items():
|
| 601 |
if md.get(key) in (None, "") and val not in (None, ""):
|
| 602 |
md[key] = val
|
|
|
|
| 603 |
graph = {
|
| 604 |
"nodes": nodes,
|
| 605 |
"edges": edges,
|
|
|
|
|
|
|
| 606 |
"doc_index": doc_index,
|
|
|
|
|
|
|
| 607 |
}
|
| 608 |
+
graph = _augment_graph_with_runtime_summaries(graph)
|
| 609 |
+
graph = _rebuild_runtime_maps(graph)
|
| 610 |
_apply_runtime_graph(graph, built_seconds=time.perf_counter() - start)
|
| 611 |
_save_graph_snapshot(graph)
|
| 612 |
logger.info(
|
| 613 |
"Graph build finished: docs=%s nodes=%s edges=%s aliases=%s took=%.2fs",
|
| 614 |
+
len(doc_index), len(graph.get("nodes", [])), len(graph.get("edges", [])), len(graph.get("alias_index", {})), _RUNTIME["last_graph_build_seconds"]
|
| 615 |
)
|
| 616 |
return graph
|
| 617 |
finally:
|
|
|
|
| 628 |
|
| 629 |
def get_runtime_status() -> Dict[str, Any]:
|
| 630 |
graph = _RUNTIME["graph"]
|
| 631 |
+
summary_count = 0
|
| 632 |
+
if graph is not None:
|
| 633 |
+
for node in graph.get("nodes", []) or []:
|
| 634 |
+
md = node.get("metadata", {}) or {}
|
| 635 |
+
if md.get("artifact_type") == "summary":
|
| 636 |
+
summary_count += 1
|
| 637 |
return {
|
| 638 |
"graph_loaded": graph is not None,
|
| 639 |
"graph_loaded_at": _RUNTIME["graph_loaded_at"],
|
|
|
|
| 641 |
"graph_node_count": len((graph or {}).get("nodes", [])),
|
| 642 |
"graph_edge_count": len((graph or {}).get("edges", [])),
|
| 643 |
"graph_alias_count": len((graph or {}).get("alias_index", {})),
|
| 644 |
+
"graph_summary_count": summary_count,
|
| 645 |
"last_graph_build_seconds": _RUNTIME["last_graph_build_seconds"],
|
| 646 |
"last_reindex_seconds": _RUNTIME["last_reindex_seconds"],
|
| 647 |
"graph_build_in_progress": _RUNTIME["graph_build_in_progress"],
|
| 648 |
"graph_snapshot_path": str(_snapshot_path()),
|
| 649 |
"graph_snapshot_exists": _snapshot_path().exists(),
|
| 650 |
+
"services_warmed_up": _RUNTIME["services_warmed_up"],
|
| 651 |
+
"services_warmup_in_progress": _RUNTIME["services_warmup_in_progress"],
|
| 652 |
+
"last_services_warmup_seconds": _RUNTIME["last_services_warmup_seconds"],
|
| 653 |
+
"startup_preload_completed": _RUNTIME["startup_preload_completed"],
|
| 654 |
+
"startup_preload_at": _RUNTIME["startup_preload_at"],
|
| 655 |
+
"last_startup_preload_seconds": _RUNTIME["last_startup_preload_seconds"],
|
| 656 |
+
"warmup_last_error": _RUNTIME["warmup_last_error"],
|
| 657 |
}
|
| 658 |
|
| 659 |
|
|
|
|
| 670 |
"graph_nodes": len(graph.get("nodes", [])),
|
| 671 |
"graph_edges": len(graph.get("edges", [])),
|
| 672 |
"graph_aliases": len(graph.get("alias_index", {})),
|
| 673 |
+
"graph_summaries": sum(1 for n in graph.get("nodes", []) if (n.get("metadata", {}) or {}).get("artifact_type") == "summary"),
|
| 674 |
}
|
| 675 |
|
| 676 |
|
src/rag/openai_clients.py
CHANGED
|
@@ -1,17 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
|
|
|
| 2 |
from src.app.settings import settings
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
def get_llm() -> ChatOpenAI:
|
|
|
|
|
|
|
|
|
|
| 5 |
if not settings.openai_api_key:
|
| 6 |
raise ValueError("Missing api key OPENAI")
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
def get_embedings() -> OpenAIEmbeddings:
|
|
|
|
|
|
|
|
|
|
| 10 |
if not settings.openai_api_key:
|
| 11 |
raise ValueError("Missing api key OPENAI")
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def get_embeding_dim(emb: OpenAIEmbeddings) -> int:
|
| 15 |
-
# gọi để biết dimension
|
| 16 |
v = emb.embed_query("dim_check")
|
| 17 |
return len(v)
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from threading import Lock
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
| 8 |
+
|
| 9 |
from src.app.settings import settings
|
| 10 |
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
_llm: Optional[ChatOpenAI] = None
|
| 14 |
+
_embeddings: Optional[OpenAIEmbeddings] = None
|
| 15 |
+
_client_lock = Lock()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
def get_llm() -> ChatOpenAI:
|
| 19 |
+
global _llm
|
| 20 |
+
if _llm is not None:
|
| 21 |
+
return _llm
|
| 22 |
if not settings.openai_api_key:
|
| 23 |
raise ValueError("Missing api key OPENAI")
|
| 24 |
+
with _client_lock:
|
| 25 |
+
if _llm is None:
|
| 26 |
+
_llm = ChatOpenAI(
|
| 27 |
+
model=settings.openai_model,
|
| 28 |
+
api_key=settings.openai_api_key,
|
| 29 |
+
temperature=0.2,
|
| 30 |
+
)
|
| 31 |
+
return _llm
|
| 32 |
+
|
| 33 |
|
| 34 |
def get_embedings() -> OpenAIEmbeddings:
|
| 35 |
+
global _embeddings
|
| 36 |
+
if _embeddings is not None:
|
| 37 |
+
return _embeddings
|
| 38 |
if not settings.openai_api_key:
|
| 39 |
raise ValueError("Missing api key OPENAI")
|
| 40 |
+
with _client_lock:
|
| 41 |
+
if _embeddings is None:
|
| 42 |
+
_embeddings = OpenAIEmbeddings(
|
| 43 |
+
model=settings.openai_embed_model,
|
| 44 |
+
api_key=settings.openai_api_key,
|
| 45 |
+
)
|
| 46 |
+
return _embeddings
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def warmup_openai_clients() -> None:
|
| 50 |
+
try:
|
| 51 |
+
get_llm()
|
| 52 |
+
get_embedings()
|
| 53 |
+
except Exception as exc:
|
| 54 |
+
logger.warning("OpenAI client warmup failed: %s", exc)
|
| 55 |
+
|
| 56 |
|
| 57 |
def get_embeding_dim(emb: OpenAIEmbeddings) -> int:
|
|
|
|
| 58 |
v = emb.embed_query("dim_check")
|
| 59 |
return len(v)
|
src/rag/qa_engine.py
CHANGED
|
@@ -31,7 +31,7 @@ def _doc_key(metadata: Dict[str, Any]) -> str:
|
|
| 31 |
|
| 32 |
def _group_for_context(passages: List[Dict[str, Any]], max_items: int) -> List[Dict[str, Any]]:
|
| 33 |
grouped: "OrderedDict[str, Dict[str, Any]]" = OrderedDict()
|
| 34 |
-
for p in passages:
|
| 35 |
md = dict(p.get("metadata") or {})
|
| 36 |
key = _doc_key(md)
|
| 37 |
bucket = grouped.setdefault(
|
|
@@ -50,19 +50,22 @@ def _group_for_context(passages: List[Dict[str, Any]], max_items: int) -> List[D
|
|
| 50 |
|
| 51 |
docs = list(grouped.values())
|
| 52 |
docs.sort(key=lambda x: float(x.get("doc_best_score", 0.0)), reverse=True)
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
if
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
if
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
|
| 67 |
|
| 68 |
def _build_context(passages: List[Dict[str, Any]], max_items: int) -> str:
|
|
@@ -70,18 +73,27 @@ def _build_context(passages: List[Dict[str, Any]], max_items: int) -> str:
|
|
| 70 |
lines: List[str] = []
|
| 71 |
for idx, group in enumerate(groups, start=1):
|
| 72 |
lines.append(f"[Nguồn {idx}] {group['doc_type']} | {group['doc_title']} | source={group['source']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
for j, item in enumerate(group["items"], start=1):
|
| 74 |
md = dict(item.get("metadata") or {})
|
| 75 |
lines.append(
|
| 76 |
-
f" - [
|
| 77 |
)
|
| 78 |
-
|
|
|
|
| 79 |
lines.append("")
|
| 80 |
return "\n".join(lines).strip()
|
| 81 |
|
| 82 |
|
| 83 |
def _to_source_item(p: Dict[str, Any]) -> SourceItem:
|
| 84 |
md = dict(p.get("metadata") or {})
|
|
|
|
| 85 |
return SourceItem(
|
| 86 |
chunk_id=str(md.get("chunk_id") or md.get("node_id") or p.get("node_id") or ""),
|
| 87 |
law_name=str(md.get("official_title") or md.get("law_name") or ""),
|
|
@@ -89,7 +101,7 @@ def _to_source_item(p: Dict[str, Any]) -> SourceItem:
|
|
| 89 |
year=int(md.get("year") or 0),
|
| 90 |
source=str(md.get("source") or md.get("issuing_agency") or ""),
|
| 91 |
article=md.get("article"),
|
| 92 |
-
snippet=
|
| 93 |
)
|
| 94 |
|
| 95 |
|
|
|
|
| 31 |
|
| 32 |
def _group_for_context(passages: List[Dict[str, Any]], max_items: int) -> List[Dict[str, Any]]:
|
| 33 |
grouped: "OrderedDict[str, Dict[str, Any]]" = OrderedDict()
|
| 34 |
+
for p in passages[:max_items]:
|
| 35 |
md = dict(p.get("metadata") or {})
|
| 36 |
key = _doc_key(md)
|
| 37 |
bucket = grouped.setdefault(
|
|
|
|
| 50 |
|
| 51 |
docs = list(grouped.values())
|
| 52 |
docs.sort(key=lambda x: float(x.get("doc_best_score", 0.0)), reverse=True)
|
| 53 |
+
return docs
|
| 54 |
|
| 55 |
+
|
| 56 |
+
def _dedup_blocks(texts: List[str]) -> List[str]:
|
| 57 |
+
seen = set()
|
| 58 |
+
out: List[str] = []
|
| 59 |
+
for text in texts:
|
| 60 |
+
block = _norm_space(text)
|
| 61 |
+
if not block:
|
| 62 |
+
continue
|
| 63 |
+
key = block.lower()
|
| 64 |
+
if key in seen:
|
| 65 |
+
continue
|
| 66 |
+
seen.add(key)
|
| 67 |
+
out.append(block)
|
| 68 |
+
return out
|
| 69 |
|
| 70 |
|
| 71 |
def _build_context(passages: List[Dict[str, Any]], max_items: int) -> str:
|
|
|
|
| 73 |
lines: List[str] = []
|
| 74 |
for idx, group in enumerate(groups, start=1):
|
| 75 |
lines.append(f"[Nguồn {idx}] {group['doc_type']} | {group['doc_title']} | source={group['source']}")
|
| 76 |
+
|
| 77 |
+
shared_blocks = _dedup_blocks([str(item.get("shared_text") or "") for item in group["items"]])
|
| 78 |
+
if shared_blocks:
|
| 79 |
+
lines.append("[Ngữ cảnh chung của văn bản]")
|
| 80 |
+
for block in shared_blocks:
|
| 81 |
+
lines.append(block)
|
| 82 |
+
|
| 83 |
for j, item in enumerate(group["items"], start=1):
|
| 84 |
md = dict(item.get("metadata") or {})
|
| 85 |
lines.append(
|
| 86 |
+
f" - [Passage {idx}.{j}] path={md.get('path_title') or '-'} | article={md.get('article') or '-'} | clause={md.get('clause') or '-'} | point={md.get('point') or '-'}"
|
| 87 |
)
|
| 88 |
+
local_text = str(item.get("local_text") or item.get("bundle_text") or item.get("retrieval_text") or item.get("text") or "")
|
| 89 |
+
lines.append(f" {local_text}")
|
| 90 |
lines.append("")
|
| 91 |
return "\n".join(lines).strip()
|
| 92 |
|
| 93 |
|
| 94 |
def _to_source_item(p: Dict[str, Any]) -> SourceItem:
|
| 95 |
md = dict(p.get("metadata") or {})
|
| 96 |
+
snippet = str(p.get("local_text") or p.get("bundle_text") or p.get("retrieval_text") or p.get("text") or p.get("snippet") or "")[:500]
|
| 97 |
return SourceItem(
|
| 98 |
chunk_id=str(md.get("chunk_id") or md.get("node_id") or p.get("node_id") or ""),
|
| 99 |
law_name=str(md.get("official_title") or md.get("law_name") or ""),
|
|
|
|
| 101 |
year=int(md.get("year") or 0),
|
| 102 |
source=str(md.get("source") or md.get("issuing_agency") or ""),
|
| 103 |
article=md.get("article"),
|
| 104 |
+
snippet=snippet,
|
| 105 |
)
|
| 106 |
|
| 107 |
|
src/rag/retrieval_pipeline.py
CHANGED
|
@@ -1,510 +1,115 @@
|
|
| 1 |
-
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
-
import
|
| 5 |
import logging
|
| 6 |
-
import
|
| 7 |
-
from collections import
|
| 8 |
-
from typing import Any, Dict, List, Optional, Set, Tuple
|
| 9 |
-
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
from src.app.settings import settings
|
| 13 |
-
from src.rag.auto_filter import infer_filters
|
| 14 |
-
from src.rag.bm25_corpus import load_bm25_stats
|
| 15 |
-
from src.rag.hybrid import hybrid_rank
|
| 16 |
-
from src.rag.legal_versioning import annotate_graph_with_versioning
|
| 17 |
-
from src.rag.openai_clients import get_embedings, get_llm
|
| 18 |
from src.rag.rerank_cross import cross_rerank
|
| 19 |
-
from src.storage.qdrant_store import get_qdrant_client, search_qdrant
|
| 20 |
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
"RELATED_IN_CONTEXT",
|
| 33 |
-
}
|
| 34 |
-
CHANGE_RELATIONS = {
|
| 35 |
-
"AMENDS",
|
| 36 |
-
"REPEALS",
|
| 37 |
-
"REPLACES",
|
| 38 |
-
"PARTIALLY_AMENDS",
|
| 39 |
-
"PARTIALLY_REPEALS",
|
| 40 |
-
"EFFECTIVE_FROM",
|
| 41 |
-
"REFERS_TO",
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
-
SANCTION_KEYWORDS = ["bị gì", "xử phạt", "chế tài", "phạt", "truy cứu", "hình sự", "hành chính"]
|
| 45 |
-
CHANGE_KEYWORDS = ["sửa đổi", "bổ sung", "bãi bỏ", "thay thế", "được sửa", "bị sửa", "bản nào"]
|
| 46 |
-
EFFECTIVE_KEYWORDS = ["hiệu lực", "còn hiệu lực", "hết hiệu lực", "áp dụng", "hiện hành"]
|
| 47 |
-
ENUMERATE_KEYWORDS = ["liệt kê", "gồm những", "gồm các", "các trường hợp", "từng khoản", "từng điểm", "bao gồm"]
|
| 48 |
-
SUMMARY_KEYWORDS = ["nói về gì", "thuộc nội dung nào", "tóm tắt", "khái quát", "bối cảnh", "ý nghĩa", "tinh thần chung"]
|
| 49 |
-
COMPARE_KEYWORDS = ["so sánh", "khác nhau", "đối chiếu", "phân biệt"]
|
| 50 |
-
PROCEDURE_KEYWORDS = ["thủ tục", "hồ sơ", "trình tự", "cách làm", "điều kiện", "quy trình"]
|
| 51 |
-
VALIDITY_KEYWORDS = ["còn hiệu lực", "hết hiệu lực", "hiệu lực", "hiện hành"]
|
| 52 |
-
GUIDANCE_KEYWORDS = ["hướng dẫn", "quy định chi tiết", "nghị định", "thông tư", "văn bản nào"]
|
| 53 |
-
|
| 54 |
-
ARTICLE_RE = re.compile(r"điều\s+(\d+)", re.IGNORECASE)
|
| 55 |
-
CLAUSE_RE = re.compile(r"khoản\s+(\d+)", re.IGNORECASE)
|
| 56 |
-
POINT_RE = re.compile(r"điểm\s+([a-zđ])", re.IGNORECASE)
|
| 57 |
-
YEAR_RE = re.compile(r"\b(19\d{2}|20\d{2})\b")
|
| 58 |
-
|
| 59 |
-
LEVEL_ORDER = {"document": 0, "article": 1, "clause": 2, "point": 3}
|
| 60 |
-
NODE_TO_LEVEL = {
|
| 61 |
-
"summary": "document",
|
| 62 |
-
"article": "article",
|
| 63 |
-
"section": "article",
|
| 64 |
-
"subsection": "article",
|
| 65 |
-
"clause": "clause",
|
| 66 |
-
"point": "point",
|
| 67 |
-
"bullet": "point",
|
| 68 |
-
"text": "point",
|
| 69 |
-
"amendment": "clause",
|
| 70 |
-
"effective": "clause",
|
| 71 |
-
"transition": "clause",
|
| 72 |
-
"responsibility": "clause",
|
| 73 |
-
"applicability": "clause",
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
_BM25_CACHE: Dict[str, Any] = {}
|
| 77 |
-
|
| 78 |
-
QUERY_ANALYSIS_SYSTEM_PROMPT = """
|
| 79 |
-
Bạn là bộ phân tích truy vấn cho GraphRAG pháp luật Việt Nam.
|
| 80 |
-
|
| 81 |
-
Nhiệm vụ duy nhất:
|
| 82 |
-
- Phân loại truy vấn.
|
| 83 |
-
- Chọn chiến lược retrieval.
|
| 84 |
-
- Sinh biến thể truy vấn để tăng recall.
|
| 85 |
-
- Không được trả lời nội dung pháp luật.
|
| 86 |
-
- Không tự thêm thông tin pháp lý ngoài câu hỏi gốc.
|
| 87 |
-
- Chỉ trả về JSON hợp lệ, không markdown.
|
| 88 |
-
|
| 89 |
-
Bạn phải cân nhắc đồng thời:
|
| 90 |
-
1. Câu hỏi nên ưu tiên trong cùng một văn bản hay nhiều văn bản.
|
| 91 |
-
2. Nên ưu tiên cùng cấp, cấp trên, cấp dưới hay phối hợp.
|
| 92 |
-
3. Có cần lôi thêm chunk cha, chunk con, chunk anh em, văn bản sửa đổi, văn bản hướng dẫn hay không.
|
| 93 |
-
|
| 94 |
-
Schema:
|
| 95 |
-
{
|
| 96 |
-
"mode": "general | change | effective | sanction",
|
| 97 |
-
"query_type": "locate | enumerate | summarize | compare | applicability | procedure | validity | cross_reference",
|
| 98 |
-
"document_scope": "single_doc | multi_doc",
|
| 99 |
-
"target_level": "document | article | clause | point",
|
| 100 |
-
"level_strategy": "same_level | parent | children | sibling | mixed",
|
| 101 |
-
"answer_granularity": "document | article | clause | point",
|
| 102 |
-
"needs_version_reasoning": true,
|
| 103 |
-
"explicit_refs": {
|
| 104 |
-
"document_name": null,
|
| 105 |
-
"article": "Điều 3",
|
| 106 |
-
"clause": "Khoản 2",
|
| 107 |
-
"point": "Điểm a",
|
| 108 |
-
"year": 2020
|
| 109 |
-
},
|
| 110 |
-
"needs": {
|
| 111 |
-
"self": true,
|
| 112 |
-
"parent": false,
|
| 113 |
-
"children": false,
|
| 114 |
-
"siblings": false,
|
| 115 |
-
"linked_docs": false,
|
| 116 |
-
"amendments": false,
|
| 117 |
-
"guidance_docs": false
|
| 118 |
-
},
|
| 119 |
-
"confidence": 0.0,
|
| 120 |
-
"reason": "...",
|
| 121 |
-
"query_variants": ["...", "...", "..."]
|
| 122 |
-
}
|
| 123 |
-
""".strip()
|
| 124 |
|
| 125 |
|
| 126 |
def _norm_space(text: str) -> str:
|
| 127 |
return " ".join((text or "").split()).strip()
|
| 128 |
|
| 129 |
|
| 130 |
-
def
|
| 131 |
-
|
| 132 |
-
if cached is not None:
|
| 133 |
-
return cached
|
| 134 |
-
try:
|
| 135 |
-
stats = load_bm25_stats(path)
|
| 136 |
-
except Exception:
|
| 137 |
-
stats = {"idf": {}, "avgdl": 0.0}
|
| 138 |
-
_BM25_CACHE[path] = stats
|
| 139 |
-
return stats
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
def ensure_versioning_ready(graph: Dict[str, Any]) -> Dict[str, Any]:
|
| 143 |
-
if graph.get("_versioning_ready"):
|
| 144 |
-
return graph
|
| 145 |
-
graph = annotate_graph_with_versioning(graph)
|
| 146 |
-
graph["_versioning_ready"] = True
|
| 147 |
-
return graph
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def detect_query_mode(question: str) -> str:
|
| 151 |
-
q = (question or "").lower()
|
| 152 |
-
if any(k in q for k in CHANGE_KEYWORDS):
|
| 153 |
-
return "change"
|
| 154 |
-
if any(k in q for k in EFFECTIVE_KEYWORDS):
|
| 155 |
-
return "effective"
|
| 156 |
-
if any(k in q for k in SANCTION_KEYWORDS):
|
| 157 |
-
return "sanction"
|
| 158 |
-
return "general"
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
def detect_query_type(question: str) -> str:
|
| 162 |
-
q = (question or "").lower()
|
| 163 |
-
has_anchor = bool(ARTICLE_RE.search(q) or CLAUSE_RE.search(q) or POINT_RE.search(q))
|
| 164 |
-
if any(k in q for k in COMPARE_KEYWORDS):
|
| 165 |
-
return "compare"
|
| 166 |
-
if any(k in q for k in ENUMERATE_KEYWORDS):
|
| 167 |
-
return "enumerate"
|
| 168 |
-
if any(k in q for k in PROCEDURE_KEYWORDS):
|
| 169 |
-
return "procedure"
|
| 170 |
-
if any(k in q for k in VALIDITY_KEYWORDS):
|
| 171 |
-
return "validity"
|
| 172 |
-
if any(k in q for k in CHANGE_KEYWORDS) or any(k in q for k in GUIDANCE_KEYWORDS):
|
| 173 |
-
return "cross_reference"
|
| 174 |
-
if any(k in q for k in SUMMARY_KEYWORDS):
|
| 175 |
-
return "summarize"
|
| 176 |
-
if has_anchor:
|
| 177 |
-
return "locate"
|
| 178 |
-
return "applicability"
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def _derive_answer_granularity(*, target_level: str, level_strategy: str) -> str:
|
| 182 |
-
target_level = str(target_level or "document")
|
| 183 |
-
level_strategy = str(level_strategy or "mixed")
|
| 184 |
-
if level_strategy == "children":
|
| 185 |
-
return {
|
| 186 |
-
"document": "article",
|
| 187 |
-
"article": "clause",
|
| 188 |
-
"clause": "point",
|
| 189 |
-
"point": "point",
|
| 190 |
-
}.get(target_level, target_level)
|
| 191 |
-
if level_strategy == "parent":
|
| 192 |
-
return {
|
| 193 |
-
"point": "clause",
|
| 194 |
-
"clause": "article",
|
| 195 |
-
"article": "document",
|
| 196 |
-
"document": "document",
|
| 197 |
-
}.get(target_level, target_level)
|
| 198 |
-
return target_level
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def _derive_needs(*, query_type: str, document_scope: str, level_strategy: str, mode: str) -> Dict[str, bool]:
|
| 202 |
-
linked_docs = document_scope == "multi_doc"
|
| 203 |
-
needs = {
|
| 204 |
-
"self": query_type in {"locate", "enumerate", "summarize", "compare"} or document_scope == "single_doc",
|
| 205 |
-
"parent": level_strategy in {"parent", "mixed"},
|
| 206 |
-
"children": level_strategy in {"children", "mixed"},
|
| 207 |
-
"siblings": level_strategy in {"same_level", "sibling", "mixed"} and query_type == "compare",
|
| 208 |
-
"linked_docs": linked_docs,
|
| 209 |
-
"amendments": mode in {"change", "effective"} or query_type in {"validity", "cross_reference"},
|
| 210 |
-
"guidance_docs": linked_docs and query_type in {"procedure", "applicability", "cross_reference"},
|
| 211 |
-
}
|
| 212 |
-
return needs
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
def _finalize_query_profile(question: str, profile: Dict[str, Any]) -> Dict[str, Any]:
|
| 216 |
-
q = (question or "").lower()
|
| 217 |
-
explicit_refs = dict(profile.get("explicit_refs") or {})
|
| 218 |
-
|
| 219 |
-
article_match = ARTICLE_RE.search(question or "")
|
| 220 |
-
clause_match = CLAUSE_RE.search(question or "")
|
| 221 |
-
point_match = POINT_RE.search(question or "")
|
| 222 |
-
year_match = YEAR_RE.search(question or "")
|
| 223 |
-
|
| 224 |
-
if article_match:
|
| 225 |
-
explicit_refs["article"] = f"Điều {article_match.group(1)}"
|
| 226 |
-
if clause_match:
|
| 227 |
-
explicit_refs["clause"] = f"Khoản {clause_match.group(1)}"
|
| 228 |
-
if point_match:
|
| 229 |
-
explicit_refs["point"] = f"Điểm {point_match.group(1).lower()}"
|
| 230 |
-
if year_match:
|
| 231 |
-
try:
|
| 232 |
-
explicit_refs["year"] = int(year_match.group(1))
|
| 233 |
-
except Exception:
|
| 234 |
-
pass
|
| 235 |
-
|
| 236 |
-
profile["explicit_refs"] = explicit_refs
|
| 237 |
-
|
| 238 |
-
if explicit_refs.get("point"):
|
| 239 |
-
profile["target_level"] = "point"
|
| 240 |
-
elif explicit_refs.get("clause"):
|
| 241 |
-
profile["target_level"] = "clause"
|
| 242 |
-
elif explicit_refs.get("article"):
|
| 243 |
-
profile["target_level"] = "article"
|
| 244 |
-
else:
|
| 245 |
-
profile["target_level"] = str(profile.get("target_level") or "document")
|
| 246 |
-
|
| 247 |
-
query_type = str(profile.get("query_type") or detect_query_type(question))
|
| 248 |
-
mode = str(profile.get("mode") or detect_query_mode(question))
|
| 249 |
-
|
| 250 |
-
if any(k in q for k in COMPARE_KEYWORDS):
|
| 251 |
-
level_strategy = "sibling" if explicit_refs.get("article") or explicit_refs.get("clause") else "same_level"
|
| 252 |
-
elif any(k in q for k in ENUMERATE_KEYWORDS):
|
| 253 |
-
level_strategy = "children"
|
| 254 |
-
elif any(k in q for k in SUMMARY_KEYWORDS):
|
| 255 |
-
level_strategy = "parent"
|
| 256 |
-
else:
|
| 257 |
-
level_strategy = str(profile.get("level_strategy") or "same_level")
|
| 258 |
-
|
| 259 |
-
if mode in {"change", "effective"} or any(k in q for k in PROCEDURE_KEYWORDS) or any(k in q for k in VALIDITY_KEYWORDS) or any(k in q for k in GUIDANCE_KEYWORDS):
|
| 260 |
-
document_scope = "multi_doc"
|
| 261 |
-
elif explicit_refs.get("article") or explicit_refs.get("clause") or explicit_refs.get("point"):
|
| 262 |
-
document_scope = "single_doc"
|
| 263 |
-
else:
|
| 264 |
-
document_scope = str(profile.get("document_scope") or "multi_doc")
|
| 265 |
-
|
| 266 |
-
if level_strategy not in {"same_level", "parent", "children", "sibling", "mixed"}:
|
| 267 |
-
level_strategy = "mixed"
|
| 268 |
-
if document_scope not in {"single_doc", "multi_doc"}:
|
| 269 |
-
document_scope = "multi_doc"
|
| 270 |
-
|
| 271 |
-
profile["mode"] = mode
|
| 272 |
-
profile["query_type"] = query_type
|
| 273 |
-
profile["document_scope"] = document_scope
|
| 274 |
-
profile["level_strategy"] = level_strategy
|
| 275 |
-
profile["answer_granularity"] = _derive_answer_granularity(
|
| 276 |
-
target_level=str(profile.get("target_level") or "document"),
|
| 277 |
-
level_strategy=level_strategy,
|
| 278 |
-
)
|
| 279 |
-
profile["needs"] = _derive_needs(
|
| 280 |
-
query_type=query_type,
|
| 281 |
-
document_scope=document_scope,
|
| 282 |
-
level_strategy=level_strategy,
|
| 283 |
-
mode=mode,
|
| 284 |
-
)
|
| 285 |
-
profile["needs_version_reasoning"] = bool(profile.get("needs_version_reasoning")) or profile["needs"]["amendments"]
|
| 286 |
-
|
| 287 |
-
confidence = profile.get("confidence", 0.0)
|
| 288 |
-
try:
|
| 289 |
-
confidence = float(confidence)
|
| 290 |
-
except Exception:
|
| 291 |
-
confidence = 0.0
|
| 292 |
-
profile["confidence"] = max(0.0, min(1.0, confidence))
|
| 293 |
-
profile["reason"] = _norm_space(str(profile.get("reason") or ""))[:200]
|
| 294 |
-
|
| 295 |
-
return profile
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
def _fallback_query_profile(question: str, *, n_variants: int = 3) -> Dict[str, Any]:
|
| 299 |
-
q = _norm_space(question)
|
| 300 |
-
article_match = ARTICLE_RE.search(q)
|
| 301 |
-
clause_match = CLAUSE_RE.search(q)
|
| 302 |
-
point_match = POINT_RE.search(q)
|
| 303 |
-
year_match = YEAR_RE.search(q)
|
| 304 |
-
|
| 305 |
-
if point_match:
|
| 306 |
-
target_level = "point"
|
| 307 |
-
elif clause_match:
|
| 308 |
-
target_level = "clause"
|
| 309 |
-
elif article_match:
|
| 310 |
-
target_level = "article"
|
| 311 |
-
else:
|
| 312 |
-
target_level = "document"
|
| 313 |
-
|
| 314 |
-
profile = {
|
| 315 |
-
"mode": detect_query_mode(q),
|
| 316 |
-
"query_type": detect_query_type(q),
|
| 317 |
-
"document_scope": "single_doc" if (article_match or clause_match or point_match) else "multi_doc",
|
| 318 |
-
"target_level": target_level,
|
| 319 |
-
"level_strategy": "same_level" if (article_match or clause_match or point_match) else "mixed",
|
| 320 |
-
"answer_granularity": target_level,
|
| 321 |
-
"needs_version_reasoning": detect_query_mode(q) in {"change", "effective"},
|
| 322 |
-
"explicit_refs": {
|
| 323 |
-
"document_name": None,
|
| 324 |
-
"article": f"Điều {article_match.group(1)}" if article_match else None,
|
| 325 |
-
"clause": f"Khoản {clause_match.group(1)}" if clause_match else None,
|
| 326 |
-
"point": f"Điểm {point_match.group(1).lower()}" if point_match else None,
|
| 327 |
-
"year": int(year_match.group(1)) if year_match else None,
|
| 328 |
-
},
|
| 329 |
-
"needs": {},
|
| 330 |
-
"confidence": 0.0,
|
| 331 |
-
"reason": "fallback_heuristic",
|
| 332 |
-
"query_variants": [q][: max(1, n_variants + 1)],
|
| 333 |
-
}
|
| 334 |
-
return _finalize_query_profile(q, profile)
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
def _extract_json_payload(raw: str) -> Dict[str, Any]:
|
| 338 |
-
text = str(raw or "").strip()
|
| 339 |
-
if text.startswith("```"):
|
| 340 |
-
lines = text.splitlines()
|
| 341 |
-
if lines and lines[0].startswith("```"):
|
| 342 |
-
lines = lines[1:]
|
| 343 |
-
if lines and lines[-1].startswith("```"):
|
| 344 |
-
lines = lines[:-1]
|
| 345 |
-
if lines and lines[0].strip().lower() == "json":
|
| 346 |
-
lines = lines[1:]
|
| 347 |
-
text = "\n".join(lines).strip()
|
| 348 |
-
return json.loads(text)
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
def analyze_query_with_llm(question: str, *, n_variants: int = 3) -> Dict[str, Any]:
|
| 352 |
-
fallback = _fallback_query_profile(question, n_variants=n_variants)
|
| 353 |
-
q = _norm_space(question)
|
| 354 |
-
if not q:
|
| 355 |
-
return fallback
|
| 356 |
-
|
| 357 |
-
try:
|
| 358 |
-
llm = get_llm()
|
| 359 |
-
response = llm.invoke(
|
| 360 |
-
[
|
| 361 |
-
SystemMessage(content=QUERY_ANALYSIS_SYSTEM_PROMPT),
|
| 362 |
-
HumanMessage(
|
| 363 |
-
content=(
|
| 364 |
-
f"Phân tích truy vấn sau và sinh tối đa {n_variants} biến thể truy vấn.\n"
|
| 365 |
-
f"Câu hỏi gốc: {q}"
|
| 366 |
-
)
|
| 367 |
-
),
|
| 368 |
-
]
|
| 369 |
-
)
|
| 370 |
-
parsed = _extract_json_payload(getattr(response, "content", "") or "")
|
| 371 |
-
out = dict(fallback)
|
| 372 |
-
|
| 373 |
-
mode = str(parsed.get("mode") or "").strip().lower()
|
| 374 |
-
if mode in {"general", "change", "effective", "sanction"}:
|
| 375 |
-
out["mode"] = mode
|
| 376 |
-
|
| 377 |
-
query_type = str(parsed.get("query_type") or "").strip().lower()
|
| 378 |
-
if query_type in {"locate", "enumerate", "summarize", "compare", "applicability", "procedure", "validity", "cross_reference"}:
|
| 379 |
-
out["query_type"] = query_type
|
| 380 |
-
|
| 381 |
-
document_scope = str(parsed.get("document_scope") or "").strip().lower()
|
| 382 |
-
if document_scope in {"single_doc", "multi_doc"}:
|
| 383 |
-
out["document_scope"] = document_scope
|
| 384 |
|
| 385 |
-
target_level = str(parsed.get("target_level") or "").strip().lower()
|
| 386 |
-
if target_level in {"document", "article", "clause", "point"}:
|
| 387 |
-
out["target_level"] = target_level
|
| 388 |
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
|
| 393 |
-
answer_granularity = str(parsed.get("answer_granularity") or "").strip().lower()
|
| 394 |
-
if answer_granularity in {"document", "article", "clause", "point"}:
|
| 395 |
-
out["answer_granularity"] = answer_granularity
|
| 396 |
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
|
| 401 |
-
explicit_refs = dict(out.get("explicit_refs") or {})
|
| 402 |
-
llm_refs = parsed.get("explicit_refs") or {}
|
| 403 |
-
if isinstance(llm_refs, dict):
|
| 404 |
-
for key in ["document_name", "article", "clause", "point", "year"]:
|
| 405 |
-
value = llm_refs.get(key)
|
| 406 |
-
if value not in (None, ""):
|
| 407 |
-
explicit_refs[key] = value
|
| 408 |
-
out["explicit_refs"] = explicit_refs
|
| 409 |
-
|
| 410 |
-
llm_needs = parsed.get("needs") or {}
|
| 411 |
-
if isinstance(llm_needs, dict):
|
| 412 |
-
base_needs = dict(out.get("needs") or {})
|
| 413 |
-
for key in ["self", "parent", "children", "siblings", "linked_docs", "amendments", "guidance_docs"]:
|
| 414 |
-
if key in llm_needs:
|
| 415 |
-
base_needs[key] = bool(llm_needs.get(key))
|
| 416 |
-
out["needs"] = base_needs
|
| 417 |
-
|
| 418 |
-
out["confidence"] = parsed.get("confidence", out.get("confidence", 0.0))
|
| 419 |
-
out["reason"] = parsed.get("reason", out.get("reason", ""))
|
| 420 |
-
|
| 421 |
-
variants = []
|
| 422 |
-
seen = set()
|
| 423 |
-
for item in [q] + list(parsed.get("query_variants") or []):
|
| 424 |
-
s = _norm_space(str(item))
|
| 425 |
-
key = s.lower()
|
| 426 |
-
if not s or key in seen:
|
| 427 |
-
continue
|
| 428 |
-
seen.add(key)
|
| 429 |
-
variants.append(s)
|
| 430 |
-
if len(variants) >= n_variants + 1:
|
| 431 |
-
break
|
| 432 |
-
out["query_variants"] = variants or fallback["query_variants"]
|
| 433 |
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
|
| 439 |
|
| 440 |
-
def
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
|
| 449 |
|
| 450 |
-
def
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
elif status == "effective_info_found":
|
| 466 |
-
bonus += 0.22
|
| 467 |
-
if legal_role in {"effective", "responsibility", "transition"}:
|
| 468 |
-
bonus += 0.10
|
| 469 |
-
elif mode == "change":
|
| 470 |
-
if status == "repealed":
|
| 471 |
-
bonus += 0.20
|
| 472 |
-
elif status == "replaced":
|
| 473 |
-
bonus += 0.22
|
| 474 |
-
elif status == "amended":
|
| 475 |
-
bonus += 0.25
|
| 476 |
-
elif status == "effective_info_found":
|
| 477 |
-
bonus += 0.05
|
| 478 |
-
if legal_role in {"amendment", "effective", "transition", "correction", "replacement"}:
|
| 479 |
-
bonus += 0.10
|
| 480 |
-
if node_type in {"amendment", "effective"}:
|
| 481 |
-
bonus += 0.08
|
| 482 |
-
else:
|
| 483 |
-
if status == "repealed":
|
| 484 |
-
bonus -= 0.12
|
| 485 |
-
elif status in {"amended", "replaced", "effective_info_found"}:
|
| 486 |
-
bonus += 0.04
|
| 487 |
-
|
| 488 |
-
if event_count > 0:
|
| 489 |
-
bonus += min(event_count * 0.02, 0.08)
|
| 490 |
-
|
| 491 |
-
return float(bonus)
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
def _extract_node_id_from_payload(payload: Dict[str, Any]) -> Optional[str]:
|
| 495 |
-
if not payload:
|
| 496 |
-
return None
|
| 497 |
-
md = payload.get("metadata")
|
| 498 |
-
if isinstance(md, dict) and md.get("node_id"):
|
| 499 |
-
return str(md["node_id"])
|
| 500 |
-
for key in ["node_id", "chunk_id", "id"]:
|
| 501 |
-
if payload.get(key):
|
| 502 |
-
return str(payload[key])
|
| 503 |
-
return None
|
| 504 |
|
| 505 |
|
| 506 |
def _candidate_doc_key(metadata: Dict[str, Any]) -> str:
|
| 507 |
-
law_name = str(metadata.get("law_name") or "").strip().lower()
|
| 508 |
if law_name:
|
| 509 |
return law_name
|
| 510 |
|
|
@@ -512,7 +117,7 @@ def _candidate_doc_key(metadata: Dict[str, Any]) -> str:
|
|
| 512 |
if document_id:
|
| 513 |
return document_id
|
| 514 |
|
| 515 |
-
file_name = str(metadata.get("file_name") or metadata.get("filename") or "").strip().lower()
|
| 516 |
if file_name:
|
| 517 |
return file_name
|
| 518 |
|
|
@@ -524,716 +129,688 @@ def _candidate_doc_key(metadata: Dict[str, Any]) -> str:
|
|
| 524 |
if source_path:
|
| 525 |
return source_path
|
| 526 |
|
| 527 |
-
source = str(metadata.get("source") or "").strip().lower()
|
| 528 |
if source:
|
| 529 |
return source
|
| 530 |
|
| 531 |
return "unknown"
|
| 532 |
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
"target_point",
|
| 556 |
-
"path_title",
|
| 557 |
-
]:
|
| 558 |
-
value = metadata.get(key)
|
| 559 |
if value is not None and str(value).strip():
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
return "\n".join(parts).strip()
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
def _point_to_candidate(point: Any) -> Dict[str, Any]:
|
| 566 |
-
payload = getattr(point, "payload", {}) or {}
|
| 567 |
-
text = str(payload.get("text") or payload.get("snippet") or "").strip()
|
| 568 |
-
metadata = dict(payload.get("metadata") or {})
|
| 569 |
-
node_id = _extract_node_id_from_payload(payload)
|
| 570 |
-
|
| 571 |
-
if isinstance(metadata, dict):
|
| 572 |
-
for key in [
|
| 573 |
-
"law_name", "law_type", "year", "source", "section", "subsection",
|
| 574 |
-
"article", "clause", "point", "chunk_id", "node_id", "node_type",
|
| 575 |
-
"legal_role", "path_title"
|
| 576 |
-
]:
|
| 577 |
-
if key not in metadata and payload.get(key) is not None:
|
| 578 |
-
metadata[key] = payload.get(key)
|
| 579 |
-
|
| 580 |
-
if not node_id:
|
| 581 |
-
node_id = str(metadata.get("chunk_id") or metadata.get("node_id") or "")
|
| 582 |
-
|
| 583 |
-
retrieval_text = _build_runtime_retrieval_text(text, metadata, payload)
|
| 584 |
-
return {
|
| 585 |
-
"node_id": node_id,
|
| 586 |
-
"text": text,
|
| 587 |
-
"snippet": text[:500],
|
| 588 |
-
"metadata": metadata,
|
| 589 |
-
"payload": payload,
|
| 590 |
-
"retrieval_text": retrieval_text,
|
| 591 |
-
"rerank_text": retrieval_text,
|
| 592 |
-
"dense_score": float(getattr(point, "score", 0.0) or 0.0),
|
| 593 |
-
"doc_key": _candidate_doc_key(metadata),
|
| 594 |
-
}
|
| 595 |
|
| 596 |
|
| 597 |
-
def _rrf_fuse(rank_lists: List[List[
|
| 598 |
-
scores: Dict[str, float] =
|
| 599 |
for ranked in rank_lists:
|
| 600 |
-
for rank,
|
| 601 |
-
|
| 602 |
-
if not node_id:
|
| 603 |
continue
|
| 604 |
-
scores[
|
| 605 |
-
return scores
|
| 606 |
-
|
| 607 |
-
def _merge_variant_candidates(rank_lists: List[List[Dict[str, Any]]]) -> List[Dict[str, Any]]:
|
| 608 |
-
fused = _rrf_fuse(rank_lists)
|
| 609 |
-
merged: Dict[str, Dict[str, Any]] = {}
|
| 610 |
-
|
| 611 |
-
def _safe_float(x: Any) -> float:
|
| 612 |
-
try:
|
| 613 |
-
return float(x or 0.0)
|
| 614 |
-
except Exception:
|
| 615 |
-
return 0.0
|
| 616 |
-
|
| 617 |
-
def _text_len(x: Any) -> int:
|
| 618 |
-
return len(str(x or "").strip())
|
| 619 |
-
|
| 620 |
-
def _candidate_quality(item: Dict[str, Any]) -> tuple:
|
| 621 |
-
"""
|
| 622 |
-
So sánh 2 version của cùng một node_id.
|
| 623 |
-
Ưu tiên:
|
| 624 |
-
1) cross_score
|
| 625 |
-
2) scope_score
|
| 626 |
-
3) dense_score
|
| 627 |
-
4) retrieval_text dài hơn một chút
|
| 628 |
-
5) text dài hơn một chút
|
| 629 |
-
"""
|
| 630 |
-
return (
|
| 631 |
-
_safe_float(item.get("cross_score")),
|
| 632 |
-
_safe_float(item.get("scope_score")),
|
| 633 |
-
_safe_float(item.get("dense_score")),
|
| 634 |
-
_text_len(item.get("retrieval_text")),
|
| 635 |
-
_text_len(item.get("text")),
|
| 636 |
-
)
|
| 637 |
|
| 638 |
-
def _maybe_prefer_better_text(base: Dict[str, Any], item: Dict[str, Any]) -> None:
|
| 639 |
-
"""
|
| 640 |
-
Chỉ cập nhật phần text/payload nếu version mới thực sự tốt hơn.
|
| 641 |
-
Không dùng rule 'text dài hơn thì thắng' nữa.
|
| 642 |
-
"""
|
| 643 |
-
if _candidate_quality(item) > _candidate_quality(base):
|
| 644 |
-
base["text"] = item.get("text")
|
| 645 |
-
base["snippet"] = item.get("snippet")
|
| 646 |
-
base["retrieval_text"] = item.get("retrieval_text")
|
| 647 |
-
base["rerank_text"] = item.get("rerank_text")
|
| 648 |
-
base["metadata"] = item.get("metadata")
|
| 649 |
-
base["payload"] = item.get("payload")
|
| 650 |
-
base["best_cross_score"] = _safe_float(item.get("cross_score"))
|
| 651 |
-
base["best_scope_score"] = _safe_float(item.get("scope_score"))
|
| 652 |
-
|
| 653 |
-
for variant_idx, ranked in enumerate(rank_lists):
|
| 654 |
-
for rank, item in enumerate(ranked, start=1):
|
| 655 |
-
node_id = str(item.get("node_id") or "").strip()
|
| 656 |
-
if not node_id:
|
| 657 |
-
continue
|
| 658 |
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
base["all_texts"].append(str(item.get("text")))
|
| 669 |
-
merged[node_id] = base
|
| 670 |
-
continue
|
| 671 |
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
_safe_float(item.get("dense_score")),
|
| 679 |
-
)
|
| 680 |
-
base["best_cross_score"] = max(
|
| 681 |
-
_safe_float(base.get("best_cross_score")),
|
| 682 |
-
_safe_float(item.get("cross_score")),
|
| 683 |
-
)
|
| 684 |
-
base["best_scope_score"] = max(
|
| 685 |
-
_safe_float(base.get("best_scope_score")),
|
| 686 |
-
_safe_float(item.get("scope_score")),
|
| 687 |
-
)
|
| 688 |
-
|
| 689 |
-
txt = str(item.get("text") or "").strip()
|
| 690 |
-
if txt and txt not in base["all_texts"]:
|
| 691 |
-
base["all_texts"].append(txt)
|
| 692 |
-
|
| 693 |
-
# Chỉ thay text nếu candidate mới tốt hơn thật sự
|
| 694 |
-
_maybe_prefer_better_text(base, item)
|
| 695 |
-
|
| 696 |
-
# Nếu retrieval_text hiện tại quá ngắn mà item mới có retrieval_text tốt hơn,
|
| 697 |
-
# thì cập nhật riêng retrieval_text nhưng không phá toàn bộ base
|
| 698 |
-
if _text_len(item.get("retrieval_text")) > _text_len(base.get("retrieval_text")):
|
| 699 |
-
base["retrieval_text"] = item.get("retrieval_text")
|
| 700 |
-
if _text_len(item.get("rerank_text")) > _text_len(base.get("rerank_text")):
|
| 701 |
-
base["rerank_text"] = item.get("rerank_text")
|
| 702 |
|
| 703 |
-
out: List[Dict[str, Any]] = []
|
| 704 |
-
for node_id, item in merged.items():
|
| 705 |
-
item["rrf_score"] = _safe_float(fused.get(node_id, 0.0))
|
| 706 |
-
item["dense_score"] = _safe_float(item.get("max_dense_score", 0.0))
|
| 707 |
-
item["cross_score"] = _safe_float(item.get("best_cross_score", 0.0))
|
| 708 |
-
item["scope_score"] = _safe_float(item.get("best_scope_score", 0.0))
|
| 709 |
-
out.append(item)
|
| 710 |
-
|
| 711 |
-
out.sort(
|
| 712 |
-
key=lambda x: (
|
| 713 |
-
_safe_float(x.get("rrf_score")),
|
| 714 |
-
_safe_float(x.get("cross_score")),
|
| 715 |
-
_safe_float(x.get("scope_score")),
|
| 716 |
-
_safe_float(x.get("dense_score")),
|
| 717 |
-
int(x.get("variant_hits", 0)),
|
| 718 |
-
),
|
| 719 |
-
reverse=True,
|
| 720 |
-
)
|
| 721 |
return out
|
| 722 |
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
query_profile = query_profile or analyze_query_with_llm(question)
|
| 731 |
-
merged_filters = dict(infer_filters(question))
|
| 732 |
-
if filters:
|
| 733 |
-
merged_filters.update({k: v for k, v in filters.items() if v is not None and v != ""})
|
| 734 |
-
explicit_refs = dict(query_profile.get("explicit_refs") or {})
|
| 735 |
-
if explicit_refs.get("year") is not None and "year" not in merged_filters:
|
| 736 |
-
merged_filters["year"] = explicit_refs["year"]
|
| 737 |
-
|
| 738 |
-
variants = list(query_profile.get("query_variants") or [_norm_space(question)])
|
| 739 |
-
client = get_qdrant_client()
|
| 740 |
embeddings = get_embedings()
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
try:
|
| 745 |
-
vector = embeddings.embed_query(variant)
|
| 746 |
-
raw_points = search_qdrant(
|
| 747 |
-
client=client,
|
| 748 |
-
query_vector=vector,
|
| 749 |
-
top_k=top_k or settings.qdrant_top_k,
|
| 750 |
-
filters=merged_filters,
|
| 751 |
-
)
|
| 752 |
-
per_variant_lists.append([_point_to_candidate(p) for p in raw_points])
|
| 753 |
-
except Exception as exc:
|
| 754 |
-
logger.warning("Variant retrieval failed for %r: %s", variant, exc)
|
| 755 |
-
|
| 756 |
-
if not per_variant_lists:
|
| 757 |
-
return []
|
| 758 |
|
| 759 |
-
merged_candidates = _merge_variant_candidates(per_variant_lists)
|
| 760 |
-
bm25_stats = get_bm25_stats_cached(settings.bm25_stats_path)
|
| 761 |
-
ranked = hybrid_rank(
|
| 762 |
-
question,
|
| 763 |
-
merged_candidates,
|
| 764 |
-
dense_key="dense_score",
|
| 765 |
-
text_key="retrieval_text",
|
| 766 |
-
alpha=0.5,
|
| 767 |
-
idf_map=bm25_stats.get("idf", {}),
|
| 768 |
-
avgdl=bm25_stats.get("avgdl", 0.0),
|
| 769 |
-
)
|
| 770 |
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
item = dict(cand)
|
| 774 |
-
item["hybrid_score"] = float(hybrid_score)
|
| 775 |
-
item["query_variants"] = variants
|
| 776 |
-
item["query_profile"] = query_profile
|
| 777 |
-
out.append(item)
|
| 778 |
-
return out
|
| 779 |
|
| 780 |
|
| 781 |
-
def
|
| 782 |
-
|
|
|
|
|
|
|
| 783 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
|
| 785 |
-
|
| 786 |
-
return str(value or "").strip().lower()
|
| 787 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 788 |
|
| 789 |
-
|
| 790 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 791 |
|
|
|
|
|
|
|
| 792 |
|
| 793 |
-
def _reverse_adjacency(graph: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
|
| 794 |
-
return graph.get("reverse_adjacency", {}) or {}
|
| 795 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 796 |
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 800 |
|
|
|
|
|
|
|
| 801 |
|
| 802 |
-
def _is_summary(node: Dict[str, Any]) -> bool:
|
| 803 |
-
md = node.get("metadata", {}) or {}
|
| 804 |
-
return md.get("artifact_type") == "summary"
|
| 805 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 806 |
|
| 807 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 808 |
graph: Dict[str, Any],
|
| 809 |
-
seed_items: List[Dict[str, Any]],
|
| 810 |
*,
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
allowed_relations = allowed_relations_for_mode(mode)
|
| 816 |
-
node_idx = _node_index(graph)
|
| 817 |
-
node_idx_by_norm = {_normalize_node_id(node_id): str(node_id) for node_id in node_idx.keys()}
|
| 818 |
-
chunk_id_index: Dict[str, str] = {}
|
| 819 |
-
for real_node_id, node in node_idx.items():
|
| 820 |
-
md = node.get("metadata", {}) or {}
|
| 821 |
-
chunk_id = md.get("chunk_id")
|
| 822 |
-
norm_chunk_id = _normalize_node_id(chunk_id)
|
| 823 |
-
if norm_chunk_id and norm_chunk_id not in chunk_id_index:
|
| 824 |
-
chunk_id_index[norm_chunk_id] = real_node_id
|
| 825 |
-
|
| 826 |
-
queue = deque()
|
| 827 |
-
best_score: Dict[str, float] = {}
|
| 828 |
-
|
| 829 |
-
for item in seed_items:
|
| 830 |
-
raw_node_id = item.get("node_id")
|
| 831 |
-
md = item.get("metadata", {}) or {}
|
| 832 |
-
raw_chunk_id = md.get("chunk_id") if isinstance(md, dict) else None
|
| 833 |
-
|
| 834 |
-
resolved_node_id: Optional[str] = None
|
| 835 |
-
norm_node_id = _normalize_node_id(raw_node_id)
|
| 836 |
-
if norm_node_id:
|
| 837 |
-
resolved_node_id = node_idx_by_norm.get(norm_node_id)
|
| 838 |
-
if not resolved_node_id:
|
| 839 |
-
norm_chunk_id = _normalize_node_id(raw_chunk_id)
|
| 840 |
-
if norm_chunk_id:
|
| 841 |
-
resolved_node_id = chunk_id_index.get(norm_chunk_id)
|
| 842 |
-
if not resolved_node_id or resolved_node_id not in node_idx:
|
| 843 |
-
continue
|
| 844 |
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
|
|
|
| 848 |
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
current_id, hop, current_score = queue.popleft()
|
| 852 |
-
if (current_id, hop) in visited:
|
| 853 |
continue
|
| 854 |
-
|
| 855 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
continue
|
|
|
|
|
|
|
|
|
|
| 857 |
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
if not nxt or rel not in allowed_relations or nxt not in node_idx:
|
| 862 |
continue
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
if _is_evidence(node):
|
| 866 |
-
next_score *= 1.05
|
| 867 |
-
elif _is_summary(node):
|
| 868 |
-
next_score *= 0.95
|
| 869 |
-
if next_score > best_score.get(str(nxt), -1.0):
|
| 870 |
-
best_score[str(nxt)] = next_score
|
| 871 |
-
queue.append((str(nxt), hop + 1, next_score))
|
| 872 |
-
|
| 873 |
-
for edge in _reverse_adjacency(graph).get(current_id, []):
|
| 874 |
-
rel = str(edge.get("relation_type") or "").strip().upper()
|
| 875 |
-
nxt = edge.get("source_id")
|
| 876 |
-
if not nxt or rel not in allowed_relations or nxt not in node_idx:
|
| 877 |
continue
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
node_type = str(md.get("node_type") or "").strip().lower()
|
| 895 |
-
node_level = NODE_TO_LEVEL.get(node_type, "document")
|
| 896 |
-
level_strategy = str(query_profile.get("level_strategy") or "mixed")
|
| 897 |
-
|
| 898 |
-
target_rank = LEVEL_ORDER.get(target_level, 0)
|
| 899 |
-
node_rank = LEVEL_ORDER.get(node_level, 0)
|
| 900 |
-
|
| 901 |
-
score = 0.0
|
| 902 |
-
if level_strategy in {"same_level", "sibling"}:
|
| 903 |
-
if node_level == target_level:
|
| 904 |
-
score += 0.44
|
| 905 |
-
elif abs(node_rank - target_rank) == 1:
|
| 906 |
-
score += 0.14
|
| 907 |
-
else:
|
| 908 |
-
score += 0.04
|
| 909 |
-
elif level_strategy == "parent":
|
| 910 |
-
if node_rank < target_rank:
|
| 911 |
-
score += 0.44
|
| 912 |
-
elif node_level == target_level:
|
| 913 |
-
score += 0.20
|
| 914 |
-
else:
|
| 915 |
-
score += 0.05
|
| 916 |
-
elif level_strategy == "children":
|
| 917 |
-
if node_rank > target_rank:
|
| 918 |
-
score += 0.44
|
| 919 |
-
elif node_level == target_level:
|
| 920 |
-
score += 0.20
|
| 921 |
-
else:
|
| 922 |
-
score += 0.05
|
| 923 |
-
else:
|
| 924 |
-
if node_level == target_level:
|
| 925 |
-
score += 0.40
|
| 926 |
-
elif node_rank > target_rank:
|
| 927 |
-
score += 0.20
|
| 928 |
-
else:
|
| 929 |
-
score += 0.05
|
| 930 |
-
|
| 931 |
-
refs = dict(query_profile.get("explicit_refs") or {})
|
| 932 |
-
q_article = refs.get("article")
|
| 933 |
-
q_clause = refs.get("clause")
|
| 934 |
-
q_point = refs.get("point")
|
| 935 |
-
|
| 936 |
-
md_article = md.get("article")
|
| 937 |
-
md_clause = md.get("clause")
|
| 938 |
-
md_point = md.get("point")
|
| 939 |
-
|
| 940 |
-
if q_article:
|
| 941 |
-
if str(md_article or "").strip().lower() == str(q_article).lower():
|
| 942 |
-
score += 0.25
|
| 943 |
-
elif md_article:
|
| 944 |
-
score -= 0.15
|
| 945 |
-
if q_clause:
|
| 946 |
-
if str(md_clause or "").strip().lower() == str(q_clause).lower():
|
| 947 |
-
score += 0.20
|
| 948 |
-
elif md_clause:
|
| 949 |
-
score -= 0.12
|
| 950 |
-
if q_point:
|
| 951 |
-
if str(md_point or "").strip().lower() == str(q_point).lower():
|
| 952 |
-
score += 0.15
|
| 953 |
-
elif md_point:
|
| 954 |
-
score -= 0.10
|
| 955 |
-
|
| 956 |
-
mode = str(query_profile.get("mode") or "general")
|
| 957 |
-
legal_role = str(md.get("legal_role") or "").strip().lower()
|
| 958 |
-
if mode == "change" and legal_role in {"amendment", "replacement", "transition"}:
|
| 959 |
-
score += 0.10
|
| 960 |
-
elif mode == "effective" and legal_role in {"effective", "transition", "responsibility"}:
|
| 961 |
-
score += 0.10
|
| 962 |
-
elif mode == "sanction" and legal_role in {"responsibility", "clause", "point"}:
|
| 963 |
-
score += 0.08
|
| 964 |
-
|
| 965 |
-
return float(score)
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
def _build_passage_from_node(
|
| 969 |
-
node_id: str,
|
| 970 |
-
node: Dict[str, Any],
|
| 971 |
-
seed_item: Optional[Dict[str, Any]],
|
| 972 |
-
graph_score: float,
|
| 973 |
-
query_profile: Dict[str, Any],
|
| 974 |
-
) -> Optional[Dict[str, Any]]:
|
| 975 |
-
text = str(node.get("text") or "").strip()
|
| 976 |
-
if not text:
|
| 977 |
-
return None
|
| 978 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 979 |
md = dict(node.get("metadata", {}) or {})
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 987 |
|
| 988 |
return {
|
| 989 |
"node_id": node_id,
|
| 990 |
-
"text":
|
| 991 |
-
"snippet":
|
| 992 |
-
"
|
| 993 |
"retrieval_text": retrieval_text,
|
| 994 |
-
"rerank_text":
|
| 995 |
-
"
|
| 996 |
-
"
|
| 997 |
-
"
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1003 |
}
|
| 1004 |
|
| 1005 |
|
| 1006 |
-
def
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1010 |
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1032 |
|
| 1033 |
-
out.sort(key=lambda x: float(x.get("doc_score", 0.0)), reverse=True)
|
| 1034 |
-
return out
|
| 1035 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1036 |
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1040 |
*,
|
| 1041 |
-
|
| 1042 |
-
top_docs: int = 3,
|
| 1043 |
-
per_doc_base: int = 3,
|
| 1044 |
-
rescue_global: int = 4,
|
| 1045 |
) -> List[Dict[str, Any]]:
|
| 1046 |
-
query_profile = query_profile or {}
|
| 1047 |
-
selected: List[Dict[str, Any]] = []
|
| 1048 |
-
seen: Set[str] = set()
|
| 1049 |
-
|
| 1050 |
-
document_scope = str(query_profile.get("document_scope") or "multi_doc")
|
| 1051 |
-
level_strategy = str(query_profile.get("level_strategy") or "mixed")
|
| 1052 |
-
needs = dict(query_profile.get("needs") or {})
|
| 1053 |
-
|
| 1054 |
-
if document_scope == "single_doc":
|
| 1055 |
-
top_docs = 1
|
| 1056 |
-
per_doc_base = max(per_doc_base, 4 if level_strategy == "children" else 3)
|
| 1057 |
-
rescue_global = min(rescue_global, 2)
|
| 1058 |
-
elif needs.get("linked_docs") or needs.get("amendments") or needs.get("guidance_docs"):
|
| 1059 |
-
top_docs = max(top_docs, 4)
|
| 1060 |
-
if level_strategy == "parent":
|
| 1061 |
-
per_doc_base = max(2, per_doc_base - 1)
|
| 1062 |
-
|
| 1063 |
-
chosen_docs = doc_groups[:max(1, top_docs)]
|
| 1064 |
-
|
| 1065 |
-
top1 = float(chosen_docs[0].get("doc_score", 0.0)) if chosen_docs else 0.0
|
| 1066 |
-
top2 = float(chosen_docs[1].get("doc_score", 0.0)) if len(chosen_docs) > 1 else 0.0
|
| 1067 |
-
|
| 1068 |
-
for idx, doc in enumerate(chosen_docs):
|
| 1069 |
-
doc_score = float(doc.get("doc_score", 0.0))
|
| 1070 |
-
items = list(doc.get("items") or [])
|
| 1071 |
-
|
| 1072 |
-
# adaptive per-doc width
|
| 1073 |
-
if idx == 0 and top1 - top2 > 0.10:
|
| 1074 |
-
take_n = per_doc_base + 1
|
| 1075 |
-
elif idx > 0 and top1 - doc_score > 0.15:
|
| 1076 |
-
take_n = max(2, per_doc_base - 1)
|
| 1077 |
-
else:
|
| 1078 |
-
take_n = per_doc_base
|
| 1079 |
-
|
| 1080 |
-
for p in items[:take_n]:
|
| 1081 |
-
nid = str(p.get("node_id") or "")
|
| 1082 |
-
if nid and nid not in seen:
|
| 1083 |
-
item = dict(p)
|
| 1084 |
-
item["doc_score"] = doc_score
|
| 1085 |
-
selected.append(item)
|
| 1086 |
-
seen.add(nid)
|
| 1087 |
-
|
| 1088 |
-
for p in sorted(all_passages, key=lambda x: float(x.get("initial_score", 0.0)), reverse=True):
|
| 1089 |
-
nid = str(p.get("node_id") or "")
|
| 1090 |
-
if nid and nid not in seen:
|
| 1091 |
-
item = dict(p)
|
| 1092 |
-
item.setdefault("doc_score", 0.0)
|
| 1093 |
-
selected.append(item)
|
| 1094 |
-
seen.add(nid)
|
| 1095 |
-
rescue_global -= 1
|
| 1096 |
-
if rescue_global <= 0:
|
| 1097 |
-
break
|
| 1098 |
-
|
| 1099 |
-
return selected
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
-
def reorder_passages_by_article_tree(graph: Dict[str, Any], passages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 1103 |
if not passages:
|
| 1104 |
-
return
|
| 1105 |
-
|
| 1106 |
-
node_idx = _node_index(graph)
|
| 1107 |
-
adjacency = _adjacency(graph)
|
| 1108 |
-
reverse = _reverse_adjacency(graph)
|
| 1109 |
-
first_id = str(passages[0].get("node_id") or "")
|
| 1110 |
-
if not first_id or first_id not in node_idx:
|
| 1111 |
-
return passages
|
| 1112 |
-
|
| 1113 |
-
current = first_id
|
| 1114 |
-
visited: Set[str] = set()
|
| 1115 |
-
article_root_id = first_id
|
| 1116 |
-
while current and current not in visited:
|
| 1117 |
-
visited.add(current)
|
| 1118 |
-
node = node_idx.get(current, {})
|
| 1119 |
-
node_type = str(node.get("node_type") or "").strip().lower()
|
| 1120 |
-
if node_type == "article":
|
| 1121 |
-
article_root_id = current
|
| 1122 |
-
break
|
| 1123 |
-
parent_id = None
|
| 1124 |
-
for edge in reverse.get(current, []):
|
| 1125 |
-
if str(edge.get("relation_type") or "").strip().upper() == "HAS_CHILD":
|
| 1126 |
-
parent_id = edge.get("source_id")
|
| 1127 |
-
break
|
| 1128 |
-
if not parent_id:
|
| 1129 |
-
break
|
| 1130 |
-
current = str(parent_id)
|
| 1131 |
-
|
| 1132 |
-
stack = [article_root_id]
|
| 1133 |
-
subtree_ids: Set[str] = set()
|
| 1134 |
-
while stack:
|
| 1135 |
-
nid = stack.pop()
|
| 1136 |
-
if nid in subtree_ids:
|
| 1137 |
-
continue
|
| 1138 |
-
subtree_ids.add(nid)
|
| 1139 |
-
for edge in adjacency.get(nid, []):
|
| 1140 |
-
if str(edge.get("relation_type") or "").strip().upper() == "HAS_CHILD":
|
| 1141 |
-
child = edge.get("target_id")
|
| 1142 |
-
if child:
|
| 1143 |
-
stack.append(str(child))
|
| 1144 |
-
|
| 1145 |
-
article_first = [p for p in passages if str(p.get("node_id") or "") in subtree_ids]
|
| 1146 |
-
others = [p for p in passages if str(p.get("node_id") or "") not in subtree_ids]
|
| 1147 |
-
return article_first + others
|
| 1148 |
-
|
| 1149 |
|
| 1150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1151 |
graph: Dict[str, Any],
|
| 1152 |
-
|
| 1153 |
-
graph_scores: Dict[str, float],
|
| 1154 |
*,
|
| 1155 |
-
|
| 1156 |
-
|
| 1157 |
-
|
| 1158 |
-
|
| 1159 |
-
|
| 1160 |
-
|
| 1161 |
-
|
| 1162 |
-
|
| 1163 |
-
|
| 1164 |
-
|
| 1165 |
-
passage = _build_passage_from_node(
|
| 1166 |
-
node_id=node_id,
|
| 1167 |
-
node=node,
|
| 1168 |
-
seed_item=seed_by_id.get(node_id),
|
| 1169 |
-
graph_score=float(graph_scores.get(node_id, 0.0)),
|
| 1170 |
-
query_profile=query_profile,
|
| 1171 |
-
)
|
| 1172 |
-
if passage:
|
| 1173 |
-
candidate_map[node_id] = passage
|
| 1174 |
-
|
| 1175 |
-
if not candidate_map:
|
| 1176 |
-
for item in seed_items:
|
| 1177 |
-
node_id = str(item.get("node_id") or "")
|
| 1178 |
-
text = str(item.get("text") or "").strip()
|
| 1179 |
-
if not node_id or not text:
|
| 1180 |
-
continue
|
| 1181 |
-
md = dict(item.get("metadata", {}) or {})
|
| 1182 |
-
passage = {
|
| 1183 |
-
"node_id": node_id,
|
| 1184 |
-
"text": text,
|
| 1185 |
-
"snippet": item.get("snippet") or text[:700],
|
| 1186 |
-
"metadata": md,
|
| 1187 |
-
"retrieval_text": item.get("retrieval_text") or _build_runtime_retrieval_text(text, md),
|
| 1188 |
-
"rerank_text": item.get("rerank_text") or _build_runtime_retrieval_text(text, md),
|
| 1189 |
-
"dense_score": float(item.get("dense_score", 0.0) or 0.0),
|
| 1190 |
-
"hybrid_score": float(item.get("hybrid_score", 0.0) or 0.0),
|
| 1191 |
-
"graph_score": 0.0,
|
| 1192 |
-
"scope_score": compute_scope_score(query_profile, md),
|
| 1193 |
-
"cross_score": 0.0,
|
| 1194 |
-
"version_bonus": compute_version_bonus({"metadata": md, "node_type": md.get("node_type")}, mode=str(query_profile.get("mode") or "general")),
|
| 1195 |
-
"initial_score": float(item.get("hybrid_score", 0.0) or 0.0),
|
| 1196 |
-
"doc_key": _candidate_doc_key(md),
|
| 1197 |
-
}
|
| 1198 |
-
candidate_map[node_id] = passage
|
| 1199 |
-
|
| 1200 |
-
all_passages = sorted(candidate_map.values(), key=lambda x: float(x.get("initial_score", 0.0)), reverse=True)
|
| 1201 |
-
doc_groups = aggregate_documents(all_passages)
|
| 1202 |
-
candidate_pool = build_final_passage_pool(
|
| 1203 |
-
doc_groups,
|
| 1204 |
-
all_passages,
|
| 1205 |
-
query_profile=query_profile,
|
| 1206 |
-
top_docs=min(4, len(doc_groups)),
|
| 1207 |
-
per_doc_base=3,
|
| 1208 |
-
rescue_global=4,
|
| 1209 |
-
)
|
| 1210 |
-
|
| 1211 |
-
cross_limit = min(cross_top_k or settings.cross_top_k, len(candidate_pool))
|
| 1212 |
-
if cross_limit > 0:
|
| 1213 |
-
reranked = cross_rerank(
|
| 1214 |
-
question=str(query_profile.get("original_question") or ""),
|
| 1215 |
-
passages=candidate_pool[:cross_limit],
|
| 1216 |
-
top_n=cross_limit,
|
| 1217 |
-
)
|
| 1218 |
-
reranked_ids = {str(p.get("node_id") or "") for p in reranked}
|
| 1219 |
-
remaining = [p for p in candidate_pool[cross_limit:] if str(p.get("node_id") or "") not in reranked_ids]
|
| 1220 |
-
candidate_pool = reranked + remaining
|
| 1221 |
-
|
| 1222 |
-
for p in candidate_pool:
|
| 1223 |
-
p["final_score"] = (
|
| 1224 |
-
0.35 * float(p.get("cross_score", 0.0) or 0.0)
|
| 1225 |
-
+ 0.25 * float(p.get("hybrid_score", 0.0) or 0.0)
|
| 1226 |
-
+ 0.20 * float(p.get("doc_score", 0.0) or 0.0)
|
| 1227 |
-
+ 0.10 * float(p.get("graph_score", 0.0) or 0.0)
|
| 1228 |
-
+ 0.10 * float(p.get("scope_score", 0.0) or 0.0)
|
| 1229 |
-
+ float(p.get("version_bonus", 0.0) or 0.0)
|
| 1230 |
-
)
|
| 1231 |
-
|
| 1232 |
-
candidate_pool.sort(key=lambda x: float(x.get("final_score", 0.0)), reverse=True)
|
| 1233 |
-
final_passages = reorder_passages_by_article_tree(graph, candidate_pool[: (final_top_k or settings.final_top_k)])
|
| 1234 |
-
for i, p in enumerate(final_passages, start=1):
|
| 1235 |
-
p["rank"] = i
|
| 1236 |
-
return final_passages, doc_groups, candidate_pool
|
| 1237 |
|
| 1238 |
|
| 1239 |
def retrieve_with_graph(
|
|
@@ -1247,53 +824,74 @@ def retrieve_with_graph(
|
|
| 1247 |
final_top_k: Optional[int] = None,
|
| 1248 |
cross_top_k: Optional[int] = None,
|
| 1249 |
) -> Dict[str, Any]:
|
| 1250 |
-
|
| 1251 |
-
|
| 1252 |
-
|
| 1253 |
-
|
| 1254 |
-
|
| 1255 |
-
|
| 1256 |
-
|
| 1257 |
-
|
| 1258 |
-
|
| 1259 |
-
|
| 1260 |
-
|
| 1261 |
-
|
| 1262 |
-
|
| 1263 |
-
|
| 1264 |
-
|
| 1265 |
-
|
| 1266 |
-
|
| 1267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1268 |
|
| 1269 |
-
|
| 1270 |
-
|
| 1271 |
-
|
| 1272 |
-
|
| 1273 |
-
|
| 1274 |
-
|
| 1275 |
-
|
| 1276 |
|
| 1277 |
-
|
| 1278 |
-
|
| 1279 |
-
|
| 1280 |
-
|
| 1281 |
-
|
| 1282 |
-
|
| 1283 |
-
|
| 1284 |
)
|
| 1285 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1286 |
return {
|
| 1287 |
"question": question,
|
| 1288 |
-
"
|
| 1289 |
-
"filters":
|
| 1290 |
-
"
|
| 1291 |
-
"
|
| 1292 |
-
"
|
| 1293 |
-
"
|
| 1294 |
-
"seed_candidates": seeds,
|
| 1295 |
-
"graph_scores": graph_scores,
|
| 1296 |
"doc_groups": doc_groups,
|
| 1297 |
-
"candidate_pool":
|
| 1298 |
-
"passages":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1299 |
}
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import hashlib
|
| 4 |
import logging
|
| 5 |
+
import math
|
| 6 |
+
from collections import Counter, defaultdict
|
| 7 |
+
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
|
| 8 |
+
|
| 9 |
+
from src.rag.hybrid import bm25_score, tokenize
|
| 10 |
+
from src.rag.openai_clients import get_embedings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
from src.rag.rerank_cross import cross_rerank
|
|
|
|
| 12 |
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
+
SUMMARY_EDGE = "HAS_CHILD_SUMMARY"
|
| 16 |
+
SUMMARIZES_EDGE = "SUMMARIZES"
|
| 17 |
+
_DOCUMENT_TOP_K = 2
|
| 18 |
+
_PASSAGES_PER_DOC = 5
|
| 19 |
+
_FINAL_TOP_K = 5
|
| 20 |
+
|
| 21 |
+
_DOC_EMBED_CACHE: Dict[str, List[float]] = {}
|
| 22 |
+
_PASSAGE_EMBED_CACHE: Dict[str, List[float]] = {}
|
| 23 |
+
_QUESTION_EMBED_CACHE: Dict[str, List[float]] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def _norm_space(text: str) -> str:
|
| 27 |
return " ".join((text or "").split()).strip()
|
| 28 |
|
| 29 |
|
| 30 |
+
def _text_cache_key(text: str) -> str:
|
| 31 |
+
return hashlib.sha1(_norm_space(text).encode("utf-8")).hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
def _graph_runtime_cache(graph: Dict[str, Any]) -> Dict[str, Any]:
|
| 35 |
+
cache = graph.get("__retrieval_runtime_cache__")
|
| 36 |
+
if isinstance(cache, dict):
|
| 37 |
+
return cache
|
| 38 |
+
cache = {}
|
| 39 |
+
graph["__retrieval_runtime_cache__"] = cache
|
| 40 |
+
return cache
|
| 41 |
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
def _cosine(a: List[float], b: List[float]) -> float:
|
| 44 |
+
if not a or not b or len(a) != len(b):
|
| 45 |
+
return 0.0
|
| 46 |
+
dot = 0.0
|
| 47 |
+
na = 0.0
|
| 48 |
+
nb = 0.0
|
| 49 |
+
for x, y in zip(a, b):
|
| 50 |
+
fx = float(x)
|
| 51 |
+
fy = float(y)
|
| 52 |
+
dot += fx * fy
|
| 53 |
+
na += fx * fx
|
| 54 |
+
nb += fy * fy
|
| 55 |
+
if na <= 0.0 or nb <= 0.0:
|
| 56 |
+
return 0.0
|
| 57 |
+
return float(dot / (math.sqrt(na) * math.sqrt(nb)))
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
def _node_index(graph: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
|
| 61 |
+
idx = graph.get("node_index", {}) or {}
|
| 62 |
+
if idx:
|
| 63 |
+
return idx
|
| 64 |
+
runtime_cache = _graph_runtime_cache(graph)
|
| 65 |
+
cached = runtime_cache.get("node_index") or {}
|
| 66 |
+
if cached:
|
| 67 |
+
return cached
|
| 68 |
+
out: Dict[str, Dict[str, Any]] = {}
|
| 69 |
+
for node in graph.get("nodes", []) or []:
|
| 70 |
+
node_id = str(node.get("node_id") or "").strip()
|
| 71 |
+
if node_id:
|
| 72 |
+
out[node_id] = node
|
| 73 |
+
runtime_cache["node_index"] = out
|
| 74 |
+
return out
|
| 75 |
|
| 76 |
|
| 77 |
+
def _adjacency(graph: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
|
| 78 |
+
adj = graph.get("adjacency", {}) or {}
|
| 79 |
+
if adj:
|
| 80 |
+
return adj
|
| 81 |
+
runtime_cache = _graph_runtime_cache(graph)
|
| 82 |
+
cached = runtime_cache.get("adjacency") or {}
|
| 83 |
+
if cached:
|
| 84 |
+
return cached
|
| 85 |
+
out: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
|
| 86 |
+
for edge in graph.get("edges", []) or []:
|
| 87 |
+
source_id = str(edge.get("source_id") or "").strip()
|
| 88 |
+
if source_id:
|
| 89 |
+
out[source_id].append(edge)
|
| 90 |
+
runtime_cache["adjacency"] = dict(out)
|
| 91 |
+
return runtime_cache["adjacency"]
|
| 92 |
|
| 93 |
|
| 94 |
+
def _reverse_adjacency(graph: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
|
| 95 |
+
rev = graph.get("reverse_adjacency", {}) or {}
|
| 96 |
+
if rev:
|
| 97 |
+
return rev
|
| 98 |
+
runtime_cache = _graph_runtime_cache(graph)
|
| 99 |
+
cached = runtime_cache.get("reverse_adjacency") or {}
|
| 100 |
+
if cached:
|
| 101 |
+
return cached
|
| 102 |
+
out: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
|
| 103 |
+
for edge in graph.get("edges", []) or []:
|
| 104 |
+
target_id = str(edge.get("target_id") or "").strip()
|
| 105 |
+
if target_id:
|
| 106 |
+
out[target_id].append(edge)
|
| 107 |
+
runtime_cache["reverse_adjacency"] = dict(out)
|
| 108 |
+
return runtime_cache["reverse_adjacency"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
|
| 111 |
def _candidate_doc_key(metadata: Dict[str, Any]) -> str:
|
| 112 |
+
law_name = str(metadata.get("law_name") or metadata.get("official_title") or "").strip().lower()
|
| 113 |
if law_name:
|
| 114 |
return law_name
|
| 115 |
|
|
|
|
| 117 |
if document_id:
|
| 118 |
return document_id
|
| 119 |
|
| 120 |
+
file_name = str(metadata.get("file_name") or metadata.get("filename") or metadata.get("file_stem") or "").strip().lower()
|
| 121 |
if file_name:
|
| 122 |
return file_name
|
| 123 |
|
|
|
|
| 129 |
if source_path:
|
| 130 |
return source_path
|
| 131 |
|
| 132 |
+
source = str(metadata.get("source") or metadata.get("issuing_agency") or "").strip().lower()
|
| 133 |
if source:
|
| 134 |
return source
|
| 135 |
|
| 136 |
return "unknown"
|
| 137 |
|
| 138 |
+
|
| 139 |
+
def _node_type(node: Dict[str, Any]) -> str:
|
| 140 |
+
return str(node.get("node_type") or "").strip().lower()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _summary_level(node: Dict[str, Any]) -> str:
|
| 144 |
+
return str((node.get("metadata", {}) or {}).get("summary_level") or "").strip().lower()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _is_summary_node(node: Dict[str, Any]) -> bool:
|
| 148 |
+
md = node.get("metadata", {}) or {}
|
| 149 |
+
return md.get("artifact_type") == "summary"
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _is_evidence_node(node: Dict[str, Any]) -> bool:
|
| 153 |
+
md = node.get("metadata", {}) or {}
|
| 154 |
+
return md.get("artifact_type") == "evidence"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _path_label(md: Dict[str, Any]) -> str:
|
| 158 |
+
for key in ["path_title", "title", "article", "clause", "point", "section", "subsection"]:
|
| 159 |
+
value = md.get(key)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
if value is not None and str(value).strip():
|
| 161 |
+
return str(value).strip()
|
| 162 |
+
return "-"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
+
def _rrf_fuse(rank_lists: List[List[str]], *, k: int = 60) -> Dict[str, float]:
|
| 166 |
+
scores: Dict[str, float] = defaultdict(float)
|
| 167 |
for ranked in rank_lists:
|
| 168 |
+
for rank, item_id in enumerate(ranked, start=1):
|
| 169 |
+
if not item_id:
|
|
|
|
| 170 |
continue
|
| 171 |
+
scores[item_id] += 1.0 / (k + rank)
|
| 172 |
+
return dict(scores)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
def _batch_embed_texts(texts: List[str], *, cache: Dict[str, List[float]]) -> Dict[str, List[float]]:
|
| 176 |
+
out: Dict[str, List[float]] = {}
|
| 177 |
+
misses: List[Tuple[str, str]] = []
|
| 178 |
+
for text in texts:
|
| 179 |
+
key = _text_cache_key(text)
|
| 180 |
+
if key in cache:
|
| 181 |
+
out[key] = cache[key]
|
| 182 |
+
else:
|
| 183 |
+
misses.append((key, text))
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
if misses:
|
| 186 |
+
embeddings = get_embedings()
|
| 187 |
+
vectors = embeddings.embed_documents([text for _, text in misses])
|
| 188 |
+
for (key, _), vec in zip(misses, vectors):
|
| 189 |
+
cache[key] = list(vec)
|
| 190 |
+
out[key] = cache[key]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
return out
|
| 193 |
|
| 194 |
+
|
| 195 |
+
def _question_embedding(question: str) -> List[float]:
|
| 196 |
+
q = _norm_space(question)
|
| 197 |
+
key = _text_cache_key(q)
|
| 198 |
+
cached = _QUESTION_EMBED_CACHE.get(key)
|
| 199 |
+
if cached is not None:
|
| 200 |
+
return cached
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
embeddings = get_embedings()
|
| 202 |
+
vec = list(embeddings.embed_query(q))
|
| 203 |
+
_QUESTION_EMBED_CACHE[key] = vec
|
| 204 |
+
return vec
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
+
def _bm25_value(question: str, text: str) -> float:
|
| 208 |
+
return bm25_score(tokenize(question), tokenize(text))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
|
| 211 |
+
def _sorted_ids_by_score(items: List[Dict[str, Any]], score_key: str) -> List[str]:
|
| 212 |
+
ranked = sorted(items, key=lambda x: float(x.get(score_key, 0.0) or 0.0), reverse=True)
|
| 213 |
+
return [str(item.get("id") or "") for item in ranked if str(item.get("id") or "")]
|
| 214 |
+
|
| 215 |
|
| 216 |
+
def _infer_node_doc_keys(
|
| 217 |
+
node_id: str,
|
| 218 |
+
node_idx: Dict[str, Dict[str, Any]],
|
| 219 |
+
adjacency: Dict[str, List[Dict[str, Any]]],
|
| 220 |
+
cache: Dict[str, Set[str]],
|
| 221 |
+
) -> Set[str]:
|
| 222 |
+
if node_id in cache:
|
| 223 |
+
return cache[node_id]
|
| 224 |
+
|
| 225 |
+
node = node_idx.get(node_id) or {}
|
| 226 |
+
md = node.get("metadata", {}) or {}
|
| 227 |
+
direct_doc_key = _candidate_doc_key(md)
|
| 228 |
+
if direct_doc_key != "unknown":
|
| 229 |
+
cache[node_id] = {direct_doc_key}
|
| 230 |
+
return cache[node_id]
|
| 231 |
|
| 232 |
+
doc_keys: Set[str] = set()
|
|
|
|
| 233 |
|
| 234 |
+
for source_id in md.get("source_node_ids", []) or []:
|
| 235 |
+
source_id = str(source_id or "").strip()
|
| 236 |
+
if source_id and source_id in node_idx:
|
| 237 |
+
doc_keys.update(_infer_node_doc_keys(source_id, node_idx, adjacency, cache))
|
| 238 |
|
| 239 |
+
if not doc_keys:
|
| 240 |
+
for edge in adjacency.get(node_id, []) or []:
|
| 241 |
+
rel = str(edge.get("relation_type") or "").strip().upper()
|
| 242 |
+
if rel not in {SUMMARY_EDGE, SUMMARIZES_EDGE}:
|
| 243 |
+
continue
|
| 244 |
+
child_id = str(edge.get("target_id") or "").strip()
|
| 245 |
+
if child_id and child_id in node_idx:
|
| 246 |
+
doc_keys.update(_infer_node_doc_keys(child_id, node_idx, adjacency, cache))
|
| 247 |
|
| 248 |
+
cache[node_id] = doc_keys
|
| 249 |
+
return doc_keys
|
| 250 |
|
|
|
|
|
|
|
| 251 |
|
| 252 |
+
def _build_doc_catalog(graph: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 253 |
+
runtime_cache = _graph_runtime_cache(graph)
|
| 254 |
+
cached = runtime_cache.get("doc_catalog")
|
| 255 |
+
if isinstance(cached, list) and cached:
|
| 256 |
+
return cached
|
| 257 |
|
| 258 |
+
node_idx = _node_index(graph)
|
| 259 |
+
adjacency = _adjacency(graph)
|
| 260 |
+
infer_cache: Dict[str, Set[str]] = {}
|
| 261 |
+
buckets: Dict[str, Dict[str, Any]] = {}
|
| 262 |
+
|
| 263 |
+
for node_id, node in node_idx.items():
|
| 264 |
+
md = node.get("metadata", {}) or {}
|
| 265 |
+
doc_keys = _infer_node_doc_keys(node_id, node_idx, adjacency, infer_cache)
|
| 266 |
+
if not doc_keys:
|
| 267 |
+
direct = _candidate_doc_key(md)
|
| 268 |
+
if direct != "unknown":
|
| 269 |
+
doc_keys = {direct}
|
| 270 |
+
if len(doc_keys) != 1:
|
| 271 |
+
continue
|
| 272 |
+
doc_key = next(iter(doc_keys))
|
| 273 |
+
bucket = buckets.setdefault(
|
| 274 |
+
doc_key,
|
| 275 |
+
{
|
| 276 |
+
"id": doc_key,
|
| 277 |
+
"doc_key": doc_key,
|
| 278 |
+
"law_name": md.get("official_title") or md.get("law_name") or md.get("document_title") or doc_key,
|
| 279 |
+
"law_type": md.get("doc_type") or md.get("law_type") or "Unknown",
|
| 280 |
+
"source": md.get("source") or md.get("issuing_agency") or "LocalFile",
|
| 281 |
+
"doc_summary": "",
|
| 282 |
+
"doc_summary_node_id": None,
|
| 283 |
+
"member_node_ids": set(),
|
| 284 |
+
"summary_node_ids": set(),
|
| 285 |
+
"base_summary_node_ids": set(),
|
| 286 |
+
},
|
| 287 |
+
)
|
| 288 |
+
bucket["member_node_ids"].add(node_id)
|
| 289 |
+
|
| 290 |
+
node_text = _norm_space(str(node.get("text") or ""))
|
| 291 |
+
if _is_summary_node(node):
|
| 292 |
+
bucket["summary_node_ids"].add(node_id)
|
| 293 |
+
if _summary_level(node) == "document" and node_text:
|
| 294 |
+
bucket["doc_summary"] = node_text
|
| 295 |
+
bucket["doc_summary_node_id"] = node_id
|
| 296 |
+
elif _summary_level(node) != "document":
|
| 297 |
+
bucket["base_summary_node_ids"].add(node_id)
|
| 298 |
+
|
| 299 |
+
if not bucket["doc_summary"]:
|
| 300 |
+
md_summary = _norm_space(str(md.get("doc_summary") or ""))
|
| 301 |
+
if md_summary:
|
| 302 |
+
bucket["doc_summary"] = md_summary
|
| 303 |
+
|
| 304 |
+
out: List[Dict[str, Any]] = []
|
| 305 |
+
for bucket in buckets.values():
|
| 306 |
+
bucket["member_node_ids"] = sorted(bucket["member_node_ids"])
|
| 307 |
+
bucket["summary_node_ids"] = sorted(bucket["summary_node_ids"])
|
| 308 |
+
bucket["base_summary_node_ids"] = sorted(bucket["base_summary_node_ids"])
|
| 309 |
+
if bucket["doc_summary"]:
|
| 310 |
+
out.append(bucket)
|
| 311 |
|
| 312 |
+
runtime_cache["doc_catalog"] = sorted(out, key=lambda x: str(x.get("law_name") or x.get("doc_key") or ""))
|
| 313 |
+
return runtime_cache["doc_catalog"]
|
| 314 |
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
+
def rank_documents_by_summary_rrf(
|
| 317 |
+
question: str,
|
| 318 |
+
graph: Dict[str, Any],
|
| 319 |
+
*,
|
| 320 |
+
top_k: int = _DOCUMENT_TOP_K,
|
| 321 |
+
question_vec: Optional[List[float]] = None,
|
| 322 |
+
) -> List[Dict[str, Any]]:
|
| 323 |
+
docs = _build_doc_catalog(graph)
|
| 324 |
+
if not docs:
|
| 325 |
+
return []
|
| 326 |
|
| 327 |
+
question_vec = question_vec or _question_embedding(question)
|
| 328 |
+
summary_texts = [str(doc.get("doc_summary") or "") for doc in docs]
|
| 329 |
+
summary_embeds = _batch_embed_texts(summary_texts, cache=_DOC_EMBED_CACHE)
|
| 330 |
+
|
| 331 |
+
dense_items: List[Dict[str, Any]] = []
|
| 332 |
+
bm25_items: List[Dict[str, Any]] = []
|
| 333 |
+
id_to_doc: Dict[str, Dict[str, Any]] = {}
|
| 334 |
+
|
| 335 |
+
for doc in docs:
|
| 336 |
+
doc_id = str(doc.get("id") or "")
|
| 337 |
+
summary_text = str(doc.get("doc_summary") or "")
|
| 338 |
+
embed = summary_embeds.get(_text_cache_key(summary_text), [])
|
| 339 |
+
dense_score = _cosine(question_vec, embed)
|
| 340 |
+
bm25_val = _bm25_value(question, summary_text)
|
| 341 |
+
item = {"id": doc_id, "dense_score": dense_score, "bm25_score": bm25_val}
|
| 342 |
+
dense_items.append(item)
|
| 343 |
+
bm25_items.append(item)
|
| 344 |
+
id_to_doc[doc_id] = doc
|
| 345 |
+
|
| 346 |
+
fused = _rrf_fuse([
|
| 347 |
+
_sorted_ids_by_score(dense_items, "dense_score"),
|
| 348 |
+
_sorted_ids_by_score(bm25_items, "bm25_score"),
|
| 349 |
+
])
|
| 350 |
+
|
| 351 |
+
ranked: List[Dict[str, Any]] = []
|
| 352 |
+
for doc_id, doc in id_to_doc.items():
|
| 353 |
+
summary_text = str(doc.get("doc_summary") or "")
|
| 354 |
+
embed = summary_embeds.get(_text_cache_key(summary_text), [])
|
| 355 |
+
dense_score = _cosine(question_vec, embed)
|
| 356 |
+
bm25_val = _bm25_value(question, summary_text)
|
| 357 |
+
item = dict(doc)
|
| 358 |
+
item["text"] = summary_text
|
| 359 |
+
item["dense_score"] = float(dense_score)
|
| 360 |
+
item["bm25_score"] = float(bm25_val)
|
| 361 |
+
item["rrf_score"] = float(fused.get(doc_id, 0.0))
|
| 362 |
+
item["hybrid_score"] = item["rrf_score"]
|
| 363 |
+
ranked.append(item)
|
| 364 |
+
|
| 365 |
+
ranked.sort(key=lambda x: (float(x.get("rrf_score", 0.0)), float(x.get("dense_score", 0.0))), reverse=True)
|
| 366 |
+
return ranked[: max(1, int(top_k or _DOCUMENT_TOP_K))]
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _same_doc(summary_node_id: str, allowed_summary_ids: Set[str]) -> bool:
|
| 370 |
+
return summary_node_id in allowed_summary_ids
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _one_hop_summary_relations(
|
| 374 |
+
node_id: str,
|
| 375 |
graph: Dict[str, Any],
|
|
|
|
| 376 |
*,
|
| 377 |
+
allowed_summary_ids: Set[str],
|
| 378 |
+
) -> Tuple[List[str], List[str], List[str]]:
|
| 379 |
+
adjacency = _adjacency(graph)
|
| 380 |
+
reverse = _reverse_adjacency(graph)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
+
parents: List[str] = []
|
| 383 |
+
children: List[str] = []
|
| 384 |
+
siblings: List[str] = []
|
| 385 |
+
sibling_seen: Set[str] = set()
|
| 386 |
|
| 387 |
+
for edge in reverse.get(node_id, []) or []:
|
| 388 |
+
if str(edge.get("relation_type") or "").strip().upper() != SUMMARY_EDGE:
|
|
|
|
|
|
|
| 389 |
continue
|
| 390 |
+
parent_id = str(edge.get("source_id") or "").strip()
|
| 391 |
+
if parent_id and _same_doc(parent_id, allowed_summary_ids):
|
| 392 |
+
parents.append(parent_id)
|
| 393 |
+
|
| 394 |
+
for edge in adjacency.get(node_id, []) or []:
|
| 395 |
+
if str(edge.get("relation_type") or "").strip().upper() != SUMMARY_EDGE:
|
| 396 |
continue
|
| 397 |
+
child_id = str(edge.get("target_id") or "").strip()
|
| 398 |
+
if child_id and _same_doc(child_id, allowed_summary_ids):
|
| 399 |
+
children.append(child_id)
|
| 400 |
|
| 401 |
+
for parent_id in parents:
|
| 402 |
+
for edge in adjacency.get(parent_id, []) or []:
|
| 403 |
+
if str(edge.get("relation_type") or "").strip().upper() != SUMMARY_EDGE:
|
|
|
|
| 404 |
continue
|
| 405 |
+
sib_id = str(edge.get("target_id") or "").strip()
|
| 406 |
+
if not sib_id or sib_id == node_id or not _same_doc(sib_id, allowed_summary_ids):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
continue
|
| 408 |
+
if sib_id not in sibling_seen:
|
| 409 |
+
sibling_seen.add(sib_id)
|
| 410 |
+
siblings.append(sib_id)
|
| 411 |
+
|
| 412 |
+
return sorted(set(parents)), sorted(set(children)), siblings
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _format_context_blocks(label: str, texts: Iterable[str]) -> str:
|
| 416 |
+
clean = [_norm_space(text) for text in texts if _norm_space(text)]
|
| 417 |
+
if not clean:
|
| 418 |
+
return ""
|
| 419 |
+
return f"[{label}]\n" + "\n".join(clean)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def _path_line(md: Dict[str, Any], *, suffix: str) -> str:
|
| 423 |
+
return f"[Vị trí] {_path_label(md)} | {suffix}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
|
| 426 |
+
def _short_anchor(text: str, *, limit: int = 240) -> str:
|
| 427 |
+
clean = _norm_space(text)
|
| 428 |
+
if len(clean) <= limit:
|
| 429 |
+
return clean
|
| 430 |
+
return clean[: max(0, limit - 3)].rstrip() + "..."
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def _build_shared_local_fields(passages: List[Dict[str, Any]], doc_info: Dict[str, Any]) -> None:
|
| 434 |
+
if not passages:
|
| 435 |
+
return
|
| 436 |
+
|
| 437 |
+
doc_title = _norm_space(str(doc_info.get("law_name") or doc_info.get("doc_key") or ""))
|
| 438 |
+
doc_summary = _norm_space(str(doc_info.get("doc_summary") or ""))
|
| 439 |
+
|
| 440 |
+
parent_counter: Counter[str] = Counter()
|
| 441 |
+
sibling_counter: Counter[str] = Counter()
|
| 442 |
+
child_counter: Counter[str] = Counter()
|
| 443 |
+
|
| 444 |
+
for passage in passages:
|
| 445 |
+
raw = passage.get("_raw_context") or {}
|
| 446 |
+
parent_counter.update({_norm_space(text): 1 for text in raw.get("parent_texts", []) or [] if _norm_space(text)})
|
| 447 |
+
sibling_counter.update({_norm_space(text): 1 for text in raw.get("sibling_texts", []) or [] if _norm_space(text)})
|
| 448 |
+
child_counter.update({_norm_space(text): 1 for text in raw.get("child_texts", []) or [] if _norm_space(text)})
|
| 449 |
+
|
| 450 |
+
shared_parent_texts = [text for text, count in parent_counter.items() if count >= 2]
|
| 451 |
+
shared_sibling_texts = [text for text, count in sibling_counter.items() if count >= 2]
|
| 452 |
+
shared_child_texts = [text for text, count in child_counter.items() if count >= 2]
|
| 453 |
+
|
| 454 |
+
shared_parts: List[str] = []
|
| 455 |
+
if doc_title:
|
| 456 |
+
shared_parts.append(f"[Văn bản] {doc_title}")
|
| 457 |
+
if doc_summary:
|
| 458 |
+
shared_parts.append(f"[Tóm tắt văn bản]\n{doc_summary}")
|
| 459 |
+
parent_block = _format_context_blocks("Cha chung", shared_parent_texts)
|
| 460 |
+
sibling_block = _format_context_blocks("Sibling chung", shared_sibling_texts)
|
| 461 |
+
child_block = _format_context_blocks("Con chung", shared_child_texts)
|
| 462 |
+
for block in [parent_block, sibling_block, child_block]:
|
| 463 |
+
if block:
|
| 464 |
+
shared_parts.append(block)
|
| 465 |
+
shared_text = "\n\n".join(part for part in shared_parts if _norm_space(part))
|
| 466 |
+
|
| 467 |
+
shared_parent_set = {text.lower() for text in shared_parent_texts}
|
| 468 |
+
shared_sibling_set = {text.lower() for text in shared_sibling_texts}
|
| 469 |
+
shared_child_set = {text.lower() for text in shared_child_texts}
|
| 470 |
+
|
| 471 |
+
for passage in passages:
|
| 472 |
+
raw = passage.get("_raw_context") or {}
|
| 473 |
+
md = dict(passage.get("metadata") or {})
|
| 474 |
+
unique_parent_texts = [
|
| 475 |
+
text for text in raw.get("parent_texts", []) or []
|
| 476 |
+
if _norm_space(text) and _norm_space(text).lower() not in shared_parent_set
|
| 477 |
+
]
|
| 478 |
+
unique_child_texts = [
|
| 479 |
+
text for text in raw.get("child_texts", []) or []
|
| 480 |
+
if _norm_space(text) and _norm_space(text).lower() not in shared_child_set
|
| 481 |
+
]
|
| 482 |
+
unique_sibling_texts = [
|
| 483 |
+
text for text in raw.get("sibling_texts", []) or []
|
| 484 |
+
if _norm_space(text) and _norm_space(text).lower() not in shared_sibling_set
|
| 485 |
+
]
|
| 486 |
+
|
| 487 |
+
local_parts: List[str] = []
|
| 488 |
+
|
| 489 |
+
self_text = _norm_space(str(raw.get("self_text") or passage.get("text") or ""))
|
| 490 |
+
if self_text:
|
| 491 |
+
local_parts.append(f"[Chính node]\n{self_text}")
|
| 492 |
+
|
| 493 |
+
if unique_parent_texts:
|
| 494 |
+
local_parts.append("[Neo cha]\n" + "\n".join(_short_anchor(text) for text in unique_parent_texts[:2]))
|
| 495 |
+
if unique_child_texts:
|
| 496 |
+
local_parts.append("[Neo con]\n" + "\n".join(_short_anchor(text) for text in unique_child_texts[:2]))
|
| 497 |
+
elif unique_sibling_texts:
|
| 498 |
+
local_parts.append("[Neo sibling]\n" + "\n".join(_short_anchor(text) for text in unique_sibling_texts[:2]))
|
| 499 |
+
|
| 500 |
+
passage["shared_text"] = shared_text
|
| 501 |
+
passage["local_text"] = "\n\n".join(part for part in local_parts if _norm_space(part))
|
| 502 |
+
passage.setdefault("bundle_text", passage.get("retrieval_text") or passage.get("text") or "")
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def _join_summary_texts(
|
| 506 |
+
*,
|
| 507 |
+
graph: Dict[str, Any],
|
| 508 |
+
node_id: str,
|
| 509 |
+
doc_info: Dict[str, Any],
|
| 510 |
+
) -> Dict[str, Any]:
|
| 511 |
+
node_idx = _node_index(graph)
|
| 512 |
+
node = node_idx.get(node_id) or {}
|
| 513 |
md = dict(node.get("metadata", {}) or {})
|
| 514 |
+
allowed_summary_ids = set(doc_info.get("summary_node_ids") or [])
|
| 515 |
+
|
| 516 |
+
parents, children, siblings = _one_hop_summary_relations(
|
| 517 |
+
node_id,
|
| 518 |
+
graph,
|
| 519 |
+
allowed_summary_ids=allowed_summary_ids,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
def _summary_text(nid: str) -> str:
|
| 523 |
+
return _norm_space(str((node_idx.get(nid) or {}).get("text") or ""))
|
| 524 |
+
|
| 525 |
+
self_text = _summary_text(node_id)
|
| 526 |
+
parent_texts = [_summary_text(nid) for nid in parents if _summary_text(nid)]
|
| 527 |
+
child_texts = [_summary_text(nid) for nid in children if _summary_text(nid)]
|
| 528 |
+
sibling_texts = [_summary_text(nid) for nid in siblings if _summary_text(nid)]
|
| 529 |
+
doc_summary = _norm_space(str(doc_info.get("doc_summary") or ""))
|
| 530 |
+
|
| 531 |
+
header = f"[Văn bản] {doc_info.get('law_name') or doc_info.get('doc_key')}"
|
| 532 |
+
path_line = _path_line(md, suffix=f"summary_level={_summary_level(node) or _node_type(node) or '-'}")
|
| 533 |
+
|
| 534 |
+
retrieval_sections: List[str] = [header, path_line]
|
| 535 |
+
parent_block = _format_context_blocks("Tóm tắt cha 1 hop", parent_texts)
|
| 536 |
+
child_block = _format_context_blocks("Tóm tắt con 1 hop", child_texts)
|
| 537 |
+
sibling_block = _format_context_blocks("Tóm tắt sibling cùng cha", sibling_texts)
|
| 538 |
+
if parent_block:
|
| 539 |
+
retrieval_sections.append(parent_block)
|
| 540 |
+
retrieval_sections.append(f"[Tóm tắt chính node]\n{self_text}")
|
| 541 |
+
if child_block:
|
| 542 |
+
retrieval_sections.append(child_block)
|
| 543 |
+
if sibling_block:
|
| 544 |
+
retrieval_sections.append(sibling_block)
|
| 545 |
+
|
| 546 |
+
retrieval_text = "\n\n".join(part for part in retrieval_sections if _norm_space(part))
|
| 547 |
+
|
| 548 |
+
rerank_sections: List[str] = [header]
|
| 549 |
+
if doc_summary:
|
| 550 |
+
rerank_sections.append(f"[Tóm tắt văn bản]\n{doc_summary}")
|
| 551 |
+
rerank_sections.append(path_line)
|
| 552 |
+
if parent_block:
|
| 553 |
+
rerank_sections.append(parent_block)
|
| 554 |
+
rerank_sections.append(f"[Tóm tắt chính node]\n{self_text}")
|
| 555 |
+
if child_block:
|
| 556 |
+
rerank_sections.append(child_block)
|
| 557 |
+
rerank_text = "\n\n".join(part for part in rerank_sections if _norm_space(part))
|
| 558 |
|
| 559 |
return {
|
| 560 |
"node_id": node_id,
|
| 561 |
+
"text": self_text,
|
| 562 |
+
"snippet": retrieval_text[:700],
|
| 563 |
+
"bundle_text": retrieval_text,
|
| 564 |
"retrieval_text": retrieval_text,
|
| 565 |
+
"rerank_text": rerank_text,
|
| 566 |
+
"shared_text": "",
|
| 567 |
+
"local_text": "",
|
| 568 |
+
"metadata": {
|
| 569 |
+
**md,
|
| 570 |
+
"doc_key": doc_info.get("doc_key"),
|
| 571 |
+
"law_name": doc_info.get("law_name") or md.get("law_name"),
|
| 572 |
+
"law_type": doc_info.get("law_type") or md.get("law_type"),
|
| 573 |
+
"source": doc_info.get("source") or md.get("source"),
|
| 574 |
+
"parent_summary_ids": parents,
|
| 575 |
+
"child_summary_ids": children,
|
| 576 |
+
"sibling_summary_ids": siblings,
|
| 577 |
+
},
|
| 578 |
+
"doc_key": str(doc_info.get("doc_key") or ""),
|
| 579 |
+
"doc_score": float(doc_info.get("rrf_score", 0.0) or 0.0),
|
| 580 |
+
"_raw_context": {
|
| 581 |
+
"self_text": self_text,
|
| 582 |
+
"parent_texts": parent_texts,
|
| 583 |
+
"child_texts": child_texts,
|
| 584 |
+
"sibling_texts": sibling_texts,
|
| 585 |
+
"path_suffix": f"summary_level={_summary_level(node) or _node_type(node) or '-'}",
|
| 586 |
+
},
|
| 587 |
}
|
| 588 |
|
| 589 |
|
| 590 |
+
def _join_evidence_texts(
|
| 591 |
+
*,
|
| 592 |
+
graph: Dict[str, Any],
|
| 593 |
+
node_id: str,
|
| 594 |
+
doc_info: Dict[str, Any],
|
| 595 |
+
) -> Dict[str, Any]:
|
| 596 |
+
node_idx = _node_index(graph)
|
| 597 |
+
node = node_idx.get(node_id) or {}
|
| 598 |
+
md = dict(node.get("metadata", {}) or {})
|
| 599 |
+
allowed_member_ids = set(doc_info.get("member_node_ids") or [])
|
| 600 |
+
|
| 601 |
+
def _evidence_text(nid: str) -> str:
|
| 602 |
+
if not nid or nid not in allowed_member_ids:
|
| 603 |
+
return ""
|
| 604 |
+
target = node_idx.get(nid) or {}
|
| 605 |
+
return _norm_space(str(target.get("text") or ""))
|
| 606 |
+
|
| 607 |
+
parent_ids: List[str] = []
|
| 608 |
+
parent_id = str(md.get("parent_id") or "").strip()
|
| 609 |
+
if parent_id and parent_id in allowed_member_ids:
|
| 610 |
+
parent_ids.append(parent_id)
|
| 611 |
+
|
| 612 |
+
child_ids: List[str] = []
|
| 613 |
+
for nid in md.get("children_ids", []) or []:
|
| 614 |
+
cid = str(nid or "").strip()
|
| 615 |
+
if cid and cid in allowed_member_ids:
|
| 616 |
+
child_ids.append(cid)
|
| 617 |
+
|
| 618 |
+
sibling_ids: List[str] = []
|
| 619 |
+
for nid in md.get("sibling_ids", []) or []:
|
| 620 |
+
sid = str(nid or "").strip()
|
| 621 |
+
if sid and sid in allowed_member_ids:
|
| 622 |
+
sibling_ids.append(sid)
|
| 623 |
+
|
| 624 |
+
self_text = _norm_space(str(node.get("text") or ""))
|
| 625 |
+
parent_texts = [_evidence_text(nid) for nid in parent_ids if _evidence_text(nid)]
|
| 626 |
+
child_texts = [_evidence_text(nid) for nid in child_ids if _evidence_text(nid)]
|
| 627 |
+
sibling_texts = [_evidence_text(nid) for nid in sibling_ids if _evidence_text(nid)]
|
| 628 |
+
doc_summary = _norm_space(str(doc_info.get("doc_summary") or ""))
|
| 629 |
+
|
| 630 |
+
header = f"[Văn bản] {doc_info.get('law_name') or doc_info.get('doc_key')}"
|
| 631 |
+
path_line = _path_line(md, suffix=f"node_type={_node_type(node) or '-'}")
|
| 632 |
+
|
| 633 |
+
retrieval_sections: List[str] = [header, path_line]
|
| 634 |
+
parent_block = _format_context_blocks("Cha 1 hop", parent_texts)
|
| 635 |
+
child_block = _format_context_blocks("Con 1 hop", child_texts)
|
| 636 |
+
sibling_block = _format_context_blocks("Sibling cùng cha", sibling_texts)
|
| 637 |
+
if parent_block:
|
| 638 |
+
retrieval_sections.append(parent_block)
|
| 639 |
+
retrieval_sections.append(f"[Chính node]\n{self_text}")
|
| 640 |
+
if child_block:
|
| 641 |
+
retrieval_sections.append(child_block)
|
| 642 |
+
if sibling_block:
|
| 643 |
+
retrieval_sections.append(sibling_block)
|
| 644 |
+
|
| 645 |
+
retrieval_text = "\n\n".join(part for part in retrieval_sections if _norm_space(part))
|
| 646 |
+
|
| 647 |
+
rerank_sections: List[str] = [header]
|
| 648 |
+
if doc_summary:
|
| 649 |
+
rerank_sections.append(f"[Tóm tắt văn bản]\n{doc_summary}")
|
| 650 |
+
rerank_sections.append(path_line)
|
| 651 |
+
if parent_block:
|
| 652 |
+
rerank_sections.append(parent_block)
|
| 653 |
+
rerank_sections.append(f"[Chính node]\n{self_text}")
|
| 654 |
+
if child_block:
|
| 655 |
+
rerank_sections.append(child_block)
|
| 656 |
+
rerank_text = "\n\n".join(part for part in rerank_sections if _norm_space(part))
|
| 657 |
|
| 658 |
+
return {
|
| 659 |
+
"node_id": node_id,
|
| 660 |
+
"text": self_text,
|
| 661 |
+
"snippet": retrieval_text[:700],
|
| 662 |
+
"bundle_text": retrieval_text,
|
| 663 |
+
"retrieval_text": retrieval_text,
|
| 664 |
+
"rerank_text": rerank_text,
|
| 665 |
+
"shared_text": "",
|
| 666 |
+
"local_text": "",
|
| 667 |
+
"metadata": {
|
| 668 |
+
**md,
|
| 669 |
+
"doc_key": doc_info.get("doc_key"),
|
| 670 |
+
"law_name": doc_info.get("law_name") or md.get("law_name"),
|
| 671 |
+
"law_type": doc_info.get("law_type") or md.get("law_type"),
|
| 672 |
+
"source": doc_info.get("source") or md.get("source"),
|
| 673 |
+
"parent_node_ids": parent_ids,
|
| 674 |
+
"child_node_ids": child_ids,
|
| 675 |
+
"sibling_node_ids": sibling_ids,
|
| 676 |
+
},
|
| 677 |
+
"doc_key": str(doc_info.get("doc_key") or ""),
|
| 678 |
+
"doc_score": float(doc_info.get("rrf_score", 0.0) or 0.0),
|
| 679 |
+
"_raw_context": {
|
| 680 |
+
"self_text": self_text,
|
| 681 |
+
"parent_texts": parent_texts,
|
| 682 |
+
"child_texts": child_texts,
|
| 683 |
+
"sibling_texts": sibling_texts,
|
| 684 |
+
"path_suffix": f"node_type={_node_type(node) or '-'}",
|
| 685 |
+
},
|
| 686 |
+
}
|
| 687 |
|
|
|
|
|
|
|
| 688 |
|
| 689 |
+
def _build_candidate_passages_for_doc(question: str, graph: Dict[str, Any], doc_info: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 690 |
+
_ = question
|
| 691 |
+
node_idx = _node_index(graph)
|
| 692 |
+
summary_ids = list(doc_info.get("base_summary_node_ids") or [])
|
| 693 |
+
evidence_ids: List[str] = []
|
| 694 |
+
for node_id in doc_info.get("member_node_ids") or []:
|
| 695 |
+
node = node_idx.get(str(node_id)) or {}
|
| 696 |
+
if _is_evidence_node(node):
|
| 697 |
+
evidence_ids.append(str(node_id))
|
| 698 |
+
|
| 699 |
+
candidates: List[Dict[str, Any]] = []
|
| 700 |
+
used_ids: Set[str] = set()
|
| 701 |
+
|
| 702 |
+
for node_id in summary_ids:
|
| 703 |
+
if node_id in used_ids:
|
| 704 |
+
continue
|
| 705 |
+
used_ids.add(node_id)
|
| 706 |
+
joined = _join_summary_texts(graph=graph, node_id=node_id, doc_info=doc_info)
|
| 707 |
+
if _norm_space(str(joined.get("retrieval_text") or "")):
|
| 708 |
+
candidates.append(joined)
|
| 709 |
|
| 710 |
+
for node_id in evidence_ids:
|
| 711 |
+
if node_id in used_ids:
|
| 712 |
+
continue
|
| 713 |
+
used_ids.add(node_id)
|
| 714 |
+
joined = _join_evidence_texts(graph=graph, node_id=node_id, doc_info=doc_info)
|
| 715 |
+
if _norm_space(str(joined.get("retrieval_text") or "")):
|
| 716 |
+
candidates.append(joined)
|
| 717 |
+
|
| 718 |
+
if not candidates and doc_info.get("doc_summary"):
|
| 719 |
+
fallback_text = _norm_space(str(doc_info.get("doc_summary") or ""))
|
| 720 |
+
candidates.append({
|
| 721 |
+
"node_id": str(doc_info.get("doc_summary_node_id") or doc_info.get("doc_key") or doc_info.get("id") or ""),
|
| 722 |
+
"text": fallback_text,
|
| 723 |
+
"snippet": fallback_text[:700],
|
| 724 |
+
"bundle_text": fallback_text,
|
| 725 |
+
"retrieval_text": fallback_text,
|
| 726 |
+
"rerank_text": fallback_text,
|
| 727 |
+
"shared_text": f"[Văn bản] {doc_info.get('law_name') or doc_info.get('doc_key')}\n\n[Tóm tắt văn bản]\n{fallback_text}",
|
| 728 |
+
"local_text": "[Chính node]\n" + fallback_text,
|
| 729 |
+
"metadata": {
|
| 730 |
+
"doc_key": doc_info.get("doc_key"),
|
| 731 |
+
"law_name": doc_info.get("law_name"),
|
| 732 |
+
"law_type": doc_info.get("law_type"),
|
| 733 |
+
"source": doc_info.get("source"),
|
| 734 |
+
"path_title": "Tóm tắt văn bản",
|
| 735 |
+
"node_type": "document_summary",
|
| 736 |
+
},
|
| 737 |
+
"doc_key": str(doc_info.get("doc_key") or ""),
|
| 738 |
+
"doc_score": float(doc_info.get("rrf_score", 0.0) or 0.0),
|
| 739 |
+
"_raw_context": {
|
| 740 |
+
"self_text": fallback_text,
|
| 741 |
+
"parent_texts": [],
|
| 742 |
+
"child_texts": [],
|
| 743 |
+
"sibling_texts": [],
|
| 744 |
+
"path_suffix": "node_type=document_summary",
|
| 745 |
+
},
|
| 746 |
+
})
|
| 747 |
+
|
| 748 |
+
return candidates
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def _rank_passages_rrf(
|
| 752 |
+
question: str,
|
| 753 |
+
passages: List[Dict[str, Any]],
|
| 754 |
*,
|
| 755 |
+
question_vec: Optional[List[float]] = None,
|
|
|
|
|
|
|
|
|
|
| 756 |
) -> List[Dict[str, Any]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 757 |
if not passages:
|
| 758 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 759 |
|
| 760 |
+
question_vec = question_vec or _question_embedding(question)
|
| 761 |
+
joined_texts = [str(p.get("retrieval_text") or "") for p in passages]
|
| 762 |
+
embeds = _batch_embed_texts(joined_texts, cache=_PASSAGE_EMBED_CACHE)
|
| 763 |
+
|
| 764 |
+
dense_items: List[Dict[str, Any]] = []
|
| 765 |
+
bm25_items: List[Dict[str, Any]] = []
|
| 766 |
+
|
| 767 |
+
for passage in passages:
|
| 768 |
+
pid = str(passage.get("node_id") or "")
|
| 769 |
+
joined_text = str(passage.get("retrieval_text") or "")
|
| 770 |
+
embed = embeds.get(_text_cache_key(joined_text), [])
|
| 771 |
+
dense_score = _cosine(question_vec, embed)
|
| 772 |
+
bm25_val = _bm25_value(question, joined_text)
|
| 773 |
+
dense_items.append({"id": pid, "dense_score": dense_score})
|
| 774 |
+
bm25_items.append({"id": pid, "bm25_score": bm25_val})
|
| 775 |
+
|
| 776 |
+
fused = _rrf_fuse([
|
| 777 |
+
_sorted_ids_by_score(dense_items, "dense_score"),
|
| 778 |
+
_sorted_ids_by_score(bm25_items, "bm25_score"),
|
| 779 |
+
])
|
| 780 |
+
|
| 781 |
+
ranked: List[Dict[str, Any]] = []
|
| 782 |
+
for item in passages:
|
| 783 |
+
pid = str(item.get("node_id") or "")
|
| 784 |
+
joined_text = str(item.get("retrieval_text") or "")
|
| 785 |
+
embed = embeds.get(_text_cache_key(joined_text), [])
|
| 786 |
+
dense_score = _cosine(question_vec, embed)
|
| 787 |
+
bm25_val = _bm25_value(question, joined_text)
|
| 788 |
+
enriched = dict(item)
|
| 789 |
+
enriched["dense_score"] = float(dense_score)
|
| 790 |
+
enriched["bm25_score"] = float(bm25_val)
|
| 791 |
+
enriched["rrf_score"] = float(fused.get(pid, 0.0))
|
| 792 |
+
enriched["hybrid_score"] = enriched["rrf_score"]
|
| 793 |
+
ranked.append(enriched)
|
| 794 |
+
|
| 795 |
+
ranked.sort(key=lambda x: (float(x.get("rrf_score", 0.0)), float(x.get("dense_score", 0.0))), reverse=True)
|
| 796 |
+
return ranked
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def _build_doc_passages(
|
| 800 |
+
question: str,
|
| 801 |
graph: Dict[str, Any],
|
| 802 |
+
doc_info: Dict[str, Any],
|
|
|
|
| 803 |
*,
|
| 804 |
+
question_vec: Optional[List[float]] = None,
|
| 805 |
+
) -> List[Dict[str, Any]]:
|
| 806 |
+
candidates = _build_candidate_passages_for_doc(question, graph, doc_info)
|
| 807 |
+
ranked = _rank_passages_rrf(question, candidates, question_vec=question_vec)
|
| 808 |
+
out = ranked[:_PASSAGES_PER_DOC]
|
| 809 |
+
_build_shared_local_fields(out, doc_info)
|
| 810 |
+
for idx, item in enumerate(out, start=1):
|
| 811 |
+
item["doc_local_rank"] = idx
|
| 812 |
+
item.pop("_raw_context", None)
|
| 813 |
+
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 814 |
|
| 815 |
|
| 816 |
def retrieve_with_graph(
|
|
|
|
| 824 |
final_top_k: Optional[int] = None,
|
| 825 |
cross_top_k: Optional[int] = None,
|
| 826 |
) -> Dict[str, Any]:
|
| 827 |
+
_ = filters
|
| 828 |
+
_ = qdrant_top_k
|
| 829 |
+
_ = graph_hops
|
| 830 |
+
_ = max_graph_nodes
|
| 831 |
+
|
| 832 |
+
question = _norm_space(question)
|
| 833 |
+
question_vec = _question_embedding(question)
|
| 834 |
+
doc_candidates = rank_documents_by_summary_rrf(question, graph, top_k=_DOCUMENT_TOP_K, question_vec=question_vec)
|
| 835 |
+
|
| 836 |
+
doc_groups: List[Dict[str, Any]] = []
|
| 837 |
+
candidate_pool: List[Dict[str, Any]] = []
|
| 838 |
+
for doc in doc_candidates:
|
| 839 |
+
passages = _build_doc_passages(question, graph, doc, question_vec=question_vec)
|
| 840 |
+
doc_groups.append(
|
| 841 |
+
{
|
| 842 |
+
"doc_key": doc.get("doc_key"),
|
| 843 |
+
"doc_score": float(doc.get("rrf_score", 0.0) or 0.0),
|
| 844 |
+
"law_name": doc.get("law_name"),
|
| 845 |
+
"source": doc.get("source"),
|
| 846 |
+
"items": passages,
|
| 847 |
+
"doc_summary": doc.get("doc_summary"),
|
| 848 |
+
}
|
| 849 |
+
)
|
| 850 |
+
candidate_pool.extend(passages)
|
| 851 |
|
| 852 |
+
cross_limit = len(candidate_pool) if cross_top_k is None else max(0, min(int(cross_top_k), len(candidate_pool)))
|
| 853 |
+
reranked_pool = cross_rerank(question=question, passages=candidate_pool, top_n=cross_limit) if cross_limit > 0 else []
|
| 854 |
+
|
| 855 |
+
if cross_limit < len(candidate_pool):
|
| 856 |
+
used = {str(item.get("node_id") or "") for item in reranked_pool}
|
| 857 |
+
remainder = [item for item in candidate_pool if str(item.get("node_id") or "") not in used]
|
| 858 |
+
reranked_pool.extend(remainder)
|
| 859 |
|
| 860 |
+
reranked_pool.sort(
|
| 861 |
+
key=lambda x: (
|
| 862 |
+
float(x.get("cross_score", 0.0) or 0.0),
|
| 863 |
+
float(x.get("hybrid_score", 0.0) or 0.0),
|
| 864 |
+
float(x.get("doc_score", 0.0) or 0.0),
|
| 865 |
+
),
|
| 866 |
+
reverse=True,
|
| 867 |
)
|
| 868 |
|
| 869 |
+
final_limit = max(1, int(final_top_k or _FINAL_TOP_K))
|
| 870 |
+
final_passages = reranked_pool[:final_limit]
|
| 871 |
+
for idx, passage in enumerate(final_passages, start=1):
|
| 872 |
+
passage["rank"] = idx
|
| 873 |
+
passage["final_score"] = float(passage.get("cross_score", 0.0) or 0.0)
|
| 874 |
+
passage.pop("_raw_context", None)
|
| 875 |
+
|
| 876 |
+
for item in reranked_pool[final_limit:]:
|
| 877 |
+
item.pop("_raw_context", None)
|
| 878 |
+
|
| 879 |
return {
|
| 880 |
"question": question,
|
| 881 |
+
"mode": "doc_summary_rrf_passage_rrf",
|
| 882 |
+
"filters": {},
|
| 883 |
+
"qdrant_top_k": None,
|
| 884 |
+
"final_top_k": final_limit,
|
| 885 |
+
"cross_top_k": cross_limit,
|
| 886 |
+
"seed_candidates": doc_candidates,
|
|
|
|
|
|
|
| 887 |
"doc_groups": doc_groups,
|
| 888 |
+
"candidate_pool": reranked_pool,
|
| 889 |
+
"passages": final_passages,
|
| 890 |
+
"query_profile": {
|
| 891 |
+
"pipeline": "doc_summary_rrf -> top5_docs -> joined_summary_passages -> top5_per_doc_rrf -> cross_rerank -> top10",
|
| 892 |
+
"document_top_k": _DOCUMENT_TOP_K,
|
| 893 |
+
"passages_per_doc": _PASSAGES_PER_DOC,
|
| 894 |
+
"uses_qdrant": False,
|
| 895 |
+
"uses_graph_summary_nodes": True,
|
| 896 |
+
},
|
| 897 |
}
|