engine.py 20.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
"""检索引擎:六种模式 + 透明深挖。

模式(前五种对齐 LightRAG,便于直接对比;第六种是本系统的差异化):
- naive   :纯 chunk 向量/BM25 召回
- local   :实体中心 —— 低层关键词链接实体 → 取其邻域关系 → 拉原文
- global  :关系中心 —— 高层关键词检索**关系向量库**(v1 根本没有这个索引)
- hybrid  :local + global
- mix     :hybrid + naive
- agentic :多轮深挖,每一步(理解/定位/扩展/取证/反思/作答)都以事件流暴露出来

深挖的核心修复:v1 用无排序 BFS,`门店`(度 110)一跳就 110 条边,然后
`_triples_text(limit=80)` 盲截前 80 条喂给大模型 —— 等于喂随机三元组。
这里改成加权束搜索:边按"关系与问题的相关度 × 端点得分 × log(佐证次数) × 跳数衰减"
打分,每跳只保留 top-K,枢纽节点另设展开上限。
"""
from __future__ import annotations
import logging
import math
import re
import time
from typing import Iterator

from ..core import db, llm
from ..extract.community import CommunityStore
from ..store.graph_store import GraphStore
from ..store.vector_store import HybridIndex
from . import context as ctx_mod
from .prompts import (ANSWER_SYSTEM, ANSWER_USER, KEYWORD_SYSTEM, KEYWORD_USER,
                      NO_CONTEXT_ANSWER, REFLECT_USER)

log = logging.getLogger(__name__)

MODES = ("naive", "local", "global", "hybrid", "mix", "agentic")
_CITE_RE = re.compile(r"\[\^([A-Za-z0-9:_\-]+)\]")


class _Cfg:
    def __init__(self, cfg: dict, overrides: dict | None = None):
        c = {**cfg, **{k: v for k, v in (overrides or {}).items() if v not in (None, "")}}
        self.max_hops = int(c.get("MAX_HOPS", 2))
        self.max_rounds = int(c.get("MAX_ROUNDS", 3))
        self.top_k = int(c.get("TOP_K", 8))
        self.top_k_entity = int(c.get("TOP_K_ENTITY", 12))
        self.top_k_relation = int(c.get("TOP_K_RELATION", 16))
        self.beam_width = int(c.get("BEAM_WIDTH", 24))
        self.max_node_degree = int(c.get("MAX_NODE_DEGREE", 60))
        self.alpha = float(c.get("HYBRID_ALPHA", 0.5))
        self.link_threshold = float(c.get("LINK_THRESHOLD", 0.3))
        self.rerank = str(c.get("RERANK_ENABLED", "1")) == "1"
        self.budget = int(c.get("CONTEXT_TOKEN_BUDGET", 12000))
        self.ratio = ctx_mod.parse_ratio(c.get("BUDGET_RATIO", ""))
        self.stream = str(c.get("STREAM_ANSWER", "1")) == "1"


# ---------------- 步骤 1:理解 ----------------
def _understand(question: str, history: list[dict] | None) -> dict:
    hist = ""
    if history:
        turns = "\n".join(f"{h.get('role', 'user')}:{h.get('content', '')[:200]}"
                          for h in history[-4:])
        hist = f"\n之前的对话(用于理解指代):\n{turns}\n"
    try:
        u = llm.chat_json([{"role": "system", "content": KEYWORD_SYSTEM},
                           {"role": "user", "content": KEYWORD_USER.format(q=question, history=hist)}])
    except Exception as e:  # noqa: BLE001
        log.warning("关键词抽取失败:%s", str(e)[:150])
        u = {}
    if not isinstance(u, dict):
        u = {}
    low = [x for x in (u.get("low_level") or []) if isinstance(x, str) and x.strip()]
    high = [x for x in (u.get("high_level") or []) if isinstance(x, str) and x.strip()]
    if not low and not high:
        low = [question]      # 兜底:整句当检索词,至少不至于空转
    return {"low_level": low, "high_level": high,
            "intent": u.get("intent", ""), "question_type": u.get("question_type", "fact")}


