TypeSafe模型生成评分

This commit is contained in:
2026-09-21 21:08:51 +08:00
parent 1de953b58f
commit d9c948f0c5
11 changed files with 490 additions and 48 deletions
+222
View File
@@ -0,0 +1,222 @@
"""单元测试:generate_node TypeSafe 路径。
mock typesafe_scorer 与 llm_client,不依赖 Ollama/Chroma/网络。
"""
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from app.core.rag_pipeline import generate_node, confidence_node
from app.config import Settings
# ==================== 辅助构造 ====================
def _make_state(
chunks=None,
question="测试问题",
self_eval=None,
help_id=None,
faq_score=0.0,
**extra,
) -> dict:
if chunks is None:
chunks = [
{"id": "c1", "document": "知识库片段A", "score": 0.95, "metadata": {}},
]
state: dict = {
"question": question,
"original_question": question,
"help_type_id": "product",
"history_qa": [],
"embedding": [],
"chunks": chunks,
"prompt": "",
"help_id": help_id,
"help_state": None,
"qv_score": None,
"answer": "",
"confidence": 0.0,
"confidence_breakdown": {},
"self_eval": self_eval if self_eval is not None else {},
"sources": [],
"faq_answer": "",
"faq_score": faq_score,
"faq_group_id": "",
"resolved_query": question,
"resolution_note": "no_change",
"category": "product_service",
"casual_reply": None,
"keywords": None,
"expanded_words": None,
}
state.update(extra)
return state
# ==================== Fixtures ====================
@pytest.fixture(autouse=True)
def _reset_typesafe_enabled(monkeypatch):
"""确保测试不会意外读取真实 .env 中的 RAG_TYPESAFE_ENABLED。"""
monkeypatch.setattr("app.config.settings.rag_typesafe_enabled", False)
monkeypatch.setattr("app.config.settings.rag_self_eval_enabled", True)
@pytest.fixture
def mock_llm_client(monkeypatch):
client = MagicMock()
client.chat_completion = AsyncMock(return_value="正常回答内容")
monkeypatch.setattr("app.core.rag_pipeline.llm_client", client)
return client
@pytest.fixture
def mock_typesafe_scorer(monkeypatch):
scorer = MagicMock()
scorer.score_answer = AsyncMock(return_value=None)
monkeypatch.setattr("app.core.rag_pipeline.typesafe_scorer", scorer)
return scorer
# ==================== 测试用例 ====================
class TestGenerateNodeTypesafeOn:
"""TypeSafe 开启时的行为。"""
@pytest.fixture(autouse=True)
def _enable_typesafe(self, monkeypatch):
monkeypatch.setattr("app.config.settings.rag_typesafe_enabled", True)
async def test_typesafe_on_returns_four_scores(
self, mock_llm_client, mock_typesafe_scorer
):
"""typesafe 开 + mock 返回四维分 → self_eval 四键齐全、answer 带 [AI] 前缀"""
mock_typesafe_scorer.score_answer.return_value = {
"factual_accuracy": 8.0,
"relevance": 9.0,
"completeness": 7.0,
"no_hallucination": 6.0,
}
state = _make_state()
result = await generate_node(state)
assert result["answer"].startswith("[AI] ")
assert result["self_eval"] == {
"factual_accuracy": 8.0,
"relevance": 9.0,
"completeness": 7.0,
"no_hallucination": 6.0,
}
mock_typesafe_scorer.score_answer.assert_called_once()
# LLM 调用不带 response_format(json_object)
call_kwargs = mock_llm_client.chat_completion.call_args[1]
assert call_kwargs.get("response_format") is None
async def test_typesafe_on_scorer_raises(self, mock_llm_client, mock_typesafe_scorer):
"""typesafe 开 + scorer 返回None(模拟异常回退) → self_eval={},流水线不失败"""
mock_typesafe_scorer.score_answer.return_value = None
state = _make_state()
result = await generate_node(state)
assert result["self_eval"] == {}
assert result["answer"].startswith("[AI] ")
async def test_typesafe_on_refusal_answer(self, mock_llm_client, mock_typesafe_scorer):
"""typesafe 开 + 拒答回答 → self_eval={}(正则抑制)"""
mock_typesafe_scorer.score_answer.return_value = {
"factual_accuracy": 5.0,
"relevance": 3.0,
"completeness": 4.0,
"no_hallucination": 2.0,
}
mock_llm_client.chat_completion.return_value = "抱歉,知识库中没有相关信息"
state = _make_state()
result = await generate_node(state)
assert result["self_eval"] == {}
assert "抱歉" in result["answer"]
async def test_typesafe_on_answer_truncated_200(self, mock_llm_client, mock_typesafe_scorer):
"""typesafe 开 + answer > 200 字 → 截断到 200"""
mock_typesafe_scorer.score_answer.return_value = {
"factual_accuracy": 8.0,
"relevance": 9.0,
"completeness": 7.0,
"no_hallucination": 6.0,
}
long_answer = "A" * 300
mock_llm_client.chat_completion.return_value = long_answer
state = _make_state()
result = await generate_node(state)
assert len(result["answer"]) == len("[AI] " + long_answer[:200])
assert result["answer"] == "[AI] " + long_answer[:200]
class TestGenerateNodeTypesafeOff:
"""TypeSafe 关闭时,legacy 路径行为不变。"""
@pytest.fixture(autouse=True)
def _disable_typesafe(self, monkeypatch):
monkeypatch.setattr("app.config.settings.rag_typesafe_enabled", False)
monkeypatch.setattr("app.config.settings.rag_self_eval_enabled", True)
async def test_typesafe_off_legacy_path(self, mock_llm_client):
"""typesafe 关 → 使用 SYSTEM_PROMPT + json_object + _parse_generate_output"""
legacy_json = (
'{"answer":"这是答案","self_eval":{'
'"factual_accuracy":8,"relevance":9,"completeness":7,"no_hallucination":6}}'
)
mock_llm_client.chat_completion.return_value = legacy_json
state = _make_state()
result = await generate_node(state)
assert result["answer"].startswith("[AI] ")
assert result["self_eval"] == {
"factual_accuracy": 8,
"relevance": 9,
"completeness": 7,
"no_hallucination": 6,
}
# LLM 调用应带 response_format=json_object
call_kwargs = mock_llm_client.chat_completion.call_args[1]
assert call_kwargs.get("response_format") == {"type": "json_object"}
class TestConfidenceNodeGate:
"""confidence_node 门控微调:只要有四键即融合,不需要 rag_self_eval_enabled。"""
async def test_confidence_with_all_keys_no_self_eval_flag(self, monkeypatch):
"""self_eval 有键即融合,即使 rag_self_eval_enabled=False"""
monkeypatch.setattr("app.config.settings.rag_self_eval_enabled", False)
state = _make_state(
help_id=None,
faq_score=0.0,
chunks=[
{"id": "c1", "document": "doc", "score": 0.90, "metadata": {}},
],
self_eval={
"factual_accuracy": 8.0,
"relevance": 9.0,
"completeness": 7.0,
"no_hallucination": 6.0,
},
)
result = await confidence_node(state)
# 应走自评融合分支,confidence_breakdown 包含 self_eval_score
assert "self_eval_score" in result["confidence_breakdown"]
assert result["confidence_breakdown"]["self_eval_score"] > 0.0
async def test_confidence_without_keys(self, monkeypatch):
"""self_eval 缺键 → 旧公式,self_eval_score=0.0"""
monkeypatch.setattr("app.config.settings.rag_self_eval_enabled", False)
state = _make_state(
help_id=None,
faq_score=0.0,
chunks=[
{"id": "c1", "document": "doc", "score": 0.90, "metadata": {}},
],
self_eval={},
)
result = await confidence_node(state)
assert result["confidence_breakdown"]["self_eval_score"] == 0.0