test_rag_runtime_controls.py 16.1 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 450 451 452 453
import asyncio
import sys
import types
from types import SimpleNamespace

agentscope = types.ModuleType("agentscope")
agentscope.init = lambda *args, **kwargs: None
agentscope_message = types.ModuleType("agentscope.message")
agentscope_message.Msg = object
agentscope_model = types.ModuleType("agentscope.model")
agentscope_model.DashScopeChatModel = object
sys.modules.setdefault("agentscope", agentscope)
sys.modules.setdefault("agentscope.message", agentscope_message)
sys.modules.setdefault("agentscope.model", agentscope_model)

from sqlalchemy.orm import declarative_base

database_session = types.ModuleType("src.database.session")
database_session.Base = declarative_base()
database_session.AsyncSessionLocal = None
sys.modules.setdefault("src.database.session", database_session)

fastapi = types.ModuleType("fastapi")


class HTTPException(Exception):
    def __init__(self, status_code=500, detail=None):
        super().__init__(detail)
        self.status_code = status_code
        self.detail = detail


fastapi.HTTPException = HTTPException
fastapi.UploadFile = object
sys.modules.setdefault("fastapi", fastapi)

from src.rag import llm, reranker, retrieval, service
from src.rag.retrieval import IntentResult
from src.utils.llm_tracker import print_thinking


def _chunk(chunk_id: str, content: str = "content", **overrides):
    data = {
        "chunk_id": chunk_id,
        "file_id": "file-1",
        "parent_chunk_id": None,
        "chunk_level": "parent",
        "chunk_index": 0,
        "content": content,
        "title_path": "title",
        "source_name": "source.pdf",
        "page_number": 1,
        "slide_number": None,
        "sheet_name": None,
        "row_start": None,
        "row_end": None,
        "status": "active",
        "intent_type": "product",
        "page_type": "product",
        "brand": "智界",
        "business_category": "权益类",
        "metadata_json": "{}",
    }
    data.update(overrides)
    return SimpleNamespace(**data)


def test_chat_stream_filters_thinking_by_default(monkeypatch):
    async def fake_stream():
        yield SimpleNamespace(content=[{"type": "thinking", "thinking": "secret"}])
        yield SimpleNamespace(
            content=[
                {"type": "thinking", "thinking": "secret"},
                {"type": "text", "text": "visible answer"},
            ]
        )

    class FakeModel:
        async def __call__(self, messages):
            return fake_stream()

    monkeypatch.setattr(llm, "get_llm_model", lambda model_name: FakeModel())

    async def collect():
        return [event async for event in llm.chat_stream("model", "prompt")]

    events = asyncio.run(collect())

    assert events == [{"type": "answer_delta", "content": "visible answer"}]


def test_stream_query_disables_stdout_thinking_during_answer_generation(monkeypatch):
    async def noop_schema():
        return None

    async def fake_classify(query, history):
        return IntentResult(intent="general_knowledge", intents=["general_knowledge"])

    async def fake_retrieve(query, intent, history, user_context):
        return {
            "chunks": [_chunk("chunk-1")],
            "ranked": [],
            "query_plan": {},
            "queries": [],
            "filters": {},
            "soft_boosts": {},
        }

    async def fake_generate_answer_stream(query, intent, chunks, history):
        assert print_thinking.get() is False
        yield {"type": "thinking_delta", "content": "secret"}
        yield {"type": "answer_delta", "content": "answer"}

    async def fake_save_query(payload, intent, retrieval_data, answer, tokens, start, status):
        return {"answer": answer, "sources": [], "citations": []}

    monkeypatch.setattr(service, "ensure_rag_schema", noop_schema)
    monkeypatch.setattr(service, "classify_intent", fake_classify)
    monkeypatch.setattr(service, "retrieve", fake_retrieve)
    monkeypatch.setattr(retrieval, "generate_answer_stream", fake_generate_answer_stream)
    monkeypatch.setattr(service, "_save_query", fake_save_query)

    token = print_thinking.set(True)
    try:
        payload = SimpleNamespace(query="有什么服务", history=[], userContext={}, sessionId="s1")

        async def collect():
            return [event async for event in service.stream_query(payload)]

        events = asyncio.run(collect())
    finally:
        print_thinking.reset(token)

    assert {"type": "thinking_delta", "content": "secret"} not in events
    assert {"type": "answer_delta", "content": "answer"} in events


