diff --git a/.env.example b/.env.example index f71260b..d668853 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,5 @@ # ========== 服务配置 ========== -SERVICE_HOST=0.0.0.0 +SERVICE_HOST=127.0.0.1 SERVICE_PORT=8990 # ========== ChromaDB 配置 (PersistentClient 模式) ========== @@ -49,9 +49,16 @@ RAG_CONFIDENCE_KEYWORD_WEIGHT=0.15 # ========== LLM 自评(generate 节点 JSON 自评,融入 KB 路径置信度),出问题可一键旁路 ========== RAG_SELF_EVAL_ENABLED=true -RAG_CONFIDENCE_SELF_EVAL_WEIGHT=0.3 # 自评信号融合权重(检索信号 = 1 - 该值) +RAG_CONFIDENCE_SELF_EVAL_WEIGHT=0.4 # 自评信号融合权重(检索信号 = 1 - 该值) RAG_LLM_MAX_TOKENS=1024 # 流水线 LLM 调用统一 max_tokens +# ========== TypeSafe(generate 节点回答打分),出问题可一键旁路 ========== +RAG_TYPESAFE_ENABLED=false +# 填入你的 TypeSafe API Key(留空则打分自动回退旧公式) +TYPESAFE_API_KEY= +TYPESAFE_MODEL=jev-latest +TYPESAFE_TIMEOUT=10 + # ========== BM25 关键词检索 ========== BM25_INDEX_PATH=./bm25_data BM25_ENABLED=true @@ -60,4 +67,4 @@ BM25_ENABLED=true RRF_ALPHA=60.0 # 平滑参数,越大越平滑,建议 30~120 # ========== 日志 ========== -LOG_LEVEL=INFO \ No newline at end of file +LOG_LEVEL=INFO diff --git a/Dockerfile b/Dockerfile index 256e43e..0e8635e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,4 +29,4 @@ RUN mkdir -p ./chroma_data EXPOSE 8990 # 启动命令 -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8990"] \ No newline at end of file +CMD ["uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", "8990"] \ No newline at end of file diff --git a/README.md b/README.md index 415ef26..97266be 100644 --- a/README.md +++ b/README.md @@ -67,13 +67,17 @@ BM25_INDEX_PATH=./bm25_data ```bash # 开发模式 -uvicorn app.main:app --host 0.0.0.0 --port 8990 --reload +uvicorn app.main:app --host 127.0.0.1 --port 8990 --reload # 或使用 Docker docker build -t changzuo-rag-service . -docker run -p 8990:8990 -v ./chroma_data:/app/chroma_data --env-file .env changzuo-rag-service +docker run -p 8990:8990 -v ./chroma_data:/app/chroma_data -v ./.env:/app/.env changzuo-rag-service ``` +> 注意:挂载 `.env`(`-v ./.env:/app/.env`)而不是用 `--env-file .env`。 +> Docker 的 `--env-file` **不会**剥离行内 `#` 注释,会把 `KEY=value # 说明` 整体当作值注入, +> 覆盖 python-dotenv 的正确解析,导致 pydantic 报 `float_parsing` / `int_parsing` 错误。 + > 生产部署(systemd + Nginx 反向代理)见 `docs/ragservice-deploy-guide.md`。 ## API 接口 @@ -91,7 +95,7 @@ docker run -p 8990:8990 -v ./chroma_data:/app/chroma_data --env-file .env changz | DELETE | `/py/rag/delKF/{file_id}` | 按 file_id 删除知识库文档 | | POST | `/py/rag/addQAF` | 上传 FAQ 文档(multipart/form-data,`问:/答:` 格式) | | DELETE | `/py/rag/delQAF/{file_id}` | 按 file_id 删除 FAQ 文档 | -| GET | `/health` | 健康检查(ChromaDB + Ollama + LLM 三组件) | +| GET | `/health` | 健康检查(ChromaDB + Ollama + LLM + TypeSafe 四组件) | ### 请求/响应格式 @@ -242,7 +246,7 @@ score(doc) = Σ 1/(rank + α) # α = RRF_ALPHA,默认 60 | 配置项 | 默认值 | 说明 | |--------|--------|------| -| `SERVICE_HOST` / `SERVICE_PORT` | `0.0.0.0` / `8990` | 服务监听地址 | +| `SERVICE_HOST` / `SERVICE_PORT` | `127.0.0.1` / `8990` | 服务监听地址 | | `CHROMADB_PATH` | `./chroma_data` | ChromaDB 持久化目录 | | `OLLAMA_BASE_URL` | `http://localhost:11434` | Ollama 地址 | | `OLLAMA_EMBED_MODEL` | `nomic-embed-text` | 嵌入模型 | diff --git a/app/config.py b/app/config.py index b6236bb..93ba1cb 100644 --- a/app/config.py +++ b/app/config.py @@ -3,7 +3,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): # 服务配置 - service_host: str = "0.0.0.0" + service_host: str = "127.0.0.1" service_port: int = 8990 # ChromaDB 配置 (PersistentClient 模式) @@ -55,10 +55,16 @@ class Settings(BaseSettings): # LLM 自评(generate 节点输出 JSON 自评分数,融入 KB 路径置信度;出问题可一键旁路) rag_self_eval_enabled: bool = True # 自评信号融合权重(检索信号权重 = 1 - 该值) - rag_confidence_self_eval_weight: float = 0.3 + rag_confidence_self_eval_weight: float = 0.4 # RAG 流水线 LLM 调用统一 max_tokens(preprocess / generate 共用;JSON 结构 + 自评字段需更大预算) rag_llm_max_tokens: int = 1024 + # TypeSafe 集成(generate 节点回答打分;出问题可一键旁路) + rag_typesafe_enabled: bool = False + typesafe_api_key: str = "" + typesafe_model: str = "jev-latest" + typesafe_timeout: int = 10 + # BM25 关键词检索 bm25_index_path: str = "./bm25_data" bm25_enabled: bool = True diff --git a/app/core/rag_pipeline.py b/app/core/rag_pipeline.py index 15474c6..03f76d9 100644 --- a/app/core/rag_pipeline.py +++ b/app/core/rag_pipeline.py @@ -8,6 +8,7 @@ from langgraph.graph import StateGraph from app.config import settings from app.core.embeddings import ollama_embeddings_adapter from app.core.llm_client import llm_client +from app.core.typesafe_client import typesafe_scorer from app.core.vector_store import get_vector_store_adapter from app.prompts.preprocess_prompt import PREPROCESS_SYSTEM_PROMPT from app.prompts.reply_prompt import SYSTEM_PROMPT, LEGACY_SYSTEM_PROMPT, USER_TEMPLATE @@ -308,38 +309,69 @@ async def generate_node(state: RagState) -> RagState: prompt = USER_TEMPLATE.format(context=context, question=state["question"]) state["prompt"] = prompt - system_prompt = SYSTEM_PROMPT if settings.rag_self_eval_enabled else LEGACY_SYSTEM_PROMPT + use_typesafe = settings.rag_typesafe_enabled + # TypeSafe 路径:纯文本回答(LEGACY),自评交给 TypeSafe 独立裁判 + system_prompt = LEGACY_SYSTEM_PROMPT if use_typesafe else ( + SYSTEM_PROMPT if settings.rag_self_eval_enabled else LEGACY_SYSTEM_PROMPT + ) messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": state["prompt"]} ] - try: - raw = await llm_client.chat_completion( - messages, - temperature=settings.llm_temperature, - max_tokens=settings.rag_llm_max_tokens, # 统一 LLM 调用预算(config 可调) - top_p=settings.llm_top_p, - response_format={"type": "json_object"} if settings.rag_self_eval_enabled else None, - ) - except Exception as e: - # json_object 模式下输出被 max_tokens 截断时 langchain 会抛异常("length limit was reached"), - # 捕获后降级重试:去掉 json_object,由 _parse_generate_output/_extract_json 容错回退纯文本,RAG 不失败 - logger.warning(f"generate: json_object 调用失败,降级重试: {e}") - raw = await llm_client.chat_completion( - messages, - temperature=settings.llm_temperature, - max_tokens=settings.rag_llm_max_tokens, - top_p=settings.llm_top_p, - response_format=None, - ) + # 自评来源:TypeSafe(独立裁判)或 LLM 自评(旧路径) + if use_typesafe: + try: + raw = await llm_client.chat_completion( + messages, + temperature=settings.llm_temperature, + max_tokens=settings.rag_llm_max_tokens, + top_p=settings.llm_top_p, + response_format=None, # TypeSafe 路径不需要 json_object + ) + except Exception as e: + logger.warning(f"generate: LLM 调用失败,重试: {e}") + raw = await llm_client.chat_completion( + messages, + temperature=settings.llm_temperature, + max_tokens=settings.rag_llm_max_tokens, + top_p=settings.llm_top_p, + response_format=None, + ) + answer = raw.strip() + self_eval = await typesafe_scorer.score_answer( + state["question"], answer, context + ) or {} + else: + try: + raw = await llm_client.chat_completion( + messages, + temperature=settings.llm_temperature, + max_tokens=settings.rag_llm_max_tokens, + top_p=settings.llm_top_p, + response_format={"type": "json_object"} if settings.rag_self_eval_enabled else None, + ) + except Exception as e: + logger.warning(f"generate: json_object 调用失败,降级重试: {e}") + raw = await llm_client.chat_completion( + messages, + temperature=settings.llm_temperature, + max_tokens=settings.rag_llm_max_tokens, + top_p=settings.llm_top_p, + response_format=None, + ) + answer, self_eval = _parse_generate_output(raw) - answer, self_eval = _parse_generate_output(raw) - - # 截断到 200 字,确保不超过 640 字节(仅截断 answer 字段,不影响 JSON 结构) + # 截断到 200 字(两条路径共用) if len(answer) > 200: answer = answer[:200] state["answer"] = "[AI] " + answer + + # 拒答检测:拒答/无相关信息时抑制自评,避免虚高分污染置信度(两条路径共用) + if re.search(r"抱歉|对不起|没有.*相关信息|无法回答|未找到|知识库中.*没有", answer): + logger.info(f"generate: 检测到拒答回答,抑制 self_eval: {answer[:50]}") + self_eval = {} + state["self_eval"] = self_eval logger.info(f"generate: self_eval={self_eval}") return state @@ -464,7 +496,7 @@ async def confidence_node(state: RagState) -> RagState: # 4. LLM 自评信号(新增) se = state.get("self_eval") or {} - if settings.rag_self_eval_enabled and all( + if all( k in se for k in ["factual_accuracy", "relevance", "completeness", "no_hallucination"] ): self_eval_score = ( @@ -473,8 +505,8 @@ async def confidence_node(state: RagState) -> RagState: ) / 10.0 # 防御性调整(仅自评有效分支内生效;回退路径不进入此块) - if self_eval_score >= 0.8 and retrieval_pass < 0.5: - # 自评高 + 检索差:自评不可信,权重压制 + if retrieval_pass < 0.5: + # 检索差:自评不可信,权重压制 w_retrieval, w_self_eval = 0.9, 0.1 else: w_retrieval = 1.0 - settings.rag_confidence_self_eval_weight diff --git a/app/core/typesafe_client.py b/app/core/typesafe_client.py new file mode 100644 index 0000000..1b5cc2d --- /dev/null +++ b/app/core/typesafe_client.py @@ -0,0 +1,97 @@ +"""TypeSafe System One 客户端封装(generate 节点回答打分)。 + +设计目标: +- 独立裁判:打分模型与生成模型分离,避免自评偏差; +- 失败安全:SDK 内置重试策略(429/529 指数退避),任何异常返回 None 由调用方回退; +- 配置旁路:rag_typesafe_enabled=False 时完全不调用; +- 类型化原语:Score/Choice/Noul 由 SDK 定义,后续 preprocess 分类可直接复用。 +""" +import logging +from typing import Any, Dict, Optional + +from typesafe_sdk import AsyncTypeSafeClient + +from app.config import settings +from app.prompts.score_prompt import SCORE_QUESTIONS + +logger = logging.getLogger(__name__) + +_NUM_LEVELS = 5 # 与 score_prompt 的等级数一致 + + +def _to_0_10(score: float) -> float: + """Score 返回概率加权的等级位置(0 ~ _NUM_LEVELS-1),归一化到 0-10。""" + return round(score / (_NUM_LEVELS - 1) * 10, 1) + + +class TypeSafeScorer: + async def score_answer( + self, + question: str, + answer: str, + context: str, + ) -> Optional[Dict[str, float]]: + """对回答四维打分,返回 {factual_accuracy, relevance, completeness, no_hallucination}(0-10)。 + + 失败返回 None(调用方回退旧公式)。 + """ + if not settings.rag_typesafe_enabled: + return None + try: + async with AsyncTypeSafeClient( + api_key=settings.typesafe_api_key, + timeout=settings.typesafe_timeout, + ) as client: + response = await client.system_one( + state={ + "question": question, + "answer": answer, + "context": context, + }, + questions=SCORE_QUESTIONS, + model=settings.typesafe_model, + ) + scores = response.scores + return { + "factual_accuracy": _to_0_10(scores["factual_accuracy"].score), + "relevance": _to_0_10(scores["relevance"].score), + "completeness": _to_0_10(scores["completeness"].score), + "no_hallucination": _to_0_10(scores["no_hallucination"].score), + } + except Exception as e: + logger.warning(f"typesafe: 打分失败,回退旧公式: {e}") + return None + + async def health_check(self) -> Dict[str, Any]: + """健康检查:验证 TypeSafe API 连通性与鉴权(轻量 GET /v1/models,不触发打分推理)。 + + - 开关关闭:status=disabled(可选组件被旁路,不算故障) + - 调用成功:status=healthy + 账号可用模型列表 + - 异常:status=unhealthy + error + """ + if not settings.rag_typesafe_enabled: + return { + "status": "disabled", + "model": settings.typesafe_model, + } + try: + async with AsyncTypeSafeClient( + api_key=settings.typesafe_api_key, + timeout=settings.typesafe_timeout, + ) as client: + response = await client.models.list() + return { + "status": "healthy", + "model": settings.typesafe_model, + "available_models": [m.name for m in response.models], + } + except Exception as e: + logger.warning(f"typesafe: 健康检查失败: {e}") + return { + "status": "unhealthy", + "error": str(e), + "model": settings.typesafe_model, + } + + +typesafe_scorer = TypeSafeScorer() diff --git a/app/main.py b/app/main.py index 6a18a93..d5c9e17 100644 --- a/app/main.py +++ b/app/main.py @@ -1,8 +1,12 @@ # ChromaDB 依赖 sqlite3 >= 3.35.0,部分 Linux 发行版自带版本过低 # 使用 pysqlite3-binary 提供的现代 SQLite 替代系统 sqlite3 -__import__('pysqlite3') -import sys -sys.modules['sqlite3'] = sys.modules.pop('pysqlite3') +# Windows 无 pysqlite3-binary wheel,回退系统 sqlite3(3.43.1 满足要求) +try: + __import__('pysqlite3') + import sys + sys.modules['sqlite3'] = sys.modules.pop('pysqlite3') +except ImportError: + pass from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware @@ -15,6 +19,7 @@ from app.api.routes_rag import router as rag_router from app.core.embeddings import ollama_embeddings_adapter from app.core.vector_store import get_vector_store_adapter from app.core.llm_client import llm_client +from app.core.typesafe_client import typesafe_scorer # 配置日志 logging.basicConfig( @@ -50,17 +55,19 @@ app.include_router(rag_router) @app.get("/health") async def health_check(): - """健康检查端点:检查 ChromaDB、Ollama、LLM API 连通性""" + """健康检查端点:检查 ChromaDB、Ollama、LLM API、TypeSafe 连通性""" vector_store = get_vector_store_adapter() chromadb_health = vector_store.health_check() ollama_health = await ollama_embeddings_adapter.health_check() llm_health = await llm_client.health_check() - + typesafe_health = await typesafe_scorer.health_check() + + # disabled 视为正常(可选组件被旁路),只有 unhealthy 才判为降级 all_healthy = all( - h.get("status") == "healthy" - for h in [chromadb_health, ollama_health, llm_health] + h.get("status") in ("healthy", "disabled") + for h in [chromadb_health, ollama_health, llm_health, typesafe_health] ) - + return { "status": "healthy" if all_healthy else "degraded", "service": "changzuo-rag-service", @@ -68,7 +75,8 @@ async def health_check(): "components": { "chromadb": chromadb_health, "ollama": ollama_health, - "llm": llm_health + "llm": llm_health, + "typesafe": typesafe_health } } diff --git a/app/prompts/score_prompt.py b/app/prompts/score_prompt.py new file mode 100644 index 0000000..3c36d0f --- /dev/null +++ b/app/prompts/score_prompt.py @@ -0,0 +1,57 @@ +"""TypeSafe Score 问题定义(generate 节点回答打分)。 + +使用 SDK 的 Score 原语,criteria 为【有序等级描述数组】(0 基索引,最多 10 级)。 +score 返回概率加权的等级位置(0 ~ len-1),归一化到 0-10 在 typesafe_client 中做。 + +等级语义对齐原 SYSTEM_PROMPT 锚点: +- factual_accuracy:有编造的事实则 ≤6 +- relevance:答非所问则 ≤3 +- completeness:遗漏关键信息则 ≤5 +- no_hallucination:有编造则 ≤3 + +等级措辞需在真实数据上验证后微调(见 plan §7)。 +""" +from typesafe_sdk import Score + +SCORE_QUESTIONS = { + "factual_accuracy": Score( + instructions="回答中的事实是否与知识库片段一致?", + criteria=[ + "回答包含片段中完全没有的关键事实,或关键名称/数字错误", + "回答存在明显与片段不符的编造事实", + "回答事实与片段基本一致,有个别细节出入", + "回答事实与片段一致,表述略有出入但不影响正确性", + "回答中的所有事实都与片段完全一致", + ], + ), + "relevance": Score( + instructions="回答是否直接回答了用户的问题?", + criteria=[ + "回答与用户问题完全无关", + "回答偏离问题主题,答非所问", + "回答部分相关,但未直接命中问题核心", + "回答直接针对问题,略有冗余", + "回答精准直接地回答了用户问题", + ], + ), + "completeness": Score( + instructions="知识库片段中的相关信息是否都被用上了?", + criteria=[ + "遗漏了片段中所有关键信息", + "遗漏了大部分关键信息", + "覆盖了部分关键信息,有遗漏", + "覆盖了绝大部分关键信息", + "覆盖了片段中全部相关信息", + ], + ), + "no_hallucination": Score( + instructions="回答中是否有片段里完全没有提及的编造内容?", + criteria=[ + "回答包含大量片段未提及的编造内容", + "回答包含明显的编造内容", + "回答基本忠实于片段,有个别添加", + "回答忠实于片段,无实质编造", + "回答完全基于片段,无任何编造", + ], + ), +} diff --git a/pyproject.toml b/pyproject.toml index 20a6719..8177033 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,9 @@ dependencies = [ # 向量数据库 - ChromaDB 1.5+ "chromadb==1.5.9", + # SQLite3 兼容层 (Linux 系统自带 sqlite3 版本过低时 ChromaDB 需要 >= 3.35.0;Windows 无此 wheel,main.py 自动回退) + "pysqlite3-binary==0.5.4; sys_platform != 'win32'", + # Ollama 客户端 (仅用于嵌入) "ollama==0.6.2", @@ -56,6 +59,9 @@ dependencies = [ # 实用工具 "python-multipart==0.0.32", "python-dotenv==1.2.3", + + # TypeSafe 回答打分(独立裁判) + "typesafe-sdk==0.7.0", ] [project.optional-dependencies] diff --git a/requirements.txt b/requirements.txt index 1950b9c..a2fe954 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,8 +4,8 @@ uvicorn[standard]==0.52.4 pydantic==2.13.5 pydantic-settings==2.15.0 -# SQLite3 兼容层 (系统自带 sqlite3 版本过低时 ChromaDB 需要 >= 3.35.0) -pysqlite3-binary==0.5.4 +# SQLite3 兼容层 (系统自带 sqlite3 版本过低时 ChromaDB 需要 >= 3.35.0;Windows 无此 wheel,main.py 自动回退) +pysqlite3-binary==0.5.4; sys_platform != "win32" # 向量数据库 - ChromaDB 1.5+ chromadb==1.5.9 @@ -36,4 +36,7 @@ bm25s==0.3.11 # 实用工具 python-multipart==0.0.32 -python-dotenv==1.2.3 \ No newline at end of file +python-dotenv==1.2.3 + +# TypeSafe 回答打分(独立裁判) +typesafe-sdk==0.7.0 \ No newline at end of file diff --git a/tests/test_generate_typesafe.py b/tests/test_generate_typesafe.py new file mode 100644 index 0000000..fe61294 --- /dev/null +++ b/tests/test_generate_typesafe.py @@ -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