engine.py 17.3 KB
"""检索引擎:透明深挖。

多轮深挖,每一步(理解/定位/扩展/取证/反思/作答)都以事件流暴露出来。

深挖的核心修复: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__)

_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)}


# ---------------- 主入口 ----------------
def run_query(question: str, graph: GraphStore, index: HybridIndex,
              communities: CommunityStore,
              history: list[dict] | None = None, overrides: dict | None = None,
              answer: bool = True, seeds_hint: list[str] | None = None):
    """深挖检索主入口。

    `answer=False`:只检索不作答,最后吐一条 `retrieved`(上下文 + 证据),
    供统一提问把它当作 search_knowledge 工具调用。
    `seeds_hint`:编排层已经链接到的概念名,补进理解结果的实体词里,定位更准。
    """
    started = time.time()
    cfg = _Cfg(db.get_all_config(), overrides)

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

    # 1) 理解
    understood = _understand(question, history)
    for h in seeds_hint or []:
        if h and h not in understood["low_level"]:
            understood["low_level"].append(h)
    yield {"type": "understand", "entities": understood["low_level"],
           "keywords": understood["high_level"], "intent": understood["intent"],
           "question_type": understood["question_type"]}

    # 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) 装配上下文(按预算排序截断,不再盲切数组)
    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)

    if not answer:
        yield {"type": "retrieved", "context_text": bundle.text,
               "chunks": [{"id": c["id"], "heading": c.get("heading", ""),
                           "doc_id": c.get("doc_id"), "text": c["text"]} for c in bundle.chunks],
               "entities": [e.get("label") or e.get("id") for e in bundle.entities][:30],
               "relations": [f"{r.get('source')}-{r.get('relation')}->{r.get('target')}"
                             for r in bundle.relations][:40],
               "subgraph": subgraph, "duration_ms": int((time.time() - started) * 1000)}
        return

    # 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,
           "duration_ms": int((time.time() - started) * 1000)}