def test_stream_query_ignores_need_clarification_and_retrieves(monkeypatch):
    async def noop_schema():
        return None

    async def fake_classify(query, history):
        return IntentResult(
            intent="product",
            intents=["product"],
            need_clarification=True,
            clarification_question="请补充车型",
        )

    async def fake_retrieve(query, intent, history, user_context):
        return {
            "chunks": [],
            "ranked": [],
            "query_plan": {"direct_query": query},
            "queries": [{"type": "direct", "query": query}],
            "filters": {},
            "soft_boosts": {},
        }

    async def fake_save_query(payload, intent, retrieval_data, answer, tokens, start, status):
        return {"answer": answer, "query_plan": retrieval_data.get("query_plan", {})}

    monkeypatch.setattr(service, "ensure_rag_schema", noop_schema)
    monkeypatch.setattr(service, "_build_effective_history", lambda payload: asyncio.sleep(0, result=[]))
    monkeypatch.setattr(service, "classify_intent", fake_classify)
    monkeypatch.setattr(service, "retrieve", fake_retrieve)
    monkeypatch.setattr(service, "_save_query", fake_save_query)

    payload = SimpleNamespace(query="智界延保多少钱", history=[], userContext={}, sessionId="s1")

    async def collect():
        return [event async for event in service.stream_query(payload)]

    events = asyncio.run(collect())

    assert {"type": "answer_delta", "content": "请补充车型"} not in events
    assert any(event["type"] == "retrieval_done" and event["data"].get("query_plan") for event in events)


def test_reranker_uses_configured_model_and_records_scores(monkeypatch):
    calls = {}

    class Result:
        def __init__(self, index, score):
            self.index = index
            self.relevance_score = score

    class TextReRank:
        @staticmethod
        def call(**kwargs):
            calls.update(kwargs)
            return SimpleNamespace(
                status_code=200,
                output=SimpleNamespace(results=[Result(1, 0.91), Result(0, 0.32)]),
            )

    monkeypatch.setitem(sys.modules, "dashscope", SimpleNamespace(TextReRank=TextReRank))
    monkeypatch.setattr(reranker, "RAG_RERANKER_MODEL", "custom-rerank", raising=False)

    first = _chunk("first", content="first")
    second = _chunk("second", content="second")

    ranked = reranker.rerank_chunks("query", [first, second])

    assert calls["model"] == "custom-rerank"
    assert [chunk.chunk_id for chunk in ranked] == ["second", "first"]
    assert ranked[0].rerank_score == 0.91
    assert ranked[1].rerank_score == 0.32


def test_reranker_defaults_to_qwen3_vl_rerank():
    assert reranker.RAG_RERANKER_MODEL == "qwen3-vl-rerank"


def test_reranker_logs_model_status_and_message_on_error(monkeypatch, caplog):
    class TextReRank:
        @staticmethod
        def call(**kwargs):
            return SimpleNamespace(status_code=400, message="Model not exist.")

    monkeypatch.setitem(sys.modules, "dashscope", SimpleNamespace(TextReRank=TextReRank))
    monkeypatch.setattr(reranker, "RAG_RERANKER_MODEL", "qwen3-vl-rerank", raising=False)

    first = _chunk("first", content="first")
    second = _chunk("second", content="second")

    with caplog.at_level("WARNING"):
        ranked = reranker.rerank_chunks("query", [first, second])

    assert ranked == [first, second]
    assert "model=qwen3-vl-rerank" in caplog.text
    assert "status=400" in caplog.text
    assert "Model not exist." in caplog.text


