合并代码,解决冲突
(cherry picked from commit 8b23bd771f04ceb1b9c1e3ae021d75001af5ba2f)
This commit is contained in:
1 parent
23badf7456
commit
93e99793d8
10 files changed
+626
-84
No files matched your search
+307
-46
@@ -12,16 +12,18 @@ import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
|
||||
from sqlalchemy import func, desc
|
||||
from sqlalchemy import func, desc, or_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, Feedback
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
|
||||
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
||||
@@ -30,6 +32,118 @@ chat_bp = Blueprint('chat', __name__)
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
|
||||
|
||||
def _session_title_from_text(text: str) -> str:
|
||||
value = str(text or '').strip()
|
||||
if not value:
|
||||
return ''
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
'id': session.id,
|
||||
'conversation_id': session.session_id,
|
||||
'title': session.title or '',
|
||||
'created_at': last_active.isoformat() if last_active else '',
|
||||
'status': session.status,
|
||||
}
|
||||
|
||||
|
||||
def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
|
||||
session_key = str(session_id or '').strip()
|
||||
if not session_key:
|
||||
return None
|
||||
return db.session.query(ChatSession).filter_by(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=session_key,
|
||||
).first()
|
||||
|
||||
|
||||
def _ensure_chat_session(
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str | None,
|
||||
title: str = '',
|
||||
status: str = 'running',
|
||||
external_conversation_id: str | None = None,
|
||||
):
|
||||
session_key = str(session_id or '').strip()
|
||||
external_id = str(external_conversation_id or '').strip() or None
|
||||
session = _get_chat_session(user_id, agent_id, session_key)
|
||||
changed = False
|
||||
if not session:
|
||||
session = ChatSession(
|
||||
session_id=session_key or uuid.uuid4().hex,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title=_session_title_from_text(title),
|
||||
status=status,
|
||||
external_conversation_id=external_id,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_active_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(session)
|
||||
db.session.commit()
|
||||
return session
|
||||
|
||||
if not session.title and title:
|
||||
session.title = _session_title_from_text(title)
|
||||
changed = True
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
if external_id and session.external_conversation_id != external_id:
|
||||
session.external_conversation_id = external_id
|
||||
changed = True
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return session
|
||||
|
||||
|
||||
def _update_chat_session(
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str,
|
||||
*,
|
||||
status: str | None = None,
|
||||
external_conversation_id: str | None = None,
|
||||
title: str | None = None,
|
||||
touch: bool = False,
|
||||
):
|
||||
session = _get_chat_session(user_id, agent_id, session_id)
|
||||
if not session:
|
||||
return None
|
||||
|
||||
changed = False
|
||||
if title and not session.title:
|
||||
session.title = _session_title_from_text(title)
|
||||
changed = True
|
||||
|
||||
external_id = str(external_conversation_id or '').strip() or None
|
||||
if external_id and session.external_conversation_id != external_id:
|
||||
session.external_conversation_id = external_id
|
||||
changed = True
|
||||
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
|
||||
if touch or changed:
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return session
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
|
||||
if normalized.startswith("\\\\"):
|
||||
@@ -681,24 +795,33 @@ def get_chat_sessions():
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
# 先查出最近活跃的会话,再为每个会话回溯最近一条非空 query 作为标题。
|
||||
# 这样本地表单/确认等“无 query 的助手消息”不会把原始用户问题覆盖成 New Chat。
|
||||
session_rows = db.session.query(ChatSession).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
|
||||
|
||||
sessions = [_serialize_session(item) for item in session_rows]
|
||||
session_ids = {item['conversation_id'] for item in sessions}
|
||||
|
||||
# 兼容旧数据:未迁移到 chat_sessions 的历史记录继续从 chat_logs 聚合出来。
|
||||
subquery = db.session.query(
|
||||
ChatLog.conversation_id,
|
||||
func.max(ChatLog.created_at).label('last_active')
|
||||
).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id
|
||||
).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
ChatLog.session_id.is_(None),
|
||||
ChatLog.conversation_id.isnot(None),
|
||||
ChatLog.conversation_id != '',
|
||||
).group_by(ChatLog.conversation_id).subquery()
|
||||
|
||||
results = db.session.query(
|
||||
|
||||
legacy_rows = db.session.query(
|
||||
subquery.c.conversation_id,
|
||||
subquery.c.last_active,
|
||||
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
||||
|
||||
sessions = []
|
||||
for row in results:
|
||||
if not row.conversation_id:
|
||||
for row in legacy_rows:
|
||||
if not row.conversation_id or row.conversation_id in session_ids:
|
||||
continue
|
||||
latest_query_row = db.session.query(ChatLog.query).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
@@ -709,13 +832,15 @@ def get_chat_sessions():
|
||||
).order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
|
||||
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
|
||||
sessions.append({
|
||||
'id': 0, # 前端需要 id key
|
||||
'id': 0,
|
||||
'conversation_id': row.conversation_id,
|
||||
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
|
||||
'created_at': row.last_active.isoformat()
|
||||
'created_at': row.last_active.isoformat(),
|
||||
'status': 'done',
|
||||
})
|
||||
|
||||
return jsonify(sessions)
|
||||
|
||||
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
|
||||
return jsonify(sessions[:20])
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['DELETE'])
|
||||
@@ -737,8 +862,9 @@ def delete_all_chat_sessions():
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
|
||||
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@@ -754,11 +880,22 @@ def delete_chat_session(conversation_id):
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
chat_logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id
|
||||
).all()
|
||||
session = _get_chat_session(user.id, agent.id, conversation_id)
|
||||
if session:
|
||||
chat_logs = db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
or_(
|
||||
ChatLog.session_id == session.session_id,
|
||||
ChatLog.conversation_id == session.external_conversation_id,
|
||||
)
|
||||
).all()
|
||||
else:
|
||||
chat_logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id
|
||||
).all()
|
||||
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
if chat_log_ids:
|
||||
@@ -766,8 +903,10 @@ def delete_chat_session(conversation_id):
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
|
||||
if session:
|
||||
db.session.delete(session)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@@ -781,9 +920,17 @@ def get_chat_messages():
|
||||
if not conversation_id:
|
||||
return jsonify([])
|
||||
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
conversation_id=conversation_id
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
|
||||
if session:
|
||||
logs = db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == g.current_user.id,
|
||||
ChatLog.agent_id == g.current_agent.id,
|
||||
ChatLog.session_id == session.session_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
else:
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
conversation_id=conversation_id
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
for log in logs:
|
||||
@@ -820,19 +967,27 @@ def save_local_message():
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
data = request.get_json() or {}
|
||||
conversation_id = data.get('conversation_id')
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
|
||||
if not conversation_id:
|
||||
import uuid
|
||||
conversation_id = str(uuid.uuid4())
|
||||
|
||||
|
||||
if not message_type:
|
||||
return jsonify({'error': 'type is required'}), 400
|
||||
|
||||
title = user_query or content
|
||||
external_conversation_id = conversation_id if conversation_id and _get_chat_session(user.id, agent.id, conversation_id) is None else None
|
||||
session = _ensure_chat_session(
|
||||
user.id,
|
||||
agent.id,
|
||||
conversation_id or None,
|
||||
title=title,
|
||||
status='done',
|
||||
external_conversation_id=external_conversation_id,
|
||||
)
|
||||
conversation_id = session.session_id
|
||||
|
||||
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
|
||||
# 这样能保证前端表单状态(例如已确认)被持久化
|
||||
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
|
||||
@@ -844,7 +999,7 @@ def save_local_message():
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id,
|
||||
session_id=conversation_id,
|
||||
message_type=message_type
|
||||
).order_by(ChatLog.created_at.desc()).limit(20).all()
|
||||
|
||||
@@ -863,14 +1018,17 @@ def save_local_message():
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id,
|
||||
conversation_id=session.external_conversation_id or conversation_id,
|
||||
session_id=conversation_id,
|
||||
query=user_query,
|
||||
answer=content,
|
||||
message_type=message_type,
|
||||
payload=payload
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
|
||||
session.status = 'done'
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||
|
||||
@@ -894,7 +1052,7 @@ def chat_completions():
|
||||
data = request.get_json() or {}
|
||||
# 提取用户提问内容
|
||||
query = data.get('query')
|
||||
# 提取会话 ID(可选)
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
# 知识库类型
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
@@ -919,31 +1077,132 @@ def chat_completions():
|
||||
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
||||
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
|
||||
from types import SimpleNamespace
|
||||
agent_proxy = SimpleNamespace(
|
||||
id=agent_id,
|
||||
name=getattr(agent, 'name', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
username=getattr(user, 'username', None),
|
||||
employee_id=getattr(user, 'employee_id', None),
|
||||
real_name=getattr(user, 'real_name', None),
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
|
||||
if PLMOracleService.supports(query, agent):
|
||||
generator = PLMOracleService.stream_chat(query, user, agent, conversation_id)
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
existing_session = _get_chat_session(user_id, agent_id, conversation_id)
|
||||
if existing_session:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running')
|
||||
|
||||
if PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id)
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
generator = Text2SQLService.stream_chat(query, user.id, agent, conversation_id)
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id)
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
generator = DifyService.stream_chat(query, user.id, agent, conversation_id, request_id=request_id)
|
||||
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id)
|
||||
|
||||
def relay_stream():
|
||||
created_event = {
|
||||
'event': 'session_created',
|
||||
'conversation_id': session.session_id,
|
||||
'provider_conversation_id': session.external_conversation_id,
|
||||
'session_status': session.status,
|
||||
}
|
||||
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
|
||||
try:
|
||||
for chunk in generator:
|
||||
if not isinstance(chunk, str) or not chunk.startswith('data: '):
|
||||
yield chunk
|
||||
continue
|
||||
|
||||
raw_payload = chunk[6:].strip()
|
||||
try:
|
||||
event_data = json.loads(raw_payload)
|
||||
except Exception:
|
||||
yield chunk
|
||||
continue
|
||||
|
||||
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
|
||||
event_name = event_data.get('event')
|
||||
should_touch = False
|
||||
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
|
||||
known_provider_conversation_id = provider_conversation_id
|
||||
should_touch = True
|
||||
if event_name == 'message_end':
|
||||
known_status = 'done'
|
||||
should_touch = True
|
||||
elif event_name == 'error':
|
||||
known_status = 'error'
|
||||
should_touch = True
|
||||
|
||||
if should_touch:
|
||||
updated_session = _update_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
session.session_id,
|
||||
status=known_status,
|
||||
external_conversation_id=known_provider_conversation_id,
|
||||
touch=True,
|
||||
)
|
||||
if updated_session:
|
||||
known_status = updated_session.status
|
||||
|
||||
event_data['provider_conversation_id'] = provider_conversation_id
|
||||
event_data['conversation_id'] = session.session_id
|
||||
event_data['session_status'] = known_status
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
return Response(
|
||||
stream_with_context(
|
||||
generator
|
||||
relay_stream()
|
||||
),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
@@ -994,7 +1253,9 @@ def submit_feedback():
|
||||
# 构造查询:限定在当前用户和 Agent 范围内
|
||||
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
|
||||
if conversation_id:
|
||||
chat_logs_query = chat_logs_query.filter_by(conversation_id=conversation_id)
|
||||
chat_logs_query = chat_logs_query.filter(
|
||||
or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id)
|
||||
)
|
||||
|
||||
# 取最新一条对话日志
|
||||
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
|
||||
|
||||
Reference in new issue
Block a user