fix(conflicts): Merge branch 'refator' into dev

This commit is contained in:
sophie committed 2026-06-01 19:37:59 +08:00
commit 7f126cfd52
24 files changed
+2314 -4223

No files matched your search

+108 -279
View File
@@ -1,4 +1,3 @@
"""
backend/app/api/chat.py
文件用途:定义聊天相关 API 路由
@@ -15,7 +14,6 @@ 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, or_
@@ -25,12 +23,9 @@ from app.services.integration_api import IntegrationApiService
from app.decorators import require_agent_permission
from app.models import Agent, ChatLog, ChatSession, Feedback
from app import db
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
chat_bp = Blueprint('chat', __name__)
PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
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()
@@ -145,21 +140,15 @@ def _update_chat_session(
def _normalize_windows_share_path(path_value: str) -> str:
normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
if normalized.startswith("\\\\"):
return "\\\\" + normalized[2:].rstrip("\\")
return normalized.rstrip("\\")
normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
if normalized.startswith('\\\\'):
return '\\\\' + normalized[2:].rstrip('\\')
return normalized.rstrip('\\')
def _is_allowed_share_path(target_url: str) -> bool:
normalized_target = _normalize_windows_share_path(target_url)
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
return bool(
normalized_root
and normalized_target.startswith("\\\\")
and normalized_target.lower().startswith(normalized_root.lower())
)
return bool(normalized_root and normalized_target.startswith('\\\\') and normalized_target.lower().startswith(normalized_root.lower()))
def _is_allowed_preview_url(target_url: str) -> bool:
"""
@@ -173,16 +162,14 @@ def _is_allowed_preview_url(target_url: str) -> bool:
if _is_allowed_share_path(target_url):
return True
parsed = urlparse(target_url)
if parsed.scheme not in ("http", "https"):
if parsed.scheme not in ('http', 'https'):
return False
host = (parsed.hostname or "").strip().lower()
host = (parsed.hostname or '').strip().lower()
if not host:
return False
# 显式放行配置中的集成服务主机。
integration_base = (IntegrationApiService.get_base_url() or "").strip()
integration_base = (IntegrationApiService.get_base_url() or '').strip()
if integration_base:
integration_host = (urlparse(integration_base).hostname or "").strip().lower()
integration_host = (urlparse(integration_base).hostname or '').strip().lower()
if integration_host and host == integration_host:
return True
@@ -194,7 +181,6 @@ def _is_allowed_preview_url(target_url: str) -> bool:
if host in ("localhost", "127.0.0.1", "::1"):
return True
try:
ip = ipaddress.ip_address(host)
return ip.is_private or ip.is_loopback
@@ -204,8 +190,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
except Exception:
return False
def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024 * 1024):
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
"""
从上游文件 URL 拉取二进制内容(供预览接口复用)。
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
@@ -217,26 +202,23 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
import time
import sqlalchemy as sa
from urllib.parse import parse_qs
if _is_allowed_share_path(file_url):
normalized_path = _normalize_windows_share_path(file_url)
try:
if not os.path.isfile(normalized_path):
return None, None, ('source file not found', 404)
return (None, None, ('source file not found', 404))
file_size = os.path.getsize(normalized_path)
if max_size is not None and file_size > max_size:
return None, None, ('file too large for online preview', 413)
return (None, None, ('file too large for online preview', 413))
with open(normalized_path, 'rb') as fh:
content = fh.read()
except OSError as exc:
current_app.logger.warning("[file-preview] failed to read share path %s: %s", normalized_path, exc)
return None, None, ('failed to read source file', 502)
current_app.logger.warning('[file-preview] failed to read share path %s: %s', normalized_path, exc)
return (None, None, ('failed to read source file', 502))
guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower()
if _extract_placeholder_text(content):
guessed_type = 'text/plain; charset=utf-8'
return content, guessed_type, None
return (content, guessed_type, None)
headers = {}
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
@@ -258,28 +240,24 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
except Exception:
pass
if not dataset_id or not remote_document_id:
try:
stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url")
stmt = sa.text('CAST(retriever_resources AS TEXT) LIKE :url')
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
if log and log.retriever_resources:
for r in log.retriever_resources:
source_url = str(r.get('source_download_url') or '')
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip()
remote_document_id = remote_document_id or str(
r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or ''
).strip()
remote_document_id = remote_document_id or str(r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '').strip()
if dataset_id and remote_document_id:
break
except Exception as e:
current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e)
current_app.logger.warning('[file-preview] failed to find IDs in ChatLog: %s', e)
if dataset_id and remote_document_id:
new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if new_info and new_info.get('source_download_url'):
current_app.logger.info("[file-preview] refreshed integration url for dataset=%s doc=%s", dataset_id, remote_document_id)
current_app.logger.info('[file-preview] refreshed integration url for dataset=%s doc=%s', dataset_id, remote_document_id)
return new_info['source_download_url']
return raw_url
@@ -327,8 +305,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
if 'unauthorized' in body or '"error"' in body:
return True
return False
if base_url and file_url.startswith(base_url) and 'token=' in file_url:
if base_url and file_url.startswith(base_url) and ('token=' in file_url):
try:
parsed = urlparse(file_url)
qs = parse_qs(parsed.query)
@@ -343,18 +320,14 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
if exp and exp < time.time() + 300:
file_url = _resolve_latest_integration_url(file_url)
except Exception as e:
current_app.logger.warning("[file-preview] failed to refresh expired integration token: %s", e)
current_app.logger.warning('[file-preview] failed to refresh expired integration token: %s', e)
headers = _build_headers(file_url)
try:
upstream = requests.get(file_url, headers=headers, timeout=(5, 20))
except requests.RequestException as e:
current_app.logger.warning("[file-preview] upstream request failed: %s", e)
return None, None, ('failed to fetch source file', 502)
# 某些旧历史记录中的 source_download_url 已过期,但上游可能返回 200 + JSON 错误体。
# 这里统一视为“坏链接”,刷新最新下载地址后重试一次。
if base_url and file_url.startswith(base_url) and 'token=' in file_url and _should_refresh_from_response(upstream):
current_app.logger.warning('[file-preview] upstream request failed: %s', e)
return (None, None, ('failed to fetch source file', 502))
if base_url and file_url.startswith(base_url) and ('token=' in file_url) and _should_refresh_from_response(upstream):
refreshed_url = _resolve_latest_integration_url(file_url)
if refreshed_url != file_url:
headers = _build_headers(refreshed_url)
@@ -362,24 +335,21 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20))
file_url = refreshed_url
except requests.RequestException as e:
current_app.logger.warning("[file-preview] refreshed upstream request failed: %s", e)
return None, None, ('failed to fetch source file', 502)
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
return (None, None, ('failed to fetch source file', 502))
if upstream.status_code != 200:
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b''
if max_size is not None and len(content) > max_size:
return None, None, ('file too large for online preview', 413)
return (None, None, ('file too large for online preview', 413))
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
if content_type == 'application/json':
body = content[:512].decode('utf-8', errors='ignore')
current_app.logger.warning("[file-preview] upstream returned json instead of binary url=%s body=%s", file_url, body)
return None, None, ('upstream returned invalid preview payload', 502)
return content, content_type, None
current_app.logger.warning('[file-preview] upstream returned json instead of binary url=%s body=%s', file_url, body)
return (None, None, ('upstream returned invalid preview payload', 502))
return (content, content_type, None)
def _extract_placeholder_text(content: bytes) -> str:
sample = content[:2048]
@@ -394,7 +364,7 @@ def _extract_placeholder_text(content: bytes) -> str:
if not lines:
continue
first_line = lines[0][:160]
if any(token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密')):
if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))):
return first_line
return ''
@@ -473,23 +443,11 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
input_path = os.path.join(temp_dir, f"input.{ext}")
with open(input_path, 'wb') as f:
f.write(content)
commands = [
'soffice',
'libreoffice',
r'C:\Program Files\LibreOffice\program\soffice.exe',
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'
]
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
success = False
for cmd in commands:
try:
process = subprocess.run(
[cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=60
)
process = subprocess.run([cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
if process.returncode == 0:
success = True
break
@@ -497,8 +455,6 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}")
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
# 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office
if not success and os.name == 'nt':
app = None
doc_obj = None
@@ -507,8 +463,7 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
import win32com.client
import pythoncom
pythoncom.CoInitialize()
output_path = os.path.join(temp_dir, "input.pdf")
output_path = os.path.join(temp_dir, 'input.pdf')
if ext in ('doc', 'docx'):
try:
from pathlib import Path
@@ -548,12 +503,11 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
except Exception:
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
success = True
elif ext in ('ppt', 'pptx'):
try:
app = win32com.client.Dispatch("KWPP.Application") # 尝试 WPS PPT
app = win32com.client.Dispatch('KWPP.Application')
except Exception:
app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT
app = win32com.client.Dispatch('PowerPoint.Application')
app.Visible = False
try:
app.DisplayAlerts = False
@@ -562,19 +516,18 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False)
doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
success = True
elif ext in ('xls', 'xlsx'):
try:
app = win32com.client.Dispatch("KET.Application") # 尝试 WPS Excel
app = win32com.client.Dispatch('KET.Application')
except Exception:
app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel
app = win32com.client.Dispatch('Excel.Application')
app.Visible = False
app.DisplayAlerts = False
doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True)
doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
success = True
except ImportError:
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.")
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Office COM API.')
except Exception as e:
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
finally:
@@ -595,9 +548,8 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
pass
if not success:
raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office")
output_path = os.path.join(temp_dir, "input.pdf")
raise Exception('Failed to convert document to PDF using LibreOffice or WPS/MS Office')
output_path = os.path.join(temp_dir, 'input.pdf')
if os.path.exists(output_path):
with open(output_path, 'rb') as f:
return f.read()
@@ -614,37 +566,22 @@ def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
normalized_ext = (ext or '').strip().lower()
if normalized_ext != 'xls':
return content
with tempfile.TemporaryDirectory() as temp_dir:
input_path = os.path.join(temp_dir, "input.xls")
output_path = os.path.join(temp_dir, "input.xlsx")
input_path = os.path.join(temp_dir, 'input.xls')
output_path = os.path.join(temp_dir, 'input.xlsx')
with open(input_path, 'wb') as f:
f.write(content)
commands = [
'soffice',
'libreoffice',
r'C:\Program Files\LibreOffice\program\soffice.exe',
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'
]
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
errors = []
for cmd in commands:
try:
process = subprocess.run(
[cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=60
)
process = subprocess.run([cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
except (FileNotFoundError, subprocess.TimeoutExpired) as e:
errors.append(f"{cmd}: {e}")
errors.append(f'{cmd}: {e}')
continue
if process.returncode == 0 and os.path.exists(output_path):
with open(output_path, 'rb') as f:
return f.read()
stderr = process.stderr.decode('utf-8', errors='ignore').strip()
errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}")
@@ -670,33 +607,31 @@ def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool
"""
if os.name != 'nt':
return False
try:
import pythoncom
import win32com.client
except ImportError:
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.")
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.')
return False
app = None
workbook = None
pythoncom.CoInitialize()
try:
try:
app = win32com.client.Dispatch("KET.Application")
app = win32com.client.Dispatch('KET.Application')
except Exception:
app = win32com.client.Dispatch("Excel.Application")
app = win32com.client.Dispatch('Excel.Application')
app.Visible = False
app.DisplayAlerts = False
workbook = app.Workbooks.Open(os.path.abspath(input_path))
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51) # 51 = xlOpenXMLWorkbook (.xlsx)
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51)
workbook.Close(False)
workbook = None
app.Quit()
app = None
return os.path.exists(output_path)
except Exception as exc:
current_app.logger.warning("WPS/MS Excel conversion failed for xls preview: %s", exc)
current_app.logger.warning('WPS/MS Excel conversion failed for xls preview: %s', exc)
return False
finally:
try:
@@ -714,7 +649,6 @@ def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool
except Exception:
pass
def _detect_excel_format(content: bytes, ext: str) -> str:
"""
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
@@ -725,18 +659,16 @@ def _detect_excel_format(content: bytes, ext: str) -> str:
head = content[:8] if content else b''
if head.startswith(b'PK\x03\x04'):
return 'xlsx'
if head.startswith(b'\xD0\xCF\x11\xE0'):
if head.startswith(b'\xd0\xcf\x11\xe0'):
return 'xls'
return normalized_ext
def _load_excel_workbook(content: bytes, ext: str):
normalized_ext = _detect_excel_format(content, ext)
if normalized_ext == 'xls':
content = _convert_excel_to_xlsx(content, 'xls')
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
@chat_bp.route('/oa/employees', methods=['GET'])
@require_agent_permission
def get_oa_employees():
@@ -750,15 +682,13 @@ def get_oa_employees():
except ValueError:
page = 1
page_size = 20
try:
from app.services.oa_sqlserver import OASQLServerService
result = OASQLServerService.search_employees(keyword, page, page_size)
return jsonify(result)
except Exception as e:
current_app.logger.error(f"[OA-Employees] Query failed: {e}")
return jsonify({'error': str(e)}), 500
current_app.logger.error(f'[OA-Employees] Query failed: {e}')
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
@chat_bp.route('/oa/resolve-names', methods=['GET'])
@require_agent_permission
@@ -779,10 +709,9 @@ def resolve_oa_names():
if sid:
result[f'sub_{sid}'] = OASQLServerService.get_subcompany_name(sid)
except Exception as e:
current_app.logger.error(f"[OA-ResolveNames] Query failed: {e}")
current_app.logger.error(f'[OA-ResolveNames] Query failed: {e}')
return jsonify(result)
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
def get_chat_sessions():
@@ -791,9 +720,8 @@ def get_chat_sessions():
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
session_rows = db.session.query(ChatSession).filter_by(
user_id=user.id,
@@ -823,13 +751,7 @@ def get_chat_sessions():
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,
ChatLog.agent_id == agent.id,
ChatLog.conversation_id == row.conversation_id,
ChatLog.query.isnot(None),
ChatLog.query != '',
).order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
latest_query_row = db.session.query(ChatLog.query).filter(ChatLog.user_id == user.id, ChatLog.agent_id == agent.id, ChatLog.conversation_id == row.conversation_id, ChatLog.query.isnot(None), ChatLog.query != '').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,
@@ -842,7 +764,6 @@ def get_chat_sessions():
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
return jsonify(sessions[:20])
@chat_bp.route('/sessions', methods=['DELETE'])
@require_agent_permission
def delete_all_chat_sessions():
@@ -851,10 +772,8 @@ def delete_all_chat_sessions():
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
chat_log_ids = [log.id for log in chat_logs]
if chat_log_ids:
@@ -867,7 +786,6 @@ def delete_all_chat_sessions():
return jsonify({'status': 'ok'})
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
@require_agent_permission
def delete_chat_session(conversation_id):
@@ -876,9 +794,8 @@ def delete_chat_session(conversation_id):
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
session = _get_chat_session(user.id, agent.id, conversation_id)
if session:
@@ -909,7 +826,6 @@ def delete_chat_session(conversation_id):
return jsonify({'status': 'ok'})
@chat_bp.route('/messages', methods=['GET'])
@require_agent_permission
def get_chat_messages():
@@ -936,24 +852,14 @@ def get_chat_messages():
for log in logs:
if log.query:
messages.append({'role': 'user', 'content': log.query})
assistant_msg = {
'role': 'assistant',
'content': log.answer,
'chat_log_id': log.id,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or []
}
assistant_msg = {'role': 'assistant', 'content': log.answer, 'chat_log_id': log.id, 'retriever_resources': log.retriever_resources or [], 'attribution_parts': log.attribution_parts or []}
if log.message_type:
assistant_msg['type'] = log.message_type
if log.payload:
assistant_msg['payload'] = log.payload
messages.append(assistant_msg)
return jsonify(messages)
@chat_bp.route('/messages/local', methods=['POST'])
@require_agent_permission
def save_local_message():
@@ -962,10 +868,8 @@ def save_local_message():
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
data = request.get_json() or {}
conversation_id = (data.get('conversation_id') or '').strip()
message_type = data.get('type')
@@ -974,7 +878,7 @@ def save_local_message():
user_query = data.get('query', '')
if not message_type:
return jsonify({'error': 'type is required'}), 400
raise ValidationError('type is required')
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
@@ -991,7 +895,6 @@ def save_local_message():
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
# 这样能保证前端表单状态(例如已确认)被持久化
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
chat_log = None
if local_id:
# 在 payload 中查找是否已存在相同 formId 的同类型消息
@@ -1004,15 +907,14 @@ def save_local_message():
).order_by(ChatLog.created_at.desc()).limit(20).all()
for log in logs:
if log.payload and isinstance(log.payload, dict) and log.payload.get('formId') == local_id:
if log.payload and isinstance(log.payload, dict) and (log.payload.get('formId') == local_id):
chat_log = log
break
if chat_log:
chat_log.content = content
chat_log.answer = content
chat_log.payload = payload
if user_query and not chat_log.query:
if user_query and (not chat_log.query):
chat_log.query = user_query
else:
chat_log = ChatLog(
@@ -1032,7 +934,6 @@ def save_local_message():
db.session.commit()
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
@chat_bp.route('/completions', methods=['POST'])
@require_agent_permission
def chat_completions():
@@ -1048,34 +949,18 @@ def chat_completions():
返回值:
Flask Response 对象,mimetype=text/event-stream
"""
# 解析 JSON 请求体
data = request.get_json() or {}
# 提取用户提问内容
query = data.get('query')
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
# 知识库类型
kb_type = data.get('kb_type', '企业知识库')
request_id = uuid.uuid4().hex[:12]
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
current_app.logger.info(
"[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
request_id,
getattr(user, 'id', None),
getattr(agent, 'id', None),
len(query or ''),
conversation_id,
kb_type
)
# 安全兜底:如果装饰器未正确注入,返回错误
current_app.logger.info('[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s', request_id, getattr(user, 'id', None), getattr(agent, 'id', None), len(query or ''), conversation_id, kb_type)
if user is None or agent is None:
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
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
user_id = getattr(user, 'id', None)
agent_id = getattr(agent, 'id', None)
@@ -1127,14 +1012,12 @@ def chat_completions():
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_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
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_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
@@ -1230,27 +1113,20 @@ def submit_feedback():
score = data.get('score')
comment = data.get('comment') or ''
conversation_id = data.get('conversation_id')
if not current_app.config.get('FEEDBACK_ENABLED', True):
return jsonify({'error': 'feedback is disabled'}), 403
raise ForbiddenError('feedback is disabled')
if score is None:
return jsonify({'error': 'score is required'}), 400
raise ValidationError('score is required')
try:
score_value = int(score)
except (TypeError, ValueError):
return jsonify({'error': 'score must be an integer'}), 400
raise ValidationError('score must be an integer')
if score_value < 1 or score_value > 5:
return jsonify({'error': 'score must be between 1 and 5'}), 400
raise ValidationError('score must be between 1 and 5')
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing user or agent context'}), 500
# 构造查询:限定在当前用户和 Agent 范围内
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
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(
@@ -1260,24 +1136,16 @@ def submit_feedback():
# 取最新一条对话日志
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
if not chat_log:
return jsonify({'error': 'ChatLog not found'}), 404
# 如果已存在反馈,则更新;否则新建
raise NotFoundError('ChatLog not found')
if chat_log.feedback:
chat_log.feedback.score = score_value
chat_log.feedback.comment = comment
else:
fb = Feedback(
chat_log_id=chat_log.id,
score=score_value,
comment=comment,
)
fb = Feedback(chat_log_id=chat_log.id, score=score_value, comment=comment)
db.session.add(fb)
db.session.commit()
return jsonify({'status': 'ok'})
@chat_bp.route('/source-file', methods=['GET'])
@require_agent_permission
def resolve_source_file():
@@ -1287,18 +1155,11 @@ def resolve_source_file():
dataset_id = (request.args.get('dataset_id') or '').strip()
remote_document_id = (request.args.get('remote_document_id') or '').strip()
if not dataset_id or not remote_document_id:
current_app.logger.warning(
"[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s",
dataset_id,
bool(remote_document_id),
(remote_document_id[:8] + "...") if remote_document_id else "",
dict(request.args),
)
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
current_app.logger.warning('[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s', dataset_id, bool(remote_document_id), remote_document_id[:8] + '...' if remote_document_id else '', dict(request.args))
raise ValidationError('dataset_id and remote_document_id are required')
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if not payload:
return jsonify({'error': 'source file mapping not found'}), 404
raise NotFoundError('source file mapping not found')
source_ext = str(payload.get('source_ext') or '').strip().lower()
source_download_url = payload.get('source_download_url')
@@ -1325,11 +1186,11 @@ def source_file_text():
dataset_id = (request.args.get('dataset_id') or '').strip()
remote_document_id = (request.args.get('remote_document_id') or '').strip()
if not dataset_id or not remote_document_id:
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
raise ValidationError('dataset_id and remote_document_id are required')
text = _fetch_dify_text_document(dataset_id, remote_document_id)
if not text:
return jsonify({'error': 'failed to resolve text source file'}), 404
raise NotFoundError('failed to resolve text source file')
filename = f'{remote_document_id}.txt'
return Response(
@@ -1354,31 +1215,29 @@ def preview_excel():
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
return jsonify({'error': 'url is required'}), 400
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
return jsonify({'error': 'url is not allowed for preview'}), 403
raise ForbiddenError('url is not allowed for preview')
parsed = urlparse(file_url)
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext
if ext and ext not in ('xlsx', 'xls'):
raise_for_status(f'unsupported file extension: {ext}', 415)
try:
limit = int(request.args.get('limit', 100))
except ValueError:
limit = 100
limit = max(1, min(limit, 300))
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
if err:
msg, code = err
return jsonify({'error': msg}), code
raise_for_status(msg, code)
detected_ext = _detect_excel_format(content or b'', ext)
if detected_ext not in ('xlsx', 'xls'):
return jsonify({'error': f'unsupported file extension: {ext or detected_ext or "unknown"}'}), 415
raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415)
try:
wb = _load_excel_workbook(content, detected_ext)
@@ -1392,23 +1251,15 @@ def preview_excel():
file_url,
e,
)
payload = {'error': 'failed to parse excel file'}
details: dict = {}
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
payload.update({
'detail': str(e),
'ext': ext,
'detected_ext': detected_ext,
'size': len(content or b''),
})
return jsonify(payload), 422
details = {'detail': str(e), 'ext': ext, 'detected_ext': detected_ext, 'size': len(content or b'')}
raise AppError(code='VALIDATION.UNPROCESSABLE', message='failed to parse excel file', http_status=422, details=details)
if not wb.sheetnames:
return jsonify({'error': 'workbook has no sheets'}), 422
raise_for_status('workbook has no sheets', 422)
requested_sheet = (request.args.get('sheet') or '').strip()
sheet_name = requested_sheet if requested_sheet in wb.sheetnames else wb.sheetnames[0]
ws = wb[sheet_name]
rows = []
for row in ws.iter_rows(values_only=True):
normalized = []
@@ -1422,23 +1273,12 @@ def preview_excel():
rows.append(normalized)
if len(rows) >= limit:
break
# 统一列宽,保证前端表格渲染稳定。
max_cols = max((len(r) for r in rows), default=0)
for r in rows:
if len(r) < max_cols:
r.extend([''] * (max_cols - len(r)))
columns = [f'COL_{i + 1}' for i in range(max_cols)]
return jsonify({
'sheet_name': sheet_name,
'sheets': wb.sheetnames,
'columns': columns,
'rows': rows,
'limit': limit,
'truncated': len(rows) >= limit,
})
return jsonify({'sheet_name': sheet_name, 'sheets': wb.sheetnames, 'columns': columns, 'rows': rows, 'limit': limit, 'truncated': len(rows) >= limit})
@chat_bp.route('/preview-text', methods=['GET'])
@require_agent_permission
@@ -1449,10 +1289,9 @@ def preview_text():
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
return jsonify({'error': 'url is required'}), 400
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
return jsonify({'error': 'url is not allowed for preview'}), 403
raise ForbiddenError('url is not allowed for preview')
parsed = urlparse(file_url)
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
@@ -1461,15 +1300,12 @@ def preview_text():
ext = explicit_ext or url_path_ext or name_ext
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
if ext and ext not in allowed:
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
raise_for_status(f'unsupported text extension: {ext}', 415)
max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
if err:
msg, code = err
return jsonify({'error': msg}), code
# 尝试多编码解码,提升兼容性。
raise_for_status(msg, code)
text = None
for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
try:
@@ -1478,14 +1314,8 @@ def preview_text():
except Exception:
continue
if text is None:
return jsonify({'error': 'failed to decode text file'}), 422
return jsonify({
'content': text,
'content_type': content_type or 'text/plain',
'ext': ext,
})
raise_for_status('failed to decode text file', 422)
return jsonify({'content': text, 'content_type': content_type or 'text/plain', 'ext': ext})
def _guess_ext_from_content(content: bytes, default_ext: str) -> str:
"""
@@ -1540,10 +1370,9 @@ def preview_file_raw():
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
return jsonify({'error': 'url is required'}), 400
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
return jsonify({'error': 'url is not allowed for preview'}), 403
raise ForbiddenError('url is not allowed for preview')
parsed = urlparse(file_url)
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
@@ -1555,7 +1384,7 @@ def preview_file_raw():
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
if err:
msg, code = err
return jsonify({'error': msg}), code
raise_for_status(msg, code)
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
real_ext = _guess_ext_from_content(content, ext)
@@ -1589,7 +1418,11 @@ def preview_file_raw():
content_type = 'text/plain; charset=utf-8'
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
else:
return jsonify({'error': 'failed to convert office file for preview'}), 422
raise AppError(
code='VALIDATION.UNPROCESSABLE',
message='failed to convert office file for preview',
http_status=422,
)
fallback_types = {
'pdf': 'application/pdf',
@@ -1610,18 +1443,14 @@ def preview_file_raw():
content = placeholder_text.encode('utf-8')
content_type = 'text/plain; charset=utf-8'
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
from urllib.parse import quote
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
filename = (request.args.get('name') or '').strip() or f"preview.{ext or 'bin'}"
encoded_filename = quote(filename)
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f'preview.{ext or "bin"}'
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f"preview.{ext or 'bin'}"
disposition_type = 'attachment' if is_download else 'inline'
resp = Response(content, status=200, mimetype=mime)
resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
resp.headers['Content-Disposition'] = f"""{disposition_type}; filename="{ascii_filename}"; filename*=UTF-8''{encoded_filename}"""
resp.headers['Cache-Control'] = 'no-store'
resp.headers['X-Preview-Actual-Ext'] = ext or ''
resp.headers['X-Preview-Original-Ext'] = original_ext or ''