sales-assistant-py-new/app/chat_qa/nodes/quality_check_node.py

76 lines
3.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import PromptTemplate
from langgraph.runtime import Runtime
from app.chat_qa.context import QAContext
from app.chat_qa.qa_state import QAState
from app.llm import llm
from app.core.log import logger
"""
相关问题质检,
"""
async def quality_check(state: QAState, runtime: Runtime[QAContext]):
prompt="""你是一位培训机构QA质检员。请判断以下QA对是否符合常规培训相关的问题。
## 判断标准
1. **问题是否属于培训常见问题**
- 课程知识疑问(概念、原理、用法)
- 学习方法咨询(怎么学、学习顺序、技巧)
- 实操问题(代码、工具、步骤、报错)
- 考试/面试相关(考点、面试题、准备方法)
- 就业/职业规划(岗位、薪资、发展方向)
2. **答案是否对应问题**
- 答案内容与问题相关
- 如果聊天记录中没有明确答案answer为空是合理的
3. **以下情况判定为不合理**
- 闲聊寒暄("在吗""你好""今天天气"
- 纯情绪表达("太难了""不想学了"
- 系统/账号问题("密码忘了""怎么登录"
- 问题过于模糊,没有具体指向("介绍一下""说说看"
## 输出格式JSON
{
"is_valid": true/false,
"score": 0.0-1.0,
"reason": "简要说明判定理由"
}"""
current_qas_list = state.get("current_qas", [])
chat_history = state["chat_history"]
if len(current_qas_list) == 0:
return {"is_valid": True}# 聊天本身数据质量问题,直接跳过
# 最终通过的QA
final_qas = []
for current_qas in current_qas_list:
messages = [
SystemMessage(content=prompt),
HumanMessage(content=f"原聊天内容:{chat_history}待质检的QA对\n{current_qas}")
]
try:
output = JsonOutputParser()
chain = llm | output
result = await chain.ainvoke(messages)
# 容错
if isinstance(result, list) and len(result) > 0:
# 如果是数组,取第一个元素
data = result[0]
elif isinstance(result, dict):
data = result
else:
# 空兜底,避免报错
data = {}
if result.get("is_valid", False):
final_qas.append(current_qas)
logger.info(f"QA质检结果{result}")
except Exception as e:
logger.error(f"QA质检失败{e}")
return {"is_valid": True, "final_qas": final_qas} # 异常:跳过
if len(final_qas) == 0:
return {"is_valid": False}
return {"is_valid": True, "final_qas": final_qas}