TypeSafe模型生成评分
This commit is contained in:
+8
-2
@@ -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
|
||||
|
||||
+58
-26
@@ -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
|
||||
|
||||
@@ -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()
|
||||
+17
-9
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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=[
|
||||
"回答包含大量片段未提及的编造内容",
|
||||
"回答包含明显的编造内容",
|
||||
"回答基本忠实于片段,有个别添加",
|
||||
"回答忠实于片段,无实质编造",
|
||||
"回答完全基于片段,无任何编造",
|
||||
],
|
||||
),
|
||||
}
|
||||
Reference in New Issue
Block a user