Files
syops/backend/app/api/chat.py
T

2292 lines
95 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/api/chat.py
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
"""
import io
import ipaddress
import mimetypes
import ntpath
import posixpath
import tempfile
import os
import re
import subprocess
import uuid
import json
import time
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_, exists, and_
from openpyxl import load_workbook
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
from app.services.dify import DifyService
from app.core.config.settings import Config
from app.services.integration_api import IntegrationApiService
from app.core.decorators import require_agent_permission
from app.models import Agent, ChatLog, ChatSession, Feedback
from app import db
from app.core.errors import (
AppError,
ConflictError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
raise_for_status,
)
chat_bp = Blueprint('chat', __name__)
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
CHAT_USER_ATTACHMENT_LIMIT = 20
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
def _normalize_user_attachments(value) -> list[dict]:
"""
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
Args:
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
Returns:
可安全写入 JSON 的附件快照列表;非法项目被忽略。
"""
if not isinstance(value, list):
return []
normalized: list[dict] = []
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
if not isinstance(item, dict):
continue
raw_name = str(item.get('name') or '')
basename = re.split(r'[\\/]+', raw_name)[-1]
name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255]
attachment_type = str(item.get('type') or '').strip().lower()
source = str(item.get('source') or '').strip().lower()
if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES:
continue
snapshot = {
'name': name,
'type': attachment_type,
'source': source,
}
extension = str(item.get('extension') or '').strip().lower()
if re.fullmatch(r'[a-z0-9]{1,16}', extension):
snapshot['extension'] = extension
try:
size = int(item.get('size')) if item.get('size') is not None else None
except (TypeError, ValueError):
size = None
if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE:
snapshot['size'] = size
normalized.append(snapshot)
return normalized
def _merge_user_attachments_from_terminal_event(
event_data: dict,
*,
user_id: int,
agent_id: int,
session_id: str,
user_attachments: list[dict],
) -> bool:
"""
在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。
Args:
event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
session_id: 当前 HXOPS 本地会话 ID。
user_attachments: 已完成白名单校验的附件快照。
Returns:
找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。
"""
if not user_attachments:
return False
try:
chat_log_id = int(event_data.get('chat_log_id') or 0)
except (TypeError, ValueError):
return False
if chat_log_id <= 0:
return False
from app.services.chat.log_service import merge_chat_log_payload
return merge_chat_log_payload(
chat_log_id=chat_log_id,
user_id=int(user_id or 0),
agent_id=int(agent_id or 0),
session_id=session_id,
payload_patch={'user_attachments': user_attachments},
)
def _build_chat_adapter_hints(
*,
shipping_task_id: str | None = None,
shipping_batch_no: str | None = None,
shipping_intake_nos: list[str] | None = None,
) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
batch_no = str(shipping_batch_no or '').strip()
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
if not task_id and not batch_no and not intake_nos:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
'intake_nos': intake_nos,
'capability': 'order_extraction' if intake_nos else None,
'contract_version': 'shipping-order-extraction-v1' if intake_nos else None,
}
}
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
"""
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
核心逻辑:
- 仅对“固资管理”Agent 生效;
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
"""
from app.services.text2sql import Text2SQLService
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
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 _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
"""
将内部 Agent 编排提示转换成业务用户可见话术。
Args:
text: chat_logs.query 中保存的用户侧文本。
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
Returns:
可直接展示在聊天历史里的用户问题。
"""
value = str(text or '').strip()
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
return value
import re
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
task_no = task_match.group(1).upper() if task_match else ''
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
return f'继续处理当前发货任务 {task_no}'.strip()
return value
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 _chat_logs_for_session(user_id: int, agent_id: int, session: ChatSession):
match_ids = {session.session_id}
external_id = str(session.external_conversation_id or '').strip()
if external_id:
match_ids.add(external_id)
return db.session.query(ChatLog).filter(
ChatLog.user_id == user_id,
ChatLog.agent_id == agent_id,
or_(
ChatLog.session_id.in_(match_ids),
ChatLog.conversation_id.in_(match_ids),
),
).order_by(ChatLog.created_at.asc()).all()
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_allowed_share_path(path_value: str) -> tuple[str, str]:
"""
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
Returns:
(path_kind, normalized_path)
- path_kind: 'windows' | 'posix' | ''
- normalized_path: 归一化后的绝对路径文本
"""
raw_value = str(path_value or '').strip().strip('"')
if not raw_value:
return ('', '')
if raw_value.startswith('\\\\'):
normalized = raw_value.replace('/', '\\')
normalized = '\\\\' + normalized[2:].rstrip('\\')
return ('windows', normalized)
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
return ('windows', normalized)
if raw_value.startswith('/'):
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
return ('posix', normalized.rstrip('/'))
return ('', '')
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
if not normalized_target or not normalized_root or target_kind != root_kind:
return False
if target_kind == 'windows':
target_lower = normalized_target.lower()
root_lower = normalized_root.lower()
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
def _is_allowed_share_path(target_url: str) -> bool:
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
if not normalized_target:
return False
history_share_root = ''
history_local_root = ''
if has_request_context():
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
if not history_share_root:
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
if not history_local_root:
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
roots = [
PLM_PREVIEW_SHARE_ROOT,
history_share_root,
history_local_root,
]
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
def _is_allowed_preview_url(target_url: str) -> bool:
"""
预览代理 URL 白名单校验。
仅允许:
1) 配置中的集成服务主机;
2) 本机地址;
3) 私网 IP 或常见内网域名(.local/.lan)。
"""
try:
if _is_allowed_share_path(target_url):
return True
parsed = urlparse(target_url)
if parsed.scheme not in ('http', 'https'):
return False
host = (parsed.hostname or '').strip().lower()
if not host:
return False
integration_base = (IntegrationApiService.get_base_url() or '').strip()
if integration_base:
integration_host = (urlparse(integration_base).hostname or '').strip().lower()
if integration_host and host == integration_host:
return True
# 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP)
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
return True
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
except ValueError:
# 非 IP 主机:仅放行内网风格本地域名。
return host.endswith(".local") or host.endswith(".lan") or host.endswith(".well-trust.com")
except Exception:
return False
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
"""
从上游文件 URL 拉取二进制内容(供预览接口复用)。
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
返回: (content_bytes, content_type, error_tuple)
其中 error_tuple = (message, status_code);成功时为 None。
"""
import base64
import json
import time
import sqlalchemy as sa
from urllib.parse import parse_qs
if _is_allowed_share_path(file_url):
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
try:
if not os.path.isfile(normalized_path):
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))
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))
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)
try:
from app.services.fixed_asset_image import FixedAssetImageService
content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes(
file_url,
max_size=max_size,
)
if content is not None or asset_image_err is not None:
return (content, content_type, asset_image_err)
except Exception as exc:
current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc)
headers = {}
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
def _resolve_latest_integration_url(raw_url: str):
dataset_id = ''
remote_document_id = ''
try:
parsed = urlparse(raw_url)
qs = parse_qs(parsed.query)
token = (qs.get('token') or [''])[0]
if token:
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
dataset_id = str(payload_data.get('dataset_id') or '').strip()
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')
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:
if not isinstance(r, dict):
continue
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]):
resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r)
dataset_id = dataset_id or str(resolved_dataset_id or '').strip()
remote_document_id = remote_document_id or str(resolved_remote_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)
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)
return new_info['source_download_url']
return raw_url
def _build_headers(raw_url: str):
next_headers = {}
is_trusted = False
if base_url and raw_url.startswith(base_url):
is_trusted = True
elif _is_allowed_preview_url(raw_url):
is_trusted = True
else:
try:
parsed = urlparse(raw_url)
host = (parsed.hostname or "").strip().lower()
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
is_trusted = True
if host in ("localhost", "127.0.0.1", "::1"):
is_trusted = True
except Exception:
pass
current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}")
if is_trusted:
if api_key:
next_headers['X-Integration-Key'] = api_key
if has_request_context():
auth_header = (request.headers.get('Authorization') or '').strip()
cookie_header = (request.headers.get('Cookie') or '').strip()
if auth_header:
next_headers['Authorization'] = auth_header
if cookie_header:
next_headers['Cookie'] = cookie_header
return next_headers
def _should_refresh_from_response(resp) -> bool:
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
if resp.status_code == 401:
return True
if resp.status_code in (403, 404) and 'token=' in file_url:
return True
if ctype == 'application/json':
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
if 'unauthorized' in body or '"error"' in body:
return True
return False
def _retry_with_refreshed_url(raw_url: str):
refreshed_url = _resolve_latest_integration_url(raw_url)
if not refreshed_url or refreshed_url == raw_url:
return None, raw_url
retry_headers = _build_headers(refreshed_url)
try:
return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url
except requests.RequestException as e:
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
return None, refreshed_url
if 'token=' in file_url:
try:
parsed = urlparse(file_url)
qs = parse_qs(parsed.query)
token = (qs.get('token') or [''])[0]
if token:
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
exp = payload_data.get('exp', 0)
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)
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))
if 'token=' in file_url and _should_refresh_from_response(upstream):
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
if refreshed_upstream is not None:
upstream = refreshed_upstream
file_url = refreshed_url
if upstream.status_code != 200:
if 'token=' in file_url:
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
if refreshed_upstream is not None:
upstream = refreshed_upstream
file_url = refreshed_url
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
if upstream.status_code == 404:
return None, None, ('source file not found', 404)
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))
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)
def _extract_placeholder_text(content: bytes) -> str:
sample = content[:2048]
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
try:
text = sample.decode(enc).replace('\x00', '').strip()
except Exception:
continue
if not text:
continue
lines = [line.strip() for line in text.splitlines() if line.strip()]
if not lines:
continue
first_line = lines[0][:160]
if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))):
return first_line
return ''
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
"""
对于 Dify 中以 text_model / txt 形式存储的文档,
直接拼接 segments 内容,避免依赖可能失效的 file-preview 签名链接。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
service = KbDifySyncService()
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
upload_info = (
((document_payload.get('data_source_info') or {}).get('upload_file'))
if isinstance(document_payload.get('data_source_info'), dict)
else {}
) or {}
source_ext = str(upload_info.get('extension') or '').strip().lower()
doc_form = str(document_payload.get('doc_form') or '').strip().lower()
mime_type = str(upload_info.get('mime_type') or '').strip().lower()
is_text_doc = (
source_ext in ('txt', 'md', 'markdown', 'csv', 'html', 'htm', 'properties', 'vtt')
or doc_form == 'text_model'
or mime_type.startswith('text/')
)
if not is_text_doc:
return None
segments_payload = service._request(
'GET',
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
)
rows = []
if isinstance(segments_payload, dict):
rows = segments_payload.get('data') or []
elif isinstance(segments_payload, list):
rows = segments_payload
if not isinstance(rows, list) or not rows:
return None
ordered_rows = sorted(
[row for row in rows if isinstance(row, dict)],
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
)
parts: list[str] = []
for row in ordered_rows:
text = str(row.get('content') or '').strip()
if text:
parts.append(text)
return '\n\n'.join(parts).strip() or None
except Exception as e:
current_app.logger.warning(
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
dataset_id,
remote_document_id,
e,
)
return None
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF
"""
import shutil
temp_dir = tempfile.mkdtemp()
try:
input_path = os.path.join(temp_dir, f"input.{ext}")
with open(input_path, 'wb') as f:
f.write(content)
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)
if process.returncode == 0:
success = True
break
else:
current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}")
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
if not success and os.name == 'nt':
app = None
doc_obj = None
pythoncom = None
try:
import win32com.client
import pythoncom
pythoncom.CoInitialize()
output_path = os.path.join(temp_dir, 'input.pdf')
if ext in ('doc', 'docx'):
try:
from pathlib import Path
from edkb_system.skills.word_bridge import convert_with_word
convert_with_word(Path(input_path), Path(output_path), 17)
success = True
except Exception as word_bridge_exc:
current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc)
if not success and ext in ('doc', 'docx'):
try:
# 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS
app = win32com.client.Dispatch("Word.Application")
except Exception:
app = win32com.client.Dispatch("KWPS.Application")
app.Visible = False
app.DisplayAlerts = False
input_abs = os.path.abspath(input_path)
output_abs = os.path.abspath(output_path)
try:
doc_obj = app.Documents.Open(
FileName=input_abs,
ConfirmConversions=False,
ReadOnly=True,
AddToRecentFiles=False,
Visible=False,
NoEncodingDialog=True,
OpenAndRepair=True,
)
except TypeError:
doc_obj = app.Documents.Open(input_abs, ReadOnly=True)
try:
# 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17)
doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF
except Exception:
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
success = True
elif ext in ('ppt', 'pptx'):
try:
app = win32com.client.Dispatch('KWPP.Application')
except Exception:
app = win32com.client.Dispatch('PowerPoint.Application')
app.Visible = False
try:
app.DisplayAlerts = False
except Exception:
pass
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')
except Exception:
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.')
except Exception as e:
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
finally:
if doc_obj is not None:
try:
doc_obj.Close(False)
except Exception:
pass
if app is not None:
try:
app.Quit()
except Exception:
pass
if pythoncom is not None:
try:
pythoncom.CoUninitialize()
except Exception:
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')
if os.path.exists(output_path):
with open(output_path, 'rb') as f:
return f.read()
else:
raise Exception("PDF output not found after conversion")
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。
"""
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')
with open(input_path, 'wb') as f:
f.write(content)
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)
except (FileNotFoundError, subprocess.TimeoutExpired) as 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}'}")
allow_windows_excel_preview = (
os.getenv('ENABLE_WINDOWS_EXCEL_PREVIEW_CONVERSION', '').strip().lower() in ('1', 'true', 'yes', 'on')
)
if allow_windows_excel_preview:
if _convert_excel_via_windows_office(input_path, output_path):
with open(output_path, 'rb') as f:
return f.read()
errors.append("windows-office: failed to convert xls via WPS/MS Excel")
else:
errors.append("windows-office: disabled for preview to avoid interactive Office dialogs")
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool:
"""
在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。
LibreOffice 不存在时,给在线预览提供兜底转换能力。
"""
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.')
return False
app = None
workbook = None
pythoncom.CoInitialize()
try:
try:
app = win32com.client.Dispatch('KET.Application')
except Exception:
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)
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)
return False
finally:
try:
if workbook is not None:
workbook.Close(False)
except Exception:
pass
try:
if app is not None:
app.Quit()
except Exception:
pass
try:
pythoncom.CoUninitialize()
except Exception:
pass
def _detect_excel_format(content: bytes, ext: str) -> str:
"""
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
- OLE 复合文档头: 老式 `.xls`
- ZIP 头: `.xlsx`
"""
normalized_ext = (ext or '').strip().lower()
head = content[:8] if content else b''
if head.startswith(b'PK\x03\x04'):
return 'xlsx'
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():
"""
获取 OA 系统中的员工列表(分页/搜索)
"""
keyword = request.args.get('keyword', '').strip()
try:
page = int(request.args.get('page', 1))
page_size = int(request.args.get('page_size', 20))
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}')
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
@chat_bp.route('/oa/resolve-names', methods=['GET'])
@require_agent_permission
def resolve_oa_names():
dept_ids = request.args.get('department_ids', '').strip()
sub_ids = request.args.get('subcompany_ids', '').strip()
result = {}
try:
from app.services.oa_sqlserver import OASQLServerService
if dept_ids:
for did in dept_ids.split(','):
did = did.strip()
if did:
result[f'dept_{did}'] = OASQLServerService.get_department_name(did)
if sub_ids:
for sid in sub_ids.split(','):
sid = sid.strip()
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}')
return jsonify(result)
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
def get_chat_sessions():
"""
获取当前用户与当前 Agent 的历史会话列表
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
session_rows = db.session.query(ChatSession).filter(
ChatSession.user_id == user.id,
ChatSession.agent_id == agent.id,
or_(
ChatSession.status == 'running',
exists().where(
and_(
ChatLog.session_id == ChatSession.session_id,
ChatLog.user_id == user.id,
ChatLog.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(
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()
legacy_rows = db.session.query(
subquery.c.conversation_id,
subquery.c.last_active,
).order_by(desc(subquery.c.last_active)).limit(20).all()
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()
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
sessions.append({
'id': 0,
'conversation_id': row.conversation_id,
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
'created_at': row.last_active.isoformat(),
'status': 'done',
})
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():
"""
删除当前用户与当前 Agent 的所有历史会话
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
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:
from app.models import GeneralFeedback
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.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
db.session.commit()
return jsonify({'status': 'ok'})
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
@require_agent_permission
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:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
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:
from app.models import GeneralFeedback
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)
if session:
db.session.delete(session)
db.session.commit()
return jsonify({'status': 'ok'})
@chat_bp.route('/messages', methods=['GET'])
@require_agent_permission
def get_chat_messages():
"""
获取指定会话的消息记录
"""
conversation_id = request.args.get('conversation_id')
if not conversation_id:
return jsonify([])
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
if session:
logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session)
else:
logs = db.session.query(ChatLog).filter(
ChatLog.user_id == g.current_user.id,
ChatLog.agent_id == g.current_agent.id,
ChatLog.conversation_id == conversation_id,
).order_by(ChatLog.created_at.asc()).all()
messages = []
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
for log in logs:
raw_payload = log.payload if isinstance(log.payload, dict) else {}
user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments'))
assistant_payload = {
key: value
for key, value in raw_payload.items()
if key != 'user_attachments'
}
if log.query or user_attachments:
user_msg = {'role': 'user', 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code)}
if user_attachments:
user_msg['attachments'] = user_attachments
messages.append(user_msg)
if (
not log.answer
and not log.message_type
and not assistant_payload
):
continue
if (
log.query
and log.answer == log.query
and (not log.message_type or log.message_type == 'text')
and not assistant_payload
):
continue
assistant_msg = {
'role': 'assistant',
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
'chat_log_id': log.id,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or [],
}
if log.run_id:
assistant_msg['run_id'] = log.run_id
if log.message_type:
assistant_msg['type'] = log.message_type
if assistant_payload:
assistant_msg['payload'] = assistant_payload
messages.append(assistant_msg)
return jsonify(messages)
@chat_bp.route('/messages/local', methods=['POST'])
@require_agent_permission
def save_local_message():
"""
保存前端本地生成的聊天记录(如表单、确认弹窗、提交结果等)
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
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()
role = (data.get('role') or 'assistant').strip()
message_type = data.get('type')
content = data.get('content', '')
payload = data.get('payload')
user_query = data.get('query', '')
if role == 'user':
user_query = user_query or content
content = ''
else:
# 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。
user_query = ''
if not message_type:
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
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
chat_log = None
if local_id:
# 在 payload 中查找是否已存在相同 formId 的同类型消息
# SQLite / Postgres 对 JSON 过滤有差异,为了简单,我们可以取出当前会话的所有该类型消息并在内存中匹配
logs = db.session.query(ChatLog).filter_by(
user_id=user.id,
agent_id=agent.id,
session_id=conversation_id,
message_type=message_type
).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):
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):
chat_log.query = user_query
else:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.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})
@chat_bp.route('/query-preview/<int:chat_log_id>', methods=['GET'])
@require_agent_permission
def get_chat_query_preview(chat_log_id: int):
page = request.args.get('page', type=int) or 1
page_size = request.args.get('page_size', type=int) or 100
page = max(1, page)
page_size = max(1, min(200, page_size))
log = db.session.query(ChatLog).filter(
ChatLog.id == chat_log_id,
ChatLog.user_id == getattr(g.current_user, 'id', 0),
ChatLog.agent_id == getattr(g.current_agent, 'id', 0),
).first()
if not log:
raise NotFoundError('query preview not found')
payload = log.payload if isinstance(log.payload, dict) else {}
if payload.get('kind') != 'text2sql_result_preview':
raise ValidationError('current message does not support query preview')
sql = str(payload.get('sql') or '').strip()
query = str(payload.get('query') or log.query or '').strip()
if not sql:
raise ValidationError('query preview sql is missing')
from app.services.text2sql import Text2SQLService
total_count = payload.get('total_count')
try:
total_count = int(total_count) if total_count is not None else None
except (TypeError, ValueError):
total_count = None
columns, rows, resolved_total = Text2SQLService.get_preview_page(
sql=sql,
query=query,
page=page,
page_size=page_size,
agent=g.current_agent,
total_count=total_count,
user_context=Text2SQLService._normalize_user_context(g.current_user),
)
if columns == ["Error"]:
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
total = resolved_total if resolved_total is not None else len(rows)
return jsonify({
'columns': columns,
'rows': [list(row) for row in rows],
'page': page,
'page_size': page_size,
'total': total,
'has_more': page * page_size < total,
'query': query,
})
@chat_bp.route('/asset-history/search', methods=['GET'])
@require_agent_permission
def search_asset_history_files():
"""
检索固定资产履历文件。
用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。
约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。
"""
asset_id = (request.args.get('asset_id') or '').strip()
asset_name = (request.args.get('asset_name') or '').strip()
limit = request.args.get('limit', type=int) or 20
limit = max(1, min(limit, 50))
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
from app.services.fixed_asset_history import FixedAssetHistoryService
if not FixedAssetHistoryService.is_enabled():
raise ServiceUnavailableError('asset history share is not configured')
items = FixedAssetHistoryService.search_history_files(
asset_id=asset_id,
asset_name=asset_name,
limit=limit,
)
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
'total': len(items),
'items': items,
})
@chat_bp.route('/asset-image/resolve', methods=['GET'])
@require_agent_permission
def resolve_asset_image_preview():
"""
解析固定资产图片预览链接。
用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。
约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。
"""
asset_id = (request.args.get('asset_id') or '').strip()
asset_name = (request.args.get('asset_name') or '').strip()
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
from app.services.fixed_asset_image import FixedAssetImageService
result = FixedAssetImageService.resolve_images(
asset_id=asset_id,
asset_name=asset_name,
)
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
'item': result.get('item'),
'items': result.get('items', []),
'total': result.get('total', 0),
})
@chat_bp.route('/completions', methods=['POST'])
@require_agent_permission
def chat_completions():
"""
SSE 流式聊天接口
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
核心逻辑:
1. 从请求体中读取 query / agent_id / conversation_id
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
传入参数:
无(从 request.json 读取)
返回值:
Flask Response 对象,mimetype=text/event-stream
"""
data = request.get_json() or {}
query = data.get('query')
display_query = str(
data.get('display_query') if 'display_query' in data else query or ''
).strip()
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
raw_shipping_intakes = data.get('shipping_intake_nos')
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
raise ValidationError('shipping_intake_nos must be a list')
shipping_intake_nos = sorted({
str(item or '').strip().upper()
for item in (raw_shipping_intakes or [])
if str(item or '').strip()
})
kb_type = data.get('kb_type', '企业知识库')
user_attachments = _normalize_user_attachments(data.get('user_attachments'))
session_title = display_query or (user_attachments[0]['name'] if user_attachments else str(query or '').strip())
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
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)
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))
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
from app.services.agent_registry.resolver import resolve_runtime_provider
if resolve_runtime_provider(agent) == 'iframe':
raise ValidationError('Embedded iframe agents do not support chat completions')
user_id = getattr(user, 'id', None)
agent_id = getattr(agent, 'id', None)
from types import SimpleNamespace
from app.services.agent_directory import serialize_directory_members
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
agent_proxy = SimpleNamespace(
id=agent_id,
name=getattr(agent, 'name', None),
type=getattr(agent, 'type', None),
dify_api_key=getattr(agent, 'dify_api_key', None),
api_base_url=getattr(agent, 'api_base_url', None),
extra_config=getattr(agent, 'extra_config', None) or {},
agent_code=getattr(agent, 'agent_code', None),
runtime_provider=getattr(agent, 'runtime_provider', None),
conversation_mode=getattr(agent, 'conversation_mode', None),
dify_app_type=getattr(agent, 'dify_app_type', None),
capabilities=getattr(agent, 'capabilities', None),
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
handler_config=getattr(agent, 'handler_config', None),
is_aggregate=is_aggregate,
directory_members=directory_members,
)
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),
role=getattr(user, 'role', None),
)
from app.services.dify import DifyService
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=session_title,
status='running',
)
external_conversation_id = session.external_conversation_id
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
current_app.logger.info(
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
request_id,
session.session_id,
external_conversation_id,
query,
)
session.external_conversation_id = None
session.updated_at = datetime.utcnow()
session.last_active_at = datetime.utcnow()
db.session.commit()
external_conversation_id = None
else:
session = _ensure_chat_session(
user_id,
agent_id,
conversation_id,
title=session_title,
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=session_title, status='running')
# [STEP 1] 流式响应可能在原请求 DB Session 清理后才开始迭代;提前快照会话标量,
# 避免 Handler 的事务提交使 ORM 对象过期后触发 DetachedInstanceError。
local_session_id = str(session.session_id)
initial_session_status = str(session.status or 'running')
initial_external_conversation_id = str(external_conversation_id or '').strip() or None
stream_session = SimpleNamespace(session_id=local_session_id)
normalized_files: list[dict] | None = None
if files is not None:
if not isinstance(files, list):
raise ValidationError('files must be a list')
normalized_files = []
for item in files:
if not isinstance(item, dict):
continue
transfer_method = str(item.get('transfer_method') or '').strip()
ftype = str(item.get('type') or '').strip()
if transfer_method not in ('local_file', 'remote_url'):
continue
if ftype not in ('image', 'document', 'audio', 'video', 'custom'):
continue
if transfer_method == 'local_file':
upload_file_id = str(item.get('upload_file_id') or '').strip()
if not upload_file_id:
continue
normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id})
else:
url = str(item.get('url') or '').strip()
if not url:
continue
normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url})
if not normalized_files:
normalized_files = None
from app.services.agent_registry.handlers.base import ChatStreamContext
relay_stream_ctx = ChatStreamContext(
query=query,
display_query=display_query,
user=user_proxy,
agent=agent_proxy,
session=stream_session,
external_conversation_id=initial_external_conversation_id,
request_id=request_id,
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
shipping_intake_nos=shipping_intake_nos,
),
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
kb_type=kb_type,
)
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from app.services.chat.router import try_fast_route
leave_supported = HRLeaveSQLServerService.supports(query)
fast_route = try_fast_route(
user=user_proxy,
agent=agent_proxy,
query=query,
agent_id=agent_id,
session_id=local_session_id,
external_conversation_id=initial_external_conversation_id,
normalized_files=normalized_files,
kb_type=kb_type,
leave_supported=leave_supported,
)
if fast_route is not None:
generator = fast_route.generator
elif leave_supported:
generator = DifyService.stream_chat(
query,
user_proxy.id,
agent_proxy,
initial_external_conversation_id,
request_id=request_id,
session_id=local_session_id,
files=normalized_files,
inputs=build_chat_dify_inputs(
agent_proxy,
session_id=local_session_id,
request_id=request_id,
trigger_source="frontend_chat",
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
shipping_intake_nos=shipping_intake_nos,
),
),
)
else:
from app.services.chat.executors import stream_chat_via_executor
generator = stream_chat_via_executor(relay_stream_ctx)
def relay_stream():
from app.services.chat_perf import chat_perf_enabled
relay_started = time.perf_counter()
relay_first_chunk_at: float | None = None
created_event = {
'event': 'session_created',
'conversation_id': local_session_id,
'provider_conversation_id': initial_external_conversation_id,
'session_status': initial_session_status,
}
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
known_provider_conversation_id = initial_external_conversation_id
known_status = initial_session_status
emitted_handler_state_keys: set[str] = set()
from app.services.chat.stream_relay import (
iter_handler_preface_sse,
iter_handler_terminal_sse,
)
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
yield preface_line
try:
merged_attachment_log_ids: set[int] = set()
for chunk in generator:
if relay_first_chunk_at is None:
relay_first_chunk_at = time.perf_counter()
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')
if event_name in ('error', 'message_end', 'workflow_finished') and user_attachments:
try:
attachment_chat_log_id = int(event_data.get('chat_log_id') or 0)
except (TypeError, ValueError):
attachment_chat_log_id = 0
if attachment_chat_log_id > 0 and attachment_chat_log_id not in merged_attachment_log_ids:
if _merge_user_attachments_from_terminal_event(
event_data,
user_id=user_id,
agent_id=agent_id,
session_id=local_session_id,
user_attachments=user_attachments,
):
merged_attachment_log_ids.add(attachment_chat_log_id)
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 in ('message_end', 'workflow_finished'):
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,
local_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'] = local_session_id
event_data['session_status'] = known_status
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
relay_total_ms = int((time.perf_counter() - relay_started) * 1000)
current_app.logger.info(
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
request_id,
local_session_id,
relay_first_ms,
relay_total_ms,
event_name,
)
event_data['hxops_relay'] = {
'first_chunk_ms': relay_first_ms,
'total_relay_ms': relay_total_ms,
}
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
if event_name in ('error', 'message_end', 'workflow_finished'):
for terminal_line in iter_handler_terminal_sse(
relay_stream_ctx,
event_data,
emitted_keys=emitted_handler_state_keys,
):
yield terminal_line
except Exception as exc:
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id)
payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'}
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
for terminal_line in iter_handler_terminal_sse(
relay_stream_ctx,
payload,
emitted_keys=emitted_handler_state_keys,
):
yield terminal_line
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
stream_with_context(
relay_stream()
),
mimetype='text/event-stream',
headers={
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream; charset=utf-8',
'Connection': 'keep-alive',
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
'X-Accel-Buffering': 'no'
}
)
@chat_bp.route('/files/upload', methods=['POST'])
@require_agent_permission
def upload_chat_file():
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
if str(getattr(agent, 'type', '') or '').strip().lower() != 'api':
raise ValidationError('This agent does not support file upload')
if not getattr(agent, 'dify_api_key', None):
raise ValidationError('This agent does not support file upload')
upload = request.files.get('file')
if not upload:
raise ValidationError('file is required')
from app.services.dify import DifyService
from app.core.config.settings import Config
params = DifyService.get_app_parameters(agent, force_refresh=True)
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {}
filename = str(getattr(upload, 'filename', '') or '').strip()
mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip()
detected_type, ext = DifyService.detect_file_type(filename, mimetype)
file_type = None
normalized_allowed_types = None
normalized_allowed_methods = None
normalized_allowed_exts = None
is_new_schema = False
if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list):
is_new_schema = True
normalized_allowed_types = set(
(
str(v or '').strip().lower()
for v in (file_upload_cfg.get('allowed_file_types') or [])
if str(v or '').strip()
)
)
normalized_allowed_methods = set(
(
str(v or '').strip().lower()
for v in (file_upload_cfg.get('allowed_file_upload_methods') or [])
if str(v or '').strip()
)
)
exts = []
for v in (file_upload_cfg.get('allowed_file_extensions') or []):
s = str(v or '').strip()
if not s:
continue
if s.startswith('.'):
s = s[1:]
s = s.lower().strip()
if s:
exts.append(s)
normalized_allowed_exts = set(exts) if exts else None
if detected_type:
file_type = detected_type
else:
if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)):
file_type = 'custom'
else:
custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None
if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)):
file_type = 'custom'
else:
raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})')
def _effective_type_methods(target_type: str) -> set[str]:
if not isinstance(file_upload_cfg, dict):
return set(normalized_allowed_methods or set())
cfg = file_upload_cfg.get(target_type)
transfer_methods = []
if isinstance(cfg, dict):
transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or []
if isinstance(transfer_methods, str):
transfer_methods = [transfer_methods]
if isinstance(transfer_methods, list) and len(transfer_methods) > 0:
return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip())
return set(normalized_allowed_methods or set())
def _is_type_enabled_in_new_schema(target_type: str) -> bool:
if not (is_new_schema and normalized_allowed_types):
return False
if not isinstance(file_upload_cfg, dict):
return target_type in normalized_allowed_types
cfg = file_upload_cfg.get(target_type)
if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool):
if cfg.get('enabled') is False:
return False
if cfg.get('enabled') is True:
return True
return target_type in normalized_allowed_types
if is_new_schema and normalized_allowed_types:
if not _is_type_enabled_in_new_schema(file_type):
raise ValidationError(f'File type not enabled: {file_type}')
type_methods = _effective_type_methods(file_type)
if 'local_file' not in type_methods:
raise ValidationError('local_file upload is not enabled')
if normalized_allowed_exts:
allowed_for_type = set()
for e in normalized_allowed_exts:
t, _ = DifyService.detect_file_type(f'file.{e}', None)
if t is None:
if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)):
allowed_for_type.add(e)
continue
if t == file_type:
allowed_for_type.add(e)
if allowed_for_type and (not ext or ext not in allowed_for_type):
raise ValidationError(f'Unsupported file extension: .{ext or ""}')
else:
# legacy schema checks
type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None
if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'):
raise ValidationError(f'File type not enabled: {file_type}')
transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or []
if isinstance(transfer_methods, str):
transfer_methods = [transfer_methods]
if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)):
raise ValidationError('local_file upload is not enabled')
def _mb_limit_for_type() -> float | None:
merged = {}
if isinstance(system_params, dict):
merged.update(system_params)
if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict):
merged.update(file_upload_cfg.get('fileUploadConfig') or {})
if file_type == 'image':
return merged.get('image_file_size_limit') or merged.get('file_size_limit')
if file_type == 'audio':
return merged.get('audio_file_size_limit') or merged.get('file_size_limit')
if file_type == 'video':
return merged.get('video_file_size_limit') or merged.get('file_size_limit')
return merged.get('file_size_limit')
size_limit_mb = _mb_limit_for_type()
if size_limit_mb is not None:
try:
import os
stream = getattr(upload, 'stream', None)
if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'):
cur = stream.tell()
stream.seek(0, os.SEEK_END)
size_bytes = stream.tell()
stream.seek(cur)
limit_bytes = int(float(size_limit_mb) * 1024 * 1024)
if size_bytes > limit_bytes:
raise ValidationError(f'File too large (limit {size_limit_mb}MB)')
except ValidationError:
raise
except Exception:
pass
base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE
dify_url = DifyService._build_files_upload_url(base_url)
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
try:
try:
upload.stream.seek(0)
except Exception:
pass
resp = requests.post(
dify_url,
headers=headers,
files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')},
data={'user': str(getattr(user, 'id', 'system'))},
timeout=(5, 300),
)
except requests.RequestException as exc:
raise ServiceUnavailableError(f'Upload failed: {exc}')
if not resp.ok:
body = (resp.text or '')[:1500]
header_snapshot = {}
try:
for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'):
v = resp.headers.get(k) or resp.headers.get(k.title())
if v:
header_snapshot[k] = v
except Exception:
header_snapshot = {}
current_app.logger.warning(
'[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s',
resp.status_code,
dify_url,
header_snapshot,
body,
)
raise AppError(
code='DIFY.UPLOAD_FAILED',
message='Upload failed',
http_status=502,
details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot},
)
data = resp.json() if resp.content else {}
return jsonify({
'id': data.get('id'),
'name': data.get('name') or filename,
'size': data.get('size'),
'extension': data.get('extension') or ext,
'mime_type': data.get('mime_type') or mimetype,
'type': file_type,
})
@chat_bp.route('/feedback', methods=['POST'])
@require_agent_permission
def submit_feedback():
"""
提交对回答的评分与评论
用途:在对话结束后,由前端发送评分(1~5)和文字意见
核心逻辑:
1. 从请求体中读取 score/comment/conversation_id
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
3. 为该 ChatLog 创建或更新 Feedback 记录
"""
data = request.get_json() or {}
score = data.get('score')
comment = data.get('comment') or ''
conversation_id = data.get('conversation_id')
if not current_app.config.get('FEEDBACK_ENABLED', True):
raise ForbiddenError('feedback is disabled')
if score is None:
raise ValidationError('score is required')
try:
score_value = int(score)
except (TypeError, ValueError):
raise ValidationError('score must be an integer')
if score_value < 1 or score_value > 5:
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:
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(
or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id)
)
# 取最新一条对话日志
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
if not chat_log:
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)
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():
"""
Resolve original source download URL by Dify dataset/document IDs.
"""
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))
raise ValidationError('dataset_id and remote_document_id are required')
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if not payload:
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')
return jsonify({
'dataset_id': dataset_id,
'remote_document_id': remote_document_id,
'source_filename': payload.get('source_filename'),
'source_ext': source_ext,
'source_download_url': source_download_url,
'download_url_expires_at': payload.get('download_url_expires_at'),
})
@chat_bp.route('/source-file-text', methods=['GET'])
@require_agent_permission
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:
raise ValidationError('dataset_id and remote_document_id are required')
text = _fetch_dify_text_document(dataset_id, remote_document_id)
if not text:
raise NotFoundError('failed to resolve text source file')
filename = f'{remote_document_id}.txt'
return Response(
text,
status=200,
mimetype='text/plain; charset=utf-8',
headers={
'Content-Disposition': f'inline; filename="{filename}"',
'Cache-Control': 'no-store',
},
)
@chat_bp.route('/preview-excel', methods=['GET'])
@require_agent_permission
def preview_excel():
"""
内网 Excel 预览接口(简版可上线)。
说明:
- xlsx 直接解析;
- xls 先转为 xlsx 后再解析。
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
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
raise_for_status(msg, code)
detected_ext = _detect_excel_format(content or b'', ext)
if detected_ext not in ('xlsx', 'xls'):
raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415)
try:
wb = _load_excel_workbook(content, detected_ext)
except Exception as e:
current_app.logger.warning(
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
ext,
detected_ext,
len(content or b''),
name,
file_url,
e,
)
details: dict = {}
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
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:
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 = []
for cell in row:
if cell is None:
normalized.append('')
elif isinstance(cell, (int, float, bool)):
normalized.append(cell)
else:
normalized.append(str(cell))
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})
@chat_bp.route('/preview-text', methods=['GET'])
@require_agent_permission
def preview_text():
"""
文本类文件预览接口(内网代理)。
支持:md/markdown/txt/csv/vtt/properties/html/htm
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
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()
explicit_ext = (request.args.get('ext') or '').strip().lower()
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:
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
raise_for_status(msg, code)
text = None
for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
try:
text = content.decode(enc)
break
except Exception:
continue
if text is None:
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:
"""
根据文件内容(Magic Bytes)纠正可能的错误扩展名
"""
import io
import zipfile
if not content:
return default_ext
if content.startswith(b'%PDF-'):
return 'pdf'
if content.startswith(b'PK\x03\x04'):
# ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。
try:
with zipfile.ZipFile(io.BytesIO(content)) as zf:
names = {name.lower() for name in zf.namelist()}
if any(name.startswith('word/') for name in names):
return 'docx'
if any(name.startswith('xl/') for name in names):
return 'xlsx'
if any(name.startswith('ppt/') for name in names):
return 'pptx'
except Exception:
pass
if default_ext == 'doc':
return 'docx'
if default_ext == 'xls':
return 'xlsx'
if default_ext == 'ppt':
return 'pptx'
if default_ext in ('docx', 'xlsx', 'pptx'):
return default_ext
return 'docx'
if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'):
# OLE 复合文件,通常是 doc, xls, ppt 等。
if default_ext == 'docx': return 'doc'
if default_ext == 'xlsx': return 'xls'
if default_ext == 'pptx': return 'ppt'
if default_ext in ('doc', 'xls', 'ppt'): return default_ext
return 'doc'
return default_ext
@chat_bp.route('/preview-file-raw', methods=['GET'])
@require_agent_permission
def preview_file_raw():
"""
二进制文件内网代理预览接口。
用途:
- 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址;
- 尽量使用 inline 响应头,避免强制下载。
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
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()
original_ext = url_path_ext or name_ext
ext = original_ext
is_download = request.args.get('download') == '1'
max_size = None if is_download else 15 * 1024 * 1024
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
if err:
msg, code = err
raise_for_status(msg, code)
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
real_ext = _guess_ext_from_content(content, ext)
if real_ext != ext:
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
ext = real_ext
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.{ext}"
elif name:
name = f"{name}.{ext}"
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
# 避免在服务端走旧版转换链路导致长时间卡住。
needs_pdf_conversion = (
request.args.get('download') != '1'
and ext in ('doc', 'ppt', 'pptx')
)
if needs_pdf_conversion:
try:
content = _convert_office_to_pdf(content, ext)
ext = 'pdf'
content_type = 'application/pdf'
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.pdf"
elif name:
name = f"{name}.pdf"
except Exception as e:
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
placeholder_text = _extract_placeholder_text(content)
if placeholder_text:
content = placeholder_text.encode('utf-8')
ext = 'txt'
content_type = 'text/plain; charset=utf-8'
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.txt"
elif name:
name = f"{name}.txt"
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
else:
raise AppError(
code='VALIDATION.UNPROCESSABLE',
message='failed to convert office file for preview',
http_status=422,
)
fallback_types = {
'pdf': 'application/pdf',
'doc': 'application/msword',
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xls': 'application/vnd.ms-excel',
'csv': 'text/csv',
'txt': 'text/plain',
'md': 'text/markdown',
'markdown': 'text/markdown',
'html': 'text/html',
'htm': 'text/html',
}
if ext == 'pdf' and not content.startswith(b'%PDF-'):
placeholder_text = _extract_placeholder_text(content)
if placeholder_text:
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'}"
encoded_filename = quote(filename)
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['Cache-Control'] = 'no-store'
resp.headers['X-Preview-Actual-Ext'] = ext or ''
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
return resp
from app.api.chat_turns import register_chat_turn_routes
register_chat_turn_routes(chat_bp)