修复AI建议逻辑和字段映射问题
- 修复AI建议基于问题描述而不是处理过程生成 - 修复工单详情页面显示逻辑 - 修复飞书时间字段处理(毫秒时间戳转换) - 优化字段映射和转换逻辑 - 添加飞书集成功能 - 改进对话历史合并功能 - 优化系统优化反馈机制
This commit is contained in:
@@ -101,26 +101,47 @@ class DialogueManager:
|
||||
# 性能优化分析
|
||||
optimization_result = self.system_optimizer.optimize_response_time(response_time)
|
||||
|
||||
# 记录Token使用情况
|
||||
if success and "token_usage" in response_result:
|
||||
token_usage = response_result["token_usage"]
|
||||
# 计算成本
|
||||
# 记录Token使用情况(兼容多种返回格式)
|
||||
if success:
|
||||
# 兼容返回 usage: {prompt_tokens, completion_tokens}
|
||||
usage = response_result.get("usage", {}) or {}
|
||||
token_usage = response_result.get("token_usage", {}) or {}
|
||||
input_tokens = token_usage.get("input_tokens")
|
||||
output_tokens = token_usage.get("output_tokens")
|
||||
if input_tokens is None and isinstance(usage, dict):
|
||||
input_tokens = usage.get("prompt_tokens") or usage.get("input_tokens") or 0
|
||||
if output_tokens is None and isinstance(usage, dict):
|
||||
output_tokens = usage.get("completion_tokens") or usage.get("output_tokens") or 0
|
||||
|
||||
# 若均为0,使用简易估算(避免记录缺失)
|
||||
if not input_tokens and user_message:
|
||||
try:
|
||||
input_tokens = max(1, len(user_message) // 4)
|
||||
except Exception:
|
||||
input_tokens = 0
|
||||
if not output_tokens and response_result.get("response"):
|
||||
try:
|
||||
output_tokens = max(1, len(response_result.get("response")) // 4)
|
||||
except Exception:
|
||||
output_tokens = 0
|
||||
|
||||
model_name = response_result.get("model") or response_result.get("model_name") or "qwen-plus-latest"
|
||||
|
||||
# 计算成本并限制
|
||||
estimated_cost = self.token_monitor._calculate_cost(
|
||||
response_result.get("model_name", "qwen-plus-latest"),
|
||||
token_usage.get("input_tokens", 0),
|
||||
token_usage.get("output_tokens", 0)
|
||||
model_name,
|
||||
int(input_tokens or 0),
|
||||
int(output_tokens or 0)
|
||||
)
|
||||
|
||||
# 检查成本限制
|
||||
if not self.system_optimizer.check_cost_limit(estimated_cost):
|
||||
return {"error": "请求成本超限,请稍后再试"}
|
||||
|
||||
|
||||
self.token_monitor.record_token_usage(
|
||||
user_id=user_id or "anonymous",
|
||||
work_order_id=work_order_id,
|
||||
model_name=response_result.get("model_name", "qwen-plus-latest"),
|
||||
input_tokens=token_usage.get("input_tokens", 0),
|
||||
output_tokens=token_usage.get("output_tokens", 0),
|
||||
model_name=model_name,
|
||||
input_tokens=int(input_tokens or 0),
|
||||
output_tokens=int(output_tokens or 0),
|
||||
response_time=response_time,
|
||||
success=success,
|
||||
error_message=error_message
|
||||
|
||||
@@ -140,7 +140,7 @@ class RealtimeChatManager:
|
||||
if len(session["context"]) > 20: # 保留最近10轮对话
|
||||
session["context"] = session["context"][-20:]
|
||||
|
||||
# 保存到数据库
|
||||
# 保存到数据库(每轮一条,带会话标记)
|
||||
self._save_conversation(session_id, user_msg, assistant_msg)
|
||||
|
||||
return {
|
||||
@@ -274,30 +274,32 @@ class RealtimeChatManager:
|
||||
"""保存对话到数据库"""
|
||||
try:
|
||||
with db_manager.get_session() as session:
|
||||
# 保存用户消息
|
||||
user_conversation = Conversation(
|
||||
work_order_id=user_msg.work_order_id,
|
||||
user_message=user_msg.content,
|
||||
assistant_response="", # 用户消息没有助手回复
|
||||
timestamp=user_msg.timestamp,
|
||||
confidence_score=None,
|
||||
knowledge_used=None,
|
||||
response_time=None
|
||||
)
|
||||
session.add(user_conversation)
|
||||
|
||||
# 保存助手消息
|
||||
assistant_conversation = Conversation(
|
||||
work_order_id=assistant_msg.work_order_id,
|
||||
user_message="", # 助手消息没有用户输入
|
||||
assistant_response=assistant_msg.content,
|
||||
timestamp=assistant_msg.timestamp,
|
||||
# 统一为一条记录:包含用户消息与助手回复
|
||||
try:
|
||||
response_time = None
|
||||
if assistant_msg.timestamp and user_msg.timestamp:
|
||||
response_time = max(0.0, (assistant_msg.timestamp - user_msg.timestamp).total_seconds() * 1000.0)
|
||||
except Exception:
|
||||
response_time = None
|
||||
|
||||
# 在知识字段中打上会话标记,便于结束时合并清理
|
||||
marked_knowledge = assistant_msg.knowledge_used or []
|
||||
try:
|
||||
marked_knowledge = list(marked_knowledge)
|
||||
marked_knowledge.append({"session_id": session_id, "type": "session_marker"})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
conversation = Conversation(
|
||||
work_order_id=assistant_msg.work_order_id or user_msg.work_order_id,
|
||||
user_message=user_msg.content or "",
|
||||
assistant_response=assistant_msg.content or "",
|
||||
timestamp=assistant_msg.timestamp or user_msg.timestamp,
|
||||
confidence_score=assistant_msg.confidence_score,
|
||||
knowledge_used=json.dumps(assistant_msg.knowledge_used, ensure_ascii=False) if assistant_msg.knowledge_used else None,
|
||||
response_time=0.5 # 模拟响应时间
|
||||
knowledge_used=json.dumps(marked_knowledge, ensure_ascii=False) if marked_knowledge else None,
|
||||
response_time=response_time
|
||||
)
|
||||
session.add(assistant_conversation)
|
||||
|
||||
session.add(conversation)
|
||||
session.commit()
|
||||
|
||||
except Exception as e:
|
||||
@@ -385,6 +387,56 @@ class RealtimeChatManager:
|
||||
"""结束会话"""
|
||||
try:
|
||||
if session_id in self.active_sessions:
|
||||
session_meta = self.active_sessions[session_id]
|
||||
# 汇总本会话为一条记录
|
||||
history = self.message_history.get(session_id, [])
|
||||
if history:
|
||||
user_parts = []
|
||||
assistant_parts = []
|
||||
response_times = []
|
||||
first_ts = None
|
||||
last_ts = None
|
||||
for i in range(len(history)):
|
||||
msg = history[i]
|
||||
if first_ts is None:
|
||||
first_ts = msg.timestamp
|
||||
last_ts = msg.timestamp
|
||||
if msg.role == "user":
|
||||
user_parts.append(msg.content)
|
||||
# 计算到下一条助手回复的间隔
|
||||
if i + 1 < len(history) and history[i+1].role == "assistant":
|
||||
try:
|
||||
rt = max(0.0, (history[i+1].timestamp - msg.timestamp).total_seconds() * 1000.0)
|
||||
response_times.append(rt)
|
||||
except Exception:
|
||||
pass
|
||||
elif msg.role == "assistant":
|
||||
assistant_parts.append(msg.content)
|
||||
agg_user = "\n\n".join([p for p in user_parts if p])
|
||||
agg_assistant = "\n\n".join([p for p in assistant_parts if p])
|
||||
avg_rt = sum(response_times)/len(response_times) if response_times else None
|
||||
|
||||
from ..core.database import db_manager as _db
|
||||
from ..core.models import Conversation as _Conv
|
||||
import json as _json
|
||||
with _db.get_session() as dbs:
|
||||
agg = _Conv(
|
||||
work_order_id=session_meta.get("work_order_id"),
|
||||
user_message=agg_user,
|
||||
assistant_response=agg_assistant,
|
||||
timestamp=last_ts or first_ts,
|
||||
confidence_score=None,
|
||||
knowledge_used=_json.dumps({"session_id": session_id, "aggregated": True}, ensure_ascii=False),
|
||||
response_time=avg_rt
|
||||
)
|
||||
dbs.add(agg)
|
||||
# 删除本会话标记的分散记录
|
||||
try:
|
||||
pattern = f'%"session_id":"{session_id}"%'
|
||||
dbs.query(_Conv).filter(_Conv.knowledge_used.like(pattern)).delete(synchronize_session=False)
|
||||
except Exception:
|
||||
pass
|
||||
dbs.commit()
|
||||
del self.active_sessions[session_id]
|
||||
|
||||
if session_id in self.message_history:
|
||||
|
||||
Reference in New Issue
Block a user