This commit is contained in:
2025-08-20 14:23:33 +08:00
parent 8e799f8d55
commit a59c956a2c
6 changed files with 69 additions and 8 deletions

View File

@@ -27,6 +27,7 @@ client = AsyncOpenAI(
# 初始化 ElasticSearch 工具
search_util = EsSearchUtil(Config.ES_CONFIG)
@router.post("/chat")
async def chat(request: fastapi.Request):
"""
@@ -37,6 +38,8 @@ async def chat(request: fastapi.Request):
data = await request.json()
user_id = data.get('user_id', 'anonymous')
query = data.get('query', '')
type_id = data.get('type_id', '1') # 1-教学模式2-对话模式
yunxiao_sample = data.get('yunxiao_sample', False) # 是不是给长春云校做例子
session_id = data.get('session_id', str(uuid.uuid4())) # 获取或生成会话ID
include_history = data.get('include_history', True)
@@ -96,6 +99,9 @@ async def chat(request: fastapi.Request):
for i, (user_msg, ai_msg) in enumerate(recent_history, 1):
history_context += f"[对话 {i}] 用户: {user_msg}\n"
history_context += f"[对话 {i}] 老师: {ai_msg}\n"
if yunxiao_sample:
with open(r"D:\dsWork\dsProject\dsLightRag\static\YunXiao.txt", "r", encoding="utf-8") as f:
history_context += f"[讨论的内容] " + f.read() + "\n"
# 4. 构建学生信息上下文
student_context = ""
@@ -121,6 +127,9 @@ async def chat(request: fastapi.Request):
最重要的是:不要直接给出答案,而是通过合作和基于学生已有知识的引导,帮助学生自己找到答案。
"""
if type_id == 2:
system_prompt = "你是一位具有丰富经验的K12教师可以解答学生提出的各类问题。"
# 添加学生信息到系统提示词
if user_id in search_util.student_info and search_util.student_info[user_id]:
student_info_str = "\n\n学生基础信息:\n"
@@ -171,7 +180,8 @@ async def chat(request: fastapi.Request):
answer_tags = [f"{user_id}_answer", f"time:{current_time.split()[0]}", f"session:{session_id}"]
try:
seg_list = jieba.cut(answer_text, cut_all=False)
answer_keywords = [kw for kw in seg_list if kw.strip() and kw not in search_util.STOPWORDS and len(kw) > 1]
answer_keywords = [kw for kw in seg_list if
kw.strip() and kw not in search_util.STOPWORDS and len(kw) > 1]
answer_keywords = answer_keywords[:5]
answer_tags.extend([f"keyword:{kw}" for kw in answer_keywords])
except Exception as e:
@@ -201,4 +211,3 @@ async def chat(request: fastapi.Request):
except Exception as e:
logger.error(f"聊天接口异常: {str(e)}")
raise HTTPException(status_code=500, detail=f"处理请求失败: {str(e)}")