def test_apply_context_budget_prefers_direct_high_score_chunks(monkeypatch):
    monkeypatch.setattr(retrieval, "RAG_MAX_CONTEXT_CHARS", 16)
    neighbor = _chunk("neighbor", content="neighbor text")
    neighbor.final_score = 0.1
    neighbor.is_neighbor = True
    direct = _chunk("direct", content="direct text")
    direct.final_score = 0.9
    direct.is_neighbor = False

    selected = retrieval._apply_context_budget([neighbor, direct])

    assert [chunk.chunk_id for chunk in selected] == ["direct"]


def test_merge_candidates_sorts_by_hybrid_score_and_dedupes_by_parent():
    hits_a = [
        {
            "chunk_id": "plain-child",
            "hybrid_score": 0.4,
            "payload": {"chunk_id": "plain-child", "parent_chunk_id": "plain-parent", "file_id": "file-1"},
        },
        {
            "chunk_id": "table-child",
            "hybrid_score": 0.6,
            "payload": {"chunk_id": "table-child", "parent_chunk_id": "table-parent", "file_id": "file-1"},
        },
    ]
    # 第二路召回里同一个父块拿到更高分,应被合并保留最高分
    hits_b = [
        {
            "chunk_id": "plain-child-2",
            "hybrid_score": 0.9,
            "payload": {"chunk_id": "plain-child-2", "parent_chunk_id": "plain-parent", "file_id": "file-1"},
        },
    ]

    candidates = retrieval._candidates_from_hits(hits_a, "direct") + retrieval._candidates_from_hits(hits_b, "standalone")
    ranked = retrieval._merge_candidates(candidates)

    assert [c.parent_chunk_id for c in ranked] == ["plain-parent", "table-parent"]
    assert ranked[0].hybrid_score == 0.9
    assert "direct" in ranked[0].retrieval_type and "standalone" in ranked[0].retrieval_type


def test_chunk_to_dict_adds_source_index_and_citation_uses_it():
    first = service._chunk_to_dict(_chunk("chunk-1"), source_index=1)
    second = service._chunk_to_dict(_chunk("chunk-2"), source_index=2)
    third = service._chunk_to_dict(_chunk("chunk-3"), source_index=3)

    citations = service._build_citations("参考 [1][3][99]", [first, second, third])

    assert first["source_index"] == 1
    assert [item["chunk_id"] for item in citations] == ["chunk-1", "chunk-3"]
    assert [item["index"] for item in citations] == [1, 3]


def test_build_effective_history_loads_session_logs(monkeypatch):
    class FakeLog:
        def __init__(self, query_text, answer_text):
            self.query_text = query_text
            self.answer_text = answer_text

    async def fake_load_session_history(session_id, limit=6):
        assert session_id == "s-memory"
        return [
            FakeLog("智界延保多少钱", "智界延保价格见价格总览。"),
            FakeLog("免责有哪些", "免责包含事故车等情况。"),
        ]

    monkeypatch.setattr(service, "_load_session_history", fake_load_session_history)

    payload = SimpleNamespace(sessionId="s-memory", history=[])
    history = asyncio.run(service._build_effective_history(payload))

    assert history == [
        {"role": "user", "content": "智界延保多少钱"},
        {"role": "assistant", "content": "智界延保价格见价格总览。"},
        {"role": "user", "content": "免责有哪些"},
        {"role": "assistant", "content": "免责包含事故车等情况。"},
    ]


def test_clear_history_deletes_only_requested_session(monkeypatch):
    calls = []

    class FakeSession:
        async def __aenter__(self):
            return self

        async def __aexit__(self, exc_type, exc, tb):
            return False

        async def execute(self, stmt):
            calls.append(str(stmt))

            class Result:
                @property
                def rowcount(self):
                    return 2

            return Result()

        async def commit(self):
            calls.append("commit")

    monkeypatch.setattr(service, "AsyncSessionLocal", lambda: FakeSession())

    result = asyncio.run(service.clear_history("s-clear"))

    assert result == {"status": "success", "deleted": 2, "sessionId": "s-clear"}
    assert "DELETE FROM rag_query_logs" in calls[0]
    assert "session_id" in calls[0]
    assert "commit" in calls