# ---------------- 步骤 2:实体链接 ----------------
def _link(index: HybridIndex, terms: list[str], cfg: _Cfg) -> tuple[list[dict], list[str], dict]:
    links, seeds, seed_score = [], [], {}
    for term in terms:
        matches = index.link_entity(term, k=3, alpha=cfg.alpha, threshold=cfg.link_threshold)
        links.append({"term": term, "matches": matches})
        for m in matches[:2]:
            if m["id"] not in seed_score:
                seeds.append(m["id"])
            seed_score[m["id"]] = max(seed_score.get(m["id"], 0.0), m["score"])
    return links, seeds, seed_score


# ---------------- 步骤 3:加权束搜索扩展 ----------------
def _edge_id(e: dict) -> str:
    return f"{e['from']}__{e['relation']}__{e['to']}"


def _beam_expand(graph: GraphStore, frontier: list[str], node_score: dict[str, float],
                 visited: set[str], rel_scores: dict[str, float], cfg: _Cfg,
                 hop_index: int) -> tuple[list[dict], list[str], int]:
    """一跳扩展。返回 (选中的边[带分数], 新节点, 被剪掉的候选数)。"""
    decay = 0.75 ** hop_index
    candidates: list[dict] = []
    seen: set[str] = set()
    for node in frontier:
        # 枢纽节点只取佐证次数最高的若干条边,避免一个 `门店` 就淹没整轮
        for e in graph.neighbors(node, max_degree=cfg.max_node_degree):
            eid = _edge_id(e)
            if eid in seen:
                continue
            seen.add(eid)
            rel_rel = rel_scores.get(eid, 0.12)
            base = node_score.get(node, 0.4)
            occ = math.log1p(float(e.get("occurrence", 1))) / math.log(6)
            score = (0.55 * rel_rel + 0.25 * base + 0.20 * min(occ, 1.0)) * decay
            candidates.append({**e, "score": round(score, 4), "hop": hop_index + 1})
    candidates.sort(key=lambda x: -x["score"])
    chosen = candidates[: cfg.beam_width]
    pruned = len(candidates) - len(chosen)

    newly: list[str] = []
    for e in chosen:
        other = e["to"] if e["from"] in frontier else e["from"]
        for n in (e["from"], e["to"]):
            node_score[n] = max(node_score.get(n, 0.0), e["score"])
        if other not in visited:
            visited.add(other)
            newly.append(other)
    return chosen, newly, pruned


def _relation_score_map(index: HybridIndex, query: str, cfg: _Cfg, pool: int = 400) -> dict[str, float]:
    """一次性算出"哪些关系跟这个问题相关",扩展时按 id 查表即可。"""
    out: dict[str, float] = {}
    for r in index.search_relations(query, k=pool, alpha=cfg.alpha):
        out[r["id"]] = r["score"]
    return out


# ---------------- 证据召回 ----------------
def _fetch_evidence(index: HybridIndex, query: str, cfg: _Cfg, exclude: set[str],
                    k: int | None = None) -> list[dict]:
    k = k or cfg.top_k
    pool = index.search_chunks(query, k=max(k * 3, 12), alpha=cfg.alpha)
    pool = [h for h in pool if h["id"] not in exclude]
    if not pool:
        return []
    if cfg.rerank and len(pool) > k:
        pairs = llm.rerank(query, [h["text"][:1500] for h in pool], top_n=k)
        if pairs:
            picked = []
            for idx, sc in pairs[:k]:
                h = dict(pool[idx])
                h["score"] = round(float(sc), 4)
                h["method"] = "重排"
                picked.append(h)
            return picked
    return pool[:k]


def _entity_payload(graph: GraphStore, ids: list[str], scores: dict[str, float]) -> list[dict]:
    out = []
    for n in ids:
        d = graph.node_detail(n)
        if not d:
            continue
        out.append({"id": n, "label": d["label"], "type": d["type"],
                    "description": d["description"], "aliases": d["aliases"],
                    "score": round(scores.get(n, 0.0), 4)})
    out.sort(key=lambda x: -x["score"])
    return out


def _relation_payload(edges: list[dict]) -> list[dict]:
    seen, out = set(), []
    for e in sorted(edges, key=lambda x: -x.get("score", 0)):
        eid = _edge_id(e)
        if eid in seen:
            continue
        seen.add(eid)
        out.append({"id": eid, "source": e["from"], "target": e["to"],
                    "relation": e["relation"], "description": e.get("description", ""),
                    "occurrence": e.get("occurrence", 1),
                    "score": e.get("score", 0), "hop": e.get("hop", 1)})
    return out


def _subgraph(graph: GraphStore, node_scores: dict[str, float], edges: list[dict],
              seeds: set[str]) -> dict:
    nodes = []
    for n, sc in node_scores.items():
        if not graph.has_node(n):
            continue
        d = graph.g.nodes[n]
        nodes.append({"id": n, "label": d.get("label", n), "type": d.get("type") or "其他",
                      "score": round(sc, 4), "seed": n in seeds,
                      "degree": graph.degree(n), "community": d.get("community")})
    nodes.sort(key=lambda x: -x["score"])
    return {"nodes": nodes, "edges": _relation_payload(edges)}


# ---------------- 作答 ----------------
def _answer_messages(question: str, context_text: str, history: list[dict] | None) -> list[dict]:
    hist = ""
    if history:
        turns = "\n".join(f"{h.get('role', 'user')}:{h.get('content', '')[:300]}"
                          for h in history[-4:])
        hist = f"\n【前序对话】\n{turns}\n"
    return [{"role": "system", "content": ANSWER_SYSTEM},
            {"role": "user", "content": ANSWER_USER.format(
                q=question, history=hist, context=context_text)}]


def _collect_citations(answer: str, chunks: list[dict]) -> list[dict]:
    """把 [^chunk_id] 解析成可点击的引用,指回具体原文。

    v1 的 citations 只是章节名字符串,点不动也定位不到,谈不上溯源。
    """
    by_id = {c["id"]: c for c in chunks}
    out, seen = [], set()
    for cid in _CITE_RE.findall(answer or ""):
        if cid in seen or cid not in by_id:
            continue
        seen.add(cid)
        c = by_id[cid]
        out.append({"chunk_id": cid, "heading": c.get("heading", ""),
                    "doc_id": c.get("doc_id"), "text": c.get("text", "")})
    # 模型没标注时,退回把实际用到的原文都列出来,至少可查
    if not out:
        for c in chunks[:6]:
            out.append({"chunk_id": c["id"], "heading": c.get("heading", ""),
                        "doc_id": c.get("doc_id"), "text": c.get("text", "")})
    return out


def _stream_answer(messages: list[dict], cfg: _Cfg) -> Iterator[dict]:
    """逐字吐出答案。v1 是阻塞调用,用户要盯着空白等 20~30 秒。"""
    if not cfg.stream:
        text = llm.chat(messages, temperature=0.3)
        yield {"type": "answer_delta", "text": text}
        yield {"type": "_final", "text": text}
        return
    buf = []
    for piece in llm.chat_stream(messages, temperature=0.3):
        buf.append(piece)
        yield {"type": "answer_delta", "text": piece}
    yield {"type": "_final", "text": "".join(buf)}


# ---------------- 非 agentic 模式的召回 ----------------
def _retrieve_static(mode: str, question: str, understood: dict, graph: GraphStore,
                     index: HybridIndex, communities: CommunityStore, cfg: _Cfg):
    """返回 (entities, relations_as_edges, chunks, community_reports, links, node_scores, seeds)。"""
    low = understood["low_level"]
    high = understood["high_level"]
    entities: list[dict] = []
    edges: list[dict] = []
    chunks: list[dict] = []
    reports: list[dict] = []
    links: list[dict] = []
    node_scores: dict[str, float] = {}
    seeds: list[str] = []

    if mode in ("local", "hybrid", "mix"):
        links, seeds, seed_score = _link(index, low or [question], cfg)
        node_scores.update(seed_score)
        for n in seeds[: cfg.top_k_entity]:
            for e in graph.neighbors(n, max_degree=cfg.max_node_degree):
                edges.append({**e, "score": round(seed_score.get(n, 0.4), 4), "hop": 1})
                for m in (e["from"], e["to"]):
                    node_scores.setdefault(m, seed_score.get(n, 0.4) * 0.6)

    if mode in ("global", "hybrid", "mix"):
        gq = " ".join(high or low or [question])
        for r in index.search_relations(gq, k=cfg.top_k_relation, alpha=cfg.alpha):
            edges.append({"from": r["source"], "to": r["target"], "relation": r["relation"],
                          "description": r.get("description", ""),
                          "occurrence": r.get("occurrence", 1),
                          "score": r["score"], "hop": 1})
            for m in (r["source"], r["target"]):
                node_scores[m] = max(node_scores.get(m, 0.0), r["score"] * 0.8)

    if mode in ("naive", "mix"):
        chunks += _fetch_evidence(index, question, cfg, set(), k=cfg.top_k)
    if mode in ("local", "global", "hybrid", "mix"):
        focus = " ".join(list(dict.fromkeys((low or []) + (high or [])))[:8])
        chunks += _fetch_evidence(index, f"{question} {focus}".strip(), cfg,
                                  {c["id"] for c in chunks}, k=cfg.top_k)

    if mode in ("global", "hybrid", "mix"):
        reports = communities.search(" ".join(high or [question]), k=3)

    entities = _entity_payload(graph, list(node_scores)[: cfg.top_k_entity * 2], node_scores)
    return entities, edges, chunks, reports, links, node_scores, seeds


# ---------------- 主入口 ----------------
def run_query(question: str, graph: GraphStore, index: HybridIndex,
              communities: CommunityStore, mode: str = "agentic",
              history: list[dict] | None = None, overrides: dict | None = None):
    started = time.time()
    cfg = _Cfg(db.get_all_config(), overrides)
    mode = mode if mode in MODES else "agentic"

    yield {"type": "start", "mode": mode,
           "graph": {"entities": graph.g.number_of_nodes(), "relations": graph.g.number_of_edges()}}

    # 1) 理解
    understood = _understand(question, history)
    yield {"type": "understand", "entities": understood["low_level"],
           "keywords": understood["high_level"], "intent": understood["intent"],
           "question_type": understood["question_type"]}

    if mode != "agentic":
        (entities, edges, chunks, reports, links,
         node_scores, seeds) = _retrieve_static(mode, question, understood, graph, index,
                                                communities, cfg)
        if links:
            yield {"type": "link", "links": links, "seeds": seeds}
        if edges:
            yield {"type": "hop", "round": 1, "max_rounds": 1, "pruned": 0,
                   "paths": _relation_payload(edges)[:60],
                   "new_nodes": list(node_scores)[:60], "frontier": seeds}
        if chunks:
            yield {"type": "evidence", "round": 1,
                   "items": [{"id": c["id"], "heading": c.get("heading", ""), "doc_id": c.get("doc_id"),
                              "snippet": c["text"][:260], "score": c.get("score", 0),
                              "method": c.get("method", "")} for c in chunks]}
        if reports:
            yield {"type": "community", "items": [{"title": r["title"], "summary": r["summary"],
                                                   "score": r.get("score", 0)} for r in reports]}
    else:
        # 2) 定位
        links, seeds, seed_score = _link(index, understood["low_level"] or [question], cfg)
        yield {"type": "link", "links": links, "seeds": seeds}

        node_scores: dict[str, float] = dict(seed_score)
        visited: set[str] = set(seeds)
        all_edges: list[dict] = []
        chunks: list[dict] = []
        evi_seen: set[str] = set()
        frontier = list(seeds)
        rel_scores = _relation_score_map(index, question + " " + " ".join(understood["high_level"]), cfg)
        reports = communities.search(" ".join(understood["high_level"] or [question]), k=2)
        if reports:
            yield {"type": "community", "items": [{"title": r["title"], "summary": r["summary"],
                                                   "score": r.get("score", 0)} for r in reports]}

        for rnd in range(1, cfg.max_rounds + 1):
            hop_edges: list[dict] = []
            newly_all: list[str] = []
            pruned_all = 0
            layer = list(frontier)
            for hop in range(cfg.max_hops):
                if not layer:
                    break
                chosen, newly, pruned = _beam_expand(graph, layer, node_scores, visited,
                                                     rel_scores, cfg, hop)
                hop_edges += chosen
                newly_all += newly
                pruned_all += pruned
                layer = newly
            all_edges += hop_edges
            yield {"type": "hop", "round": rnd, "max_rounds": cfg.max_rounds,
                   "paths": _relation_payload(hop_edges),
                   "new_nodes": newly_all, "frontier": frontier, "pruned": pruned_all}

            focus = " ".join(list(dict.fromkeys(frontier + newly_all))[:12])
            round_items = _fetch_evidence(index, f"{question} {focus}".strip(), cfg, evi_seen)
            for h in round_items:
                evi_seen.add(h["id"])
            chunks += round_items
            yield {"type": "evidence", "round": rnd,
                   "items": [{"id": c["id"], "heading": c.get("heading", ""),
                              "doc_id": c.get("doc_id"), "snippet": c["text"][:260],
                              "score": c.get("score", 0), "method": c.get("method", "")}
                             for c in round_items]}

            if rnd >= cfg.max_rounds:
                yield {"type": "reflect", "round": rnd, "sufficient": True,
                       "reason": "已达最大深挖轮数,进入作答。", "next_targets": []}
                break
            triples = "\n".join(
                f"- {e['from']} —[{e['relation']}]→ {e['to']}" +
                (f":{e.get('description', '')}" if e.get("description") else "")
                for e in sorted(all_edges, key=lambda x: -x["score"])[:40]) or "(暂无)"
            evidence_txt = "\n\n".join(
                f"【{c.get('heading') or '正文'}】{c['text'][:400]}" for c in chunks[:8]) or "(暂无)"
            try:
                rf = llm.chat_json([{"role": "user", "content": REFLECT_USER.format(
                    q=question, triples=triples, evidence=evidence_txt)}])
            except Exception:  # noqa: BLE001
                rf = {"sufficient": True, "reason": "反思步骤异常,直接作答。", "next_targets": []}
            if not isinstance(rf, dict):
                rf = {"sufficient": True, "reason": "反思返回格式异常,直接作答。", "next_targets": []}
            sufficient = bool(rf.get("sufficient", True))
            next_targets = [x for x in (rf.get("next_targets") or []) if isinstance(x, str)]
            yield {"type": "reflect", "round": rnd, "sufficient": sufficient,
                   "reason": rf.get("reason", ""), "next_targets": next_targets}
            if sufficient or not next_targets:
                break
            new_frontier = []
            for term in next_targets:
                for m in index.link_entity(term, k=2, alpha=cfg.alpha, threshold=cfg.link_threshold):
                    if m["id"] not in visited:
                        new_frontier.append(m["id"])
                        visited.add(m["id"])
                        node_scores[m["id"]] = max(node_scores.get(m["id"], 0), m["score"])
            if not new_frontier:
                break
            frontier = new_frontier

        entities = _entity_payload(
            graph, sorted(node_scores, key=lambda n: -node_scores[n])[: cfg.top_k_entity * 2],
            node_scores)
        edges = all_edges
        seeds_set = set(seeds)

    # 3) 装配上下文(按预算排序截断,不再盲切数组)
    if mode != "agentic":
        seeds_set = set(seeds)
    bundle = ctx_mod.build_context(entities, _relation_payload(edges), chunks, reports,
                                   cfg.budget, cfg.ratio)
    yield {"type": "context", "used_tokens": bundle.used_tokens, "budget": cfg.budget,
           "counts": {"entities": len(bundle.entities), "relations": len(bundle.relations),
                      "chunks": len(bundle.chunks), "communities": len(bundle.communities)},
           "dropped": bundle.dropped}

    subgraph = _subgraph(graph, node_scores, edges, seeds_set)

    # 4) 作答(流式)
    if not bundle.text.strip():
        messages = [{"role": "user", "content": NO_CONTEXT_ANSWER.format(q=question)}]
    else:
        messages = _answer_messages(question, bundle.text, history)
    yield {"type": "answer_start"}
    answer = ""
    try:
        for ev in _stream_answer(messages, cfg):
            if ev["type"] == "_final":
                answer = ev["text"]
            else:
                yield ev
    except Exception as e:  # noqa: BLE001
        answer = f"(作答失败:{e})"
        yield {"type": "answer_delta", "text": answer}

    yield {"type": "answer", "answer": answer,
           "citations": _collect_citations(answer, bundle.chunks),
           "subgraph": subgraph, "mode": mode,
           "duration_ms": int((time.time() - started) * 1000)}