test_engine_integration.py 6.73 KB
"""检索引擎端到端(打桩 LLM,不走网络):六种模式都要能跑通并产出可溯源的答案。"""
from __future__ import annotations
import json
import sys
from pathlib import Path

import numpy as np
import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from app.extract.community import CommunityStore   # noqa: E402
from app.retrieve import engine                    # noqa: E402
from app.store import vector_store as vs           # noqa: E402
from app.store.graph_store import GraphStore       # noqa: E402


def _fake_embed(texts, *a, **kw):
    """可复现的伪向量:靠字符哈希,相似文本自然更接近。"""
    if not texts:
        return np.zeros((0, 16), dtype=np.float32)
    arr = np.zeros((len(texts), 16), dtype=np.float32)
    for i, t in enumerate(texts):
        for ch in (t or "x"):
            arr[i][ord(ch) % 16] += 1.0
    norms = np.linalg.norm(arr, axis=1, keepdims=True)
    norms[norms == 0] = 1.0
    return arr / norms


@pytest.fixture()
def world(tmp_path: Path, monkeypatch):
    graph = GraphStore(tmp_path / "graph.json")
    src = {"chunk_id": "d1:c0", "doc_id": 1, "heading": "赔付规则", "snippet": "…"}
    graph.add_entity("门店", "门店", "线下销售网点", src, doc_id=1)
    graph.add_entity("兜底协议", "协议", "未达标时的赔付约定", src, doc_id=1)
    graph.add_entity("生态系数", "指标", "衡量门店生态经营水平", src, doc_id=1)
    graph.add_relation("门店", "兜底协议", "签署", "门店与主机厂签署兜底协议", src, doc_id=1)
    graph.add_relation("兜底协议", "生态系数", "计算依赖", "赔付金额依赖生态系数", src, doc_id=1)

    index = vs.HybridIndex(tmp_path / "index")
    monkeypatch.setattr(vs.llm, "embed", _fake_embed)
    monkeypatch.setattr(engine.llm, "embed", _fake_embed)
    index.upsert_chunks(1, [
        {"id": "d1:c0", "doc_id": 1, "order": 0, "heading": "赔付规则",
         "text": "门店未达标时,按兜底协议约定的差额赔付,赔付金额依赖生态系数。", "tokens": 30},
        {"id": "d1:c1", "doc_id": 1, "order": 1, "heading": "生态系数",
         "text": "生态系数由多项渗透率加权得出,每个生态月结算一次。", "tokens": 25},
    ])
    index.rebuild_entities(graph.all_entities())
    index.rebuild_relations(graph.all_relations())

    communities = CommunityStore(tmp_path / "communities.json")
    communities.reports = [{"id": 0, "title": "门店赔付体系", "summary": "围绕兜底协议的赔付与考核",
                            "keywords": ["兜底", "赔付"], "size": 3,
                            "members": ["门店", "兜底协议", "生态系数"],
                            "top_entities": ["门店"]}]

    def fake_chat(messages, temperature=0.2, **kw):
        body = json.dumps(messages, ensure_ascii=False)
        if "low_level" in body:
            return json.dumps({"low_level": ["门店", "兜底协议"], "high_level": ["赔付规则"],
                               "intent": "想知道赔付怎么算", "question_type": "calculation"},
                              ensure_ascii=False)
        if "sufficient" in body:
            return json.dumps({"sufficient": True, "reason": "已覆盖", "next_targets": []},
                              ensure_ascii=False)
        return "门店未达标按兜底协议的差额赔付 [^d1:c0],金额依赖生态系数 [^d1:c1]。"

    monkeypatch.setattr(engine.llm, "chat", fake_chat)
    monkeypatch.setattr(engine.llm, "chat_json",
                        lambda m, **kw: engine.llm.parse_json(fake_chat(m)))
    monkeypatch.setattr(engine.llm, "chat_stream",
                        lambda m, **kw: iter([fake_chat(m)]))
    monkeypatch.setattr(engine.llm, "rerank", lambda *a, **kw: [])
    return graph, index, communities


def _run(world, mode):
    graph, index, communities = world
    return list(engine.run_query("门店没达标要赔多少钱?", graph, index, communities, mode=mode))


@pytest.mark.parametrize("mode", list(engine.MODES))
def test_every_mode_produces_an_answer(world, mode):
    events = _run(world, mode)
    kinds = [e["type"] for e in events]
    assert "understand" in kinds
    assert kinds[-1] == "answer"
    answer = events[-1]
    assert answer["answer"]
    assert answer["mode"] == mode
    assert "subgraph" in answer


def test_agentic_emits_the_full_transparent_trace(world):
    events = _run(world, "agentic")
    kinds = {e["type"] for e in events}
    # 透明深挖的每一步都必须暴露出来,这是本系统的核心卖点
    for step in ("start", "understand", "link", "hop", "evidence", "reflect",
                 "context", "answer_start", "answer"):
        assert step in kinds, f"缺少 {step} 事件"


def test_citations_point_back_to_real_chunks(world):
    answer = _run(world, "agentic")[-1]
    ids = {c["chunk_id"] for c in answer["citations"]}
    assert "d1:c0" in ids
    assert all(c["doc_id"] == 1 for c in answer["citations"])


def test_context_event_reports_budget_usage(world):
    ctx = next(e for e in _run(world, "agentic") if e["type"] == "context")
    assert ctx["used_tokens"] > 0
    assert ctx["used_tokens"] <= ctx["budget"]
    assert ctx["counts"]["chunks"] >= 1


def test_hop_paths_carry_scores(world):
    hops = [e for e in _run(world, "agentic") if e["type"] == "hop"]
    assert hops
    paths = hops[0]["paths"]
    assert paths and all("score" in p for p in paths)
    assert paths == sorted(paths, key=lambda p: -p["score"])


def test_global_mode_uses_relation_index(world):
    """v1 根本没有关系向量索引,global 模式无从谈起。"""
    events = _run(world, "global")
    hop = next((e for e in events if e["type"] == "hop"), None)
    assert hop is not None and hop["paths"]


def test_empty_graph_says_so_instead_of_hallucinating(tmp_path: Path, monkeypatch):
    graph = GraphStore(tmp_path / "g.json")
    monkeypatch.setattr(vs.llm, "embed", _fake_embed)
    monkeypatch.setattr(engine.llm, "embed", _fake_embed)
    index = vs.HybridIndex(tmp_path / "idx")
    communities = CommunityStore(tmp_path / "c.json")
    captured = {}

    def fake_chat(messages, **kw):
        captured["last"] = json.dumps(messages, ensure_ascii=False)
        return "知识库里没有能回答这个问题的依据。"

    monkeypatch.setattr(engine.llm, "chat", fake_chat)
    monkeypatch.setattr(engine.llm, "chat_json", lambda m, **kw: {})
    monkeypatch.setattr(engine.llm, "chat_stream", lambda m, **kw: iter([fake_chat(m)]))
    monkeypatch.setattr(engine.llm, "rerank", lambda *a, **kw: [])

    events = list(engine.run_query("随便问点什么", graph, index, communities, mode="agentic"))
    assert events[-1]["type"] == "answer"
    assert "没有检索到" in captured["last"]     # 走的是"无依据"提示词