def test_stream_query_emits_reasoning_steps_and_logs_complete_answer(monkeypatch, caplog):
    async def noop_schema():
        return None

    async def fake_build_effective_history(payload):
        return [{"role": "user", "content": "上一轮"}]

    async def fake_classify(query, history):
        assert history == [{"role": "user", "content": "上一轮"}]
        return IntentResult(intent="general_knowledge", intents=["general_knowledge"])

    async def fake_retrieve(query, intent, history, user_context):
        return {
            "chunks": [_chunk("chunk-1")],
            "ranked": [],
            "query_plan": {"direct_query": query},
            "queries": [{"type": "direct", "query": query}],
            "filters": {},
            "soft_boosts": {},
        }

    async def fake_generate_answer_stream(query, intent, chunks, history):
        yield {"type": "answer_delta", "content": "流式"}
        yield {"type": "answer_delta", "content": "回答"}

    async def fake_save_query(payload, intent, retrieval_data, answer, tokens, start, status):
        return {"answer": answer, "sources": [], "citations": [], "duration_ms": 1}

    monkeypatch.setattr(service, "ensure_rag_schema", noop_schema)
    monkeypatch.setattr(service, "_build_effective_history", fake_build_effective_history)
    monkeypatch.setattr(service, "classify_intent", fake_classify)
    monkeypatch.setattr(service, "retrieve", fake_retrieve)
    monkeypatch.setattr(retrieval, "generate_answer_stream", fake_generate_answer_stream)
    monkeypatch.setattr(service, "_save_query", fake_save_query)

    payload = SimpleNamespace(query="继续说", history=[], userContext={}, sessionId="s1")

    async def collect():
        return [event async for event in service.stream_query(payload)]

    with caplog.at_level("INFO"):
        events = asyncio.run(collect())

    reasoning_phases = [
        event["data"]["phase"]
        for event in events
        if event.get("type") == "reasoning_step"
    ]
    assert "intent" in reasoning_phases
    assert "retrieval" in reasoning_phases
    assert "sources" in reasoning_phases
    assert "answer" in reasoning_phases
    assert "answer_delta:" not in caplog.text
    assert "answer complete:" in caplog.text
    assert "流式回答" in caplog.text


def test_stream_query_done_survives_query_log_save_failure(monkeypatch, caplog):
    async def noop_schema():
        return None

    async def fake_build_effective_history(payload):
        return []

    async def fake_classify(query, history):
        return IntentResult(intent="general_knowledge", intents=["general_knowledge"])

    async def fake_retrieve(query, intent, history, user_context):
        return {
            "chunks": [_chunk("chunk-1")],
            "ranked": [],
            "query_plan": {"direct_query": query},
            "queries": [{"type": "direct", "query": query}],
            "filters": {},
            "soft_boosts": {},
        }

    async def fake_generate_answer_stream(query, intent, chunks, history):
        yield {"type": "answer_delta", "content": "answer"}

    async def fake_save_query(payload, intent, retrieval_data, answer, tokens, start, status):
        raise RuntimeError("db unavailable")

    monkeypatch.setattr(service, "ensure_rag_schema", noop_schema)
    monkeypatch.setattr(service, "_build_effective_history", fake_build_effective_history)
    monkeypatch.setattr(service, "classify_intent", fake_classify)
    monkeypatch.setattr(service, "retrieve", fake_retrieve)
    monkeypatch.setattr(retrieval, "generate_answer_stream", fake_generate_answer_stream)
    monkeypatch.setattr(service, "_save_query", fake_save_query)

    payload = SimpleNamespace(query="question", history=[], userContext={}, sessionId="s1")

    async def collect():
        return [event async for event in service.stream_query(payload)]

    with caplog.at_level("ERROR"):
        events = asyncio.run(collect())

    done = [event for event in events if event.get("type") == "done"]
    assert done
    assert done[-1]["data"]["answer"] == "answer"
    assert done[-1]["data"]["queryLogId"] is None
    assert "failed to save query log" in caplog.text