前后端更新

This commit is contained in:
super committed 2026-03-04 22:55:36 +08:00
1 parent a0c8721fbb
commit 24da604727
33 files changed
+1951 -580

No files matched your search

+17 -16
View File
@@ -85,22 +85,21 @@ class DifyService:
full_answer.append(data.get('answer', ''))
elif event == 'message_end':
# 对话结束,记录日志
# 异步或在此处记录日志(为了演示简单,此处同步记录,生产环境建议放入 Celery/RQ)
latency = int((time.time() - start_time) * 1000)
metadata = data.get('metadata', {})
usage = metadata.get('usage', {})
# 创建日志条目
# 注意:在生成器中操作 DB 需要确保应用上下文存在
DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id'),
query=query,
answer="".join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency
)
# 显式使用应用上下文
with current_app.app_context():
DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id') or conversation_id,
query=query,
answer="".join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency
)
except json.JSONDecodeError:
continue
@@ -120,18 +119,20 @@ class DifyService:
用途:将对话详情持久化到 ChatLog 表
"""
try:
# 确保在应用上下文中(Flask stream_with_context 会保持上下文)
# 确保在应用上下文中
chat_log = ChatLog(
user_id=user_id,
agent_id=agent_id,
conversation_id=conversation_id,
query=query,
answer=answer,
tokens_used=tokens,
latency=latency
tokens_used=tokens or 0,
latency=latency or 0
)
db.session.add(chat_log)
db.session.commit()
except Exception as e:
current_app.logger.error(f"Failed to log chat: {e}")
# Re-acquire logger from current_app as it might be detached
if current_app:
current_app.logger.error(f"Failed to log chat: {e}")
db.session.rollback()