Merge branch 'runny&xinxin' into dev

This commit is contained in:
super committed 2026-05-14 10:58:26 +08:00
commit 8d73343bd8
77 files changed
+17955 -274

No files matched your search

+6
View File
@@ -49,6 +49,8 @@ def create_app(config_name='default'):
from app.api.admin import admin_bp
from app.api.agents import agents_bp
from app.api.user import user_bp
from app.api.knowledge_base import knowledge_base_bp
from app.api.integration import integration_bp
# 聊天相关接口
app.register_blueprint(chat_bp, url_prefix='/api/chat')
@@ -58,6 +60,10 @@ def create_app(config_name='default'):
app.register_blueprint(agents_bp, url_prefix='/api/agents')
# 当前用户相关接口(首页、常用问题等)
app.register_blueprint(user_bp, url_prefix='/api/user')
# 知识库/数据清洗模块接口
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
# 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件)
app.register_blueprint(integration_bp, url_prefix='/api/integration')
# Eagerly load persisted runtime settings so the very first request after
# a worker boot already sees the admin-saved configuration (otherwise the
+37 -16
View File
@@ -4,14 +4,25 @@ backend/app/api/agents.py
引用文件:flask, models, decorators
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
"""
from flask import Blueprint, jsonify, g
from app.models import Agent, User
from flask import Blueprint, jsonify
from app import db
from app.decorators import _get_current_user # 内部工具函数
from app.models import Agent, User
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
def _serialize_agent_row(row) -> dict:
return {
'id': row.id,
'name': row.name,
'description': row.description,
'icon_url': row.icon_url,
}
@agents_bp.route('', methods=['GET'])
def list_user_agents():
"""
@@ -23,12 +34,27 @@ def list_user_agents():
# 管理员:返回所有激活的 Agent
if user.role == 'admin':
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
else:
# 普通用户:仅返回多对多关系中已授权的 Agent
agents = [a for a in user.agents if a.is_active]
agent_rows = [
type('AgentRow', (), {
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url,
})()
for a in user.agents
if a.is_active
]
# 序列化为前端所需字段
return jsonify([_serialize_agent_row(row) for row in agent_rows])
@agents_bp.route('/public', methods=['GET'])
def list_public_agents():
@@ -37,17 +63,12 @@ def list_public_agents():
用途:登录页面展示
"""
# 返回所有激活的 Agent,包含基本信息
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
data = [
{
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url,
}
for a in agents
]
return jsonify(data)
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
.filter(Agent.is_active.is_(True))
.order_by(Agent.id.asc())
.all()
)
return jsonify([_serialize_agent_row(row) for row in agent_rows])
+61 -8
View File
@@ -43,7 +43,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
return False
# 显式放行配置中的集成服务主机。
integration_base = (current_app.config.get("INTEGRATION_API_BASE") or "").strip()
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:
@@ -76,8 +76,8 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
from urllib.parse import parse_qs
headers = {}
base_url = current_app.config.get('INTEGRATION_API_BASE', '')
api_key = current_app.config.get('INTEGRATION_API_KEY', '')
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
def _resolve_latest_integration_url(raw_url: str):
dataset_id = ''
@@ -280,6 +280,58 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
raise Exception("PDF output not found after conversion")
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',
r'C:\Program Files\LibreOffice\program\soffice.exe',
r'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}'}")
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
def _load_excel_workbook(content: bytes, ext: str):
normalized_ext = (ext or '').strip().lower()
if normalized_ext == 'xls':
content = _convert_excel_to_xlsx(content, normalized_ext)
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
def get_chat_sessions():
@@ -578,8 +630,8 @@ def preview_excel():
"""
内网 Excel 预览接口(简版可上线)。
说明:
- 当前仅支持 xlsx;
- xls 返回 415,由前端走下载兜底。
- xlsx 直接解析;
- xls 先转为 xlsx 后再解析。
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
@@ -602,13 +654,13 @@ def preview_excel():
limit = 100
limit = max(1, min(limit, 300))
content, _, err = _fetch_preview_source_bytes(file_url)
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
if err:
msg, code = err
return jsonify({'error': msg}), code
try:
wb = load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
wb = _load_excel_workbook(content, ext)
except Exception as e:
current_app.logger.warning("[excel-preview] parse workbook failed: %s", e)
return jsonify({'error': 'failed to parse excel file'}), 422
@@ -673,7 +725,8 @@ def preview_text():
if ext and ext not in allowed:
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
content, content_type, err = _fetch_preview_source_bytes(file_url)
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
+816
View File
@@ -0,0 +1,816 @@
"""
backend/app/api/chat.py
文件用途:定义聊天相关 API 路由
引用文件:flask, services.dify, decorators, models
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
"""
import io
import ipaddress
import tempfile
import os
import subprocess
from urllib.parse import urlparse
import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
from sqlalchemy import func, desc
from openpyxl import load_workbook
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
from app.decorators import require_agent_permission
from app.models import Agent, ChatLog, Feedback
from app import db
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
chat_bp = Blueprint('chat', __name__)
def _is_allowed_preview_url(target_url: str) -> bool:
"""
预览代理 URL 白名单校验。
仅允许:
1) 配置中的集成服务主机;
2) 本机地址;
3) 私网 IP 或常见内网域名(.local/.lan)。
"""
try:
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
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")
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
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:
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()
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 = {}
if base_url and raw_url.startswith(base_url) and api_key:
next_headers['X-Integration-Key'] = api_key
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 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
if base_url and file_url.startswith(base_url) and '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)
# 某些旧历史记录中的 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):
refreshed_url = _resolve_latest_integration_url(file_url)
if refreshed_url != file_url:
headers = _build_headers(refreshed_url)
try:
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)
if upstream.status_code != 200:
return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b''
if 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 _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 将 office 文件转为 PDF
"""
with tempfile.TemporaryDirectory() as temp_dir:
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'
]
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
# 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office
if not success and os.name == 'nt':
try:
import win32com.client
import pythoncom
pythoncom.CoInitialize()
output_path = os.path.join(temp_dir, "input.pdf")
if ext in ('doc', 'docx'):
try:
app = win32com.client.Dispatch("KWPS.Application") # 尝试 WPS Word
except Exception:
app = win32com.client.Dispatch("Word.Application") # 回退 MS Word
app.Visible = False
doc = app.Documents.Open(os.path.abspath(input_path))
doc.SaveAs(os.path.abspath(output_path), FileFormat=17) # 17 = wdFormatPDF
doc.Close()
app.Quit()
success = True
elif ext in ('ppt', 'pptx'):
try:
app = win32com.client.Dispatch("KWPP.Application") # 尝试 WPS PPT
except Exception:
app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT
app.Visible = False
presentation = app.Presentations.Open(os.path.abspath(input_path), WithWindow=False)
presentation.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
presentation.Close()
app.Quit()
success = True
elif ext in ('xls', 'xlsx'):
try:
app = win32com.client.Dispatch("KET.Application") # 尝试 WPS Excel
except Exception:
app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel
app.Visible = False
wb = app.Workbooks.Open(os.path.abspath(input_path))
wb.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
wb.Close(False)
app.Quit()
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}")
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")
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',
r'C:\Program Files\LibreOffice\program\soffice.exe',
r'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}'}")
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
def _load_excel_workbook(content: bytes, ext: str):
normalized_ext = (ext or '').strip().lower()
if normalized_ext == 'xls':
content = _convert_excel_to_xlsx(content, normalized_ext)
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
@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:
return jsonify({'error': 'Missing context'}), 500
# 聚合查询:按 conversation_id 分组,获取最新时间
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
# 更严谨的做法是先查出 conversation_ids,再查详情。
# 这里为了简单,我们假设 query 不为空
# 修正逻辑:先查出最近的 20 个 conversation_id
subquery = db.session.query(
ChatLog.conversation_id,
func.max(ChatLog.created_at).label('last_active')
).filter_by(
user_id=user.id,
agent_id=agent.id
).group_by(ChatLog.conversation_id).subquery()
# 联表查询获取详细信息,按时间倒序
results = db.session.query(
subquery.c.conversation_id,
subquery.c.last_active,
ChatLog.query
).join(
ChatLog,
(ChatLog.conversation_id == subquery.c.conversation_id) &
(ChatLog.created_at == subquery.c.last_active)
).order_by(desc(subquery.c.last_active)).limit(20).all()
sessions = []
for row in results:
if not row.conversation_id:
continue
sessions.append({
'id': 0, # 前端需要 id key
'conversation_id': row.conversation_id,
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
'created_at': row.last_active.isoformat()
})
return jsonify(sessions)
@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:
return jsonify({'error': 'Missing context'}), 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.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:
return jsonify({'error': 'Missing context'}), 500
chat_logs = db.session.query(ChatLog).filter_by(
user_id=user.id,
agent_id=agent.id,
conversation_id=conversation_id
).all()
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.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([])
logs = db.session.query(ChatLog).filter_by(
conversation_id=conversation_id
).order_by(ChatLog.created_at.asc()).all()
messages = []
for log in logs:
messages.append({'role': 'user', 'content': log.query})
messages.append({
'role': 'assistant',
'content': log.answer,
'chat_log_id': log.id,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or []
})
return jsonify(messages)
@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
"""
# 解析 JSON 请求体
data = request.get_json() or {}
# 提取用户提问内容
query = data.get('query')
# 提取会话 ID(可选)
conversation_id = data.get('conversation_id')
# 知识库类型
kb_type = data.get('kb_type', '企业知识库')
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
current_app.logger.info(
"[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
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
from app.services.dify import DifyService
if kb_type == 'ERP知识库':
from app.services.text2sql import Text2SQLService
generator = Text2SQLService.stream_chat(query, user.id, agent, conversation_id)
else:
generator = DifyService.stream_chat(query, user.id, agent, conversation_id)
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
stream_with_context(
generator
),
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('/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):
return jsonify({'error': 'feedback is disabled'}), 403
if score is None:
return jsonify({'error': 'score is required'}), 400
try:
score_value = int(score)
except (TypeError, ValueError):
return jsonify({'error': 'score must be an integer'}), 400
if score_value < 1 or score_value > 5:
return jsonify({'error': 'score must be between 1 and 5'}), 400
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 范围内
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
if conversation_id:
chat_logs_query = chat_logs_query.filter_by(conversation_id=conversation_id)
# 取最新一条对话日志
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
if not chat_log:
return jsonify({'error': 'ChatLog not found'}), 404
# 如果已存在反馈,则更新;否则新建
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),
)
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if not payload:
return jsonify({'error': 'source file mapping not found'}), 404
return jsonify({
'dataset_id': dataset_id,
'remote_document_id': remote_document_id,
'source_filename': payload.get('source_filename'),
'source_ext': payload.get('source_ext'),
'source_download_url': payload.get('source_download_url'),
'download_url_expires_at': payload.get('download_url_expires_at'),
})
@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:
return jsonify({'error': 'url is required'}), 400
if not _is_allowed_preview_url(file_url):
return jsonify({'error': 'url is not allowed for preview'}), 403
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'):
return jsonify({'error': 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
try:
wb = _load_excel_workbook(content, ext)
except Exception as e:
current_app.logger.warning("[excel-preview] parse workbook failed: %s", e)
return jsonify({'error': 'failed to parse excel file'}), 422
if not wb.sheetnames:
return jsonify({'error': '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:
return jsonify({'error': 'url is required'}), 400
if not _is_allowed_preview_url(file_url):
return jsonify({'error': 'url is not allowed for preview'}), 403
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
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
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
# 尝试多编码解码,提升兼容性。
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:
return jsonify({'error': 'failed to decode text file'}), 422
return jsonify({
'content': text,
'content_type': content_type or 'text/plain',
'ext': 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:
return jsonify({'error': 'url is required'}), 400
if not _is_allowed_preview_url(file_url):
return jsonify({'error': 'url is not allowed for preview'}), 403
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
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
# 如果是无法纯前端渲染的旧版 Office 或 PPT 格式,尝试转为 PDF 供前端统一渲染
if ext in ('doc', 'ppt', 'pptx') and request.args.get('download') != '1':
try:
content = _convert_office_to_pdf(content, ext)
ext = 'pdf'
content_type = 'application/pdf'
except Exception as e:
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
# 转换失败则回退到原始格式
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-'):
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
mime = fallback_types.get(ext) or content_type 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'
return resp
+349
View File
@@ -0,0 +1,349 @@
"""
backend/app/api/integration.py
文件用途:知识库外部集成查询接口
"""
from __future__ import annotations
from pathlib import Path
from flask import Blueprint, abort, current_app, jsonify, request, send_file
from sqlalchemy import func
from sqlalchemy.orm import joinedload
from app import db
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
integration_bp = Blueprint('integration', __name__)
def _require_integration_key():
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
if not configured:
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
if configured != incoming:
return jsonify({'error': 'Unauthorized'}), 401
return None
def _integration_base_url() -> str:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
return explicit
return request.host_url.rstrip('/')
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
versions = list(getattr(document, 'versions', []) or [])
if not versions:
return None
return next((item for item in versions if item.is_current), versions[0])
def _document_query():
return (
db.session.query(KbDocument)
.options(
joinedload(KbDocument.group),
joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records),
)
.filter(KbDocument.is_deleted.is_(False))
)
def _serialize_integration_document(
document: KbDocument,
*,
version: KbDocumentVersion | None = None,
sync_record: KbDifySyncRecord | None = None,
):
version = version or _current_version(document)
if not version:
abort(404, description='No current version found.')
sync_record = sync_record or (
next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None)
or (version.sync_records[0] if getattr(version, 'sync_records', None) else None)
)
base_url = _integration_base_url()
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
markdown_download_url = (
f'{base_url}/api/integration/files/{document.id}/download?kind=md'
if version.cleaned_file_path or version.cleaned_preview_path
else None
)
return {
'document_id': document.id,
'knowledge_base': {
'id': document.group.id if document.group else None,
'name': document.group.name if document.group else None,
'department_id': document.group.department_id if document.group else None,
'dify_dataset_id': document.group.dify_dataset_id if document.group else None,
},
'title': document.title,
'source_filename': version.source_file_name,
'source_ext': version.source_file_ext,
'file_name': version.source_file_name,
'version_id': version.id,
'version_no': version.version_no,
'convert_status': version.status,
'sync_status': sync_record.status if sync_record else None,
'uploaded_at': version.created_at.isoformat() if version.created_at else None,
'converted_at': version.converted_at.isoformat() if version.converted_at else None,
'download_url_expires_at': None,
'source_download_url': source_download_url,
'markdown_download_url': markdown_download_url,
'markdown_download_url_expires_at': None,
'markdown_public_url': markdown_download_url,
'dify': {
'dataset_id': sync_record.dataset_id if sync_record else (document.group.dify_dataset_id if document.group else None),
'remote_document_id': sync_record.remote_document_id if sync_record else None,
'status': sync_record.status if sync_record else None,
'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None,
},
}
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
return {
'id': group.id,
'knowledge_base_id': group.id,
'name': group.name,
'description': group.description,
'department_id': group.department_id,
'dify_dataset_id': group.dify_dataset_id,
'document_count': int(document_count or 0),
'created_at': group.created_at.isoformat() if group.created_at else None,
'updated_at': group.updated_at.isoformat() if group.updated_at else None,
}
def _list_files_payload(
*,
knowledge_base_id: int | None = None,
department_id: int | None = None,
file_name: str | None = None,
) -> list[dict]:
normalized_file_name = str(file_name or '').strip().lower()
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
if knowledge_base_id is not None:
query = query.filter(KbDocument.group_id == knowledge_base_id)
if department_id is not None:
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
documents = query.all()
payload = []
for document in documents:
version = _current_version(document)
if not version:
continue
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
if normalized_file_name and normalized_file_name not in normalized_name and normalized_file_name not in document.title.lower():
continue
payload.append(_serialize_integration_document(document, version=version))
return payload
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
if kind == 'source':
path = Path(version.source_file_path)
filename = version.source_file_name or f'document-{version.document_id}'
return path, filename
preferred = version.cleaned_file_path or version.cleaned_preview_path
if not preferred:
abort(409, description='Markdown not ready.')
path = Path(preferred)
filename = f'document-{version.document_id}-v{version.version_no}.md'
return path, filename
@integration_bp.before_request
def _verify_integration_access():
result = _require_integration_key()
if result is not None:
return result
return None
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
def get_file_detail(file_id: int):
document = _document_query().filter(KbDocument.id == file_id).first()
if not document:
return jsonify({'error': 'Document not found.'}), 404
return jsonify(_serialize_integration_document(document))
@integration_bp.route('/knowledge-bases', methods=['GET'])
def list_knowledge_bases():
department_id = request.args.get('department_id', type=int)
q = str(request.args.get('q') or '').strip()
document_counts = (
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
.filter(KbDocument.is_deleted.is_(False))
.group_by(KbDocument.group_id)
.subquery()
)
query = (
db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
.filter(KbGroup.is_active.is_(True))
.order_by(KbGroup.name.asc())
)
if department_id is not None:
query = query.filter(KbGroup.department_id == department_id)
if q:
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
rows = query.all()
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
@integration_bp.route('/files', methods=['GET'])
def list_files():
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
department_id = request.args.get('department_id', type=int)
file_name = request.args.get('file_name')
return jsonify({'data': _list_files_payload(
knowledge_base_id=knowledge_base_id,
department_id=department_id,
file_name=file_name,
)})
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
def list_files_for_knowledge_base(knowledge_base_id: int):
return jsonify({'data': _list_files_payload(
knowledge_base_id=knowledge_base_id,
file_name=request.args.get('file_name'),
)})
@integration_bp.route('/dify-file', methods=['GET'])
def get_file_detail_by_dify():
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
if not remote_document_id:
return jsonify({'error': 'remote_document_id is required'}), 400
record_query = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.options(
joinedload(KbDifySyncRecord.document_version)
.joinedload(KbDocumentVersion.document)
.joinedload(KbDocument.group),
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
)
if dataset_id:
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
record = record_query.first()
version = record.document_version if record else None
document = version.document if version else None
if not document:
return jsonify({'error': 'No local file mapping found for the given Dify document.'}), 404
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
@integration_bp.route('/dify-files/resolve', methods=['POST'])
def resolve_files_by_dify():
data = request.get_json(silent=True) or {}
items = data.get('items') if isinstance(data.get('items'), list) else []
if not items:
return jsonify({'data': []})
remote_ids = sorted({
str(item.get('remote_document_id') or '').strip()
for item in items
if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()
})
dataset_ids = sorted({
str(item.get('dataset_id') or '').strip()
for item in items
if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()
})
if not remote_ids:
return jsonify({'data': []})
query = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.options(
joinedload(KbDifySyncRecord.document_version)
.joinedload(KbDocumentVersion.document)
.joinedload(KbDocument.group),
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id.in_(remote_ids),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
)
if dataset_ids:
query = query.filter(
(KbDifySyncRecord.dataset_id.in_(dataset_ids)) | (KbDifySyncRecord.dataset_id.is_(None))
)
records = query.all()
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
records_by_remote: dict[str, KbDifySyncRecord] = {}
for record in records:
key = (record.dataset_id, record.remote_document_id)
records_by_key.setdefault(key, record)
records_by_remote.setdefault(record.remote_document_id, record)
payload = []
for item in items:
if not isinstance(item, dict):
continue
requested_dataset_id = str(item.get('dataset_id') or '').strip() or None
requested_remote_document_id = str(item.get('remote_document_id') or '').strip()
if not requested_remote_document_id:
continue
record = records_by_key.get((requested_dataset_id, requested_remote_document_id))
if record is None and requested_dataset_id is None:
record = records_by_remote.get(requested_remote_document_id)
version = record.document_version if record else None
document = version.document if version else None
payload.append({
'request': {
'dataset_id': requested_dataset_id,
'remote_document_id': requested_remote_document_id,
},
'found': bool(document),
'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None,
})
return jsonify({'data': payload})
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
def download_file(file_id: int):
kind = str(request.args.get('kind') or 'md').strip().lower()
document = _document_query().filter(KbDocument.id == file_id).first()
if not document:
return jsonify({'error': 'Document not found.'}), 404
version = _current_version(document)
if not version:
return jsonify({'error': 'No version found.'}), 404
path, filename = _resolve_download_path(version, kind)
if not path.exists():
return jsonify({'error': 'File not found on disk.'}), 404
return send_file(path, as_attachment=True, download_name=filename)
File diff suppressed because it is too large. Load diff
+157 -98
View File
@@ -5,7 +5,7 @@ from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_even
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.auth_jwt import get_current_user as _auth_current_user
from app.auth_jwt import issue_local_access_token
from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
from datetime import datetime, timedelta
import uuid
@@ -147,6 +147,20 @@ def _get_current_user():
"""
return _auth_current_user()
def _run_db_with_retry(operation, *, label: str):
try:
return operation()
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
db.session.rollback()
db.session.remove()
try:
db.engine.dispose()
except Exception as dispose_exc:
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
return operation()
def _is_wecom_configured():
return all([
current_app.config.get('WECOM_ENABLED'),
@@ -891,7 +905,7 @@ def login():
'error_code': 'PASSWORD_LOGIN_DISABLED',
}), 403
try:
def _attempt_login():
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
@@ -919,12 +933,28 @@ def login():
_write_login_audit('password', 'success', user=user)
db.session.commit()
return jsonify(_build_login_payload(user, 'password'))
try:
return _attempt_login()
except OperationalError as e:
print(f"Database connection error: {e}")
return jsonify({'error': 'Database connection failed'}), 503
db.session.rollback()
db.session.remove()
try:
return _attempt_login()
except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc)
return jsonify({'error': 'Database connection failed'}), 503
except DatabaseError as e:
db.session.rollback()
db.session.remove()
try:
return _attempt_login()
except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc)
return jsonify({'error': 'Database connection failed'}), 503
except Exception as e:
db.session.rollback()
print(f"Login error: {e}")
current_app.logger.exception('Login error: %s', e)
return jsonify({'error': 'Internal server error'}), 500
@@ -1720,64 +1750,76 @@ def home():
user = _get_current_user()
if not user:
return jsonify({'error': 'Unauthorized'}), 401
# Get all agents available to user (including public ones)
if user.role == 'admin':
agents = db.session.query(Agent).filter_by(is_active=True).all()
else:
# User permissions
agents = user.agents
# Favorites
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites]
# Quick Questions (Global + User specific)
qqs = db.session.query(QuickQuestion).filter(
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
).all()
# Layout
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
layout = layout_config.layout if layout_config else {}
# Embedded agents
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
embedded_agents = []
for rel in embedded_rel:
agent = db.session.get(Agent, rel.agent_id)
if agent:
embedded_agents.append({
def _load_home_payload():
# Get all agents available to user (including public ones)
if user.role == 'admin':
agent_rows = (
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
.filter(Agent.is_active.is_(True))
.all()
)
else:
# User permissions
agent_rows = [{
'id': agent.id,
'name': agent.name,
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
})
'description': agent.description,
'icon_url': agent.icon_url,
} for agent in user.agents]
return jsonify({
'user': {
'id': user.id,
'username': user.username,
'role': user.role,
'default_agent_id': user.default_agent_id,
'language': user.language,
'theme_preference': user.theme_preference or 'system',
},
'agents': [{
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url
} for a in agents],
'favorite_agent_ids': favorite_ids,
'quick_questions': [{
'id': q.id,
'title': q.title,
'question': q.question,
'agent_id': q.agent_id
} for q in qqs],
'embedded_agents': embedded_agents,
'layout': layout
})
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites]
qqs = db.session.query(QuickQuestion).filter(
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
).all()
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
layout = layout_config.layout if layout_config else {}
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
embedded_agents = []
for rel in embedded_rel:
agent = db.session.get(Agent, rel.agent_id)
if agent:
embedded_agents.append({
'id': agent.id,
'name': agent.name,
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
})
return jsonify({
'user': {
'id': user.id,
'username': user.username,
'role': user.role,
'default_agent_id': user.default_agent_id,
'language': user.language,
'theme_preference': user.theme_preference or 'system',
},
'agents': [{
'id': a.id if hasattr(a, 'id') else a['id'],
'name': a.name if hasattr(a, 'name') else a['name'],
'description': a.description if hasattr(a, 'description') else a['description'],
'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url']
} for a in agent_rows],
'favorite_agent_ids': favorite_ids,
'quick_questions': [{
'id': q.id,
'title': q.title,
'question': q.question,
'agent_id': q.agent_id
} for q in qqs],
'embedded_agents': embedded_agents,
'layout': layout
})
try:
return _run_db_with_retry(_load_home_payload, label='user.home')
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('user.home retry failed: %s', exc)
return jsonify({'error': 'Database connection failed'}), 503
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
def toggle_favorite(agent_id: int):
@@ -1888,41 +1930,45 @@ def user_profile():
# PUT
data = request.get_json() or {}
if 'real_name' in data:
user.real_name = data['real_name']
if 'phone_number' in data:
user.phone_number = data['phone_number']
if 'language' in data:
user.language = data['language']
if 'theme_preference' in data:
if data['theme_preference'] not in ['light', 'dark', 'system']:
return jsonify({'error': 'Invalid theme preference'}), 400
user.theme_preference = data['theme_preference']
# Allow editing email, employee_id, department
if 'email' in data:
# Check uniqueness
if data['email']:
existing = db.session.query(User).filter_by(email=data['email']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Email already exists'}), 400
user.email = data['email']
if 'employee_id' in data:
# Check uniqueness
if data['employee_id']:
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Employee ID already exists'}), 400
user.employee_id = data['employee_id']
if 'department' in data:
user.department = data['department']
try:
def _update_profile():
if 'real_name' in data:
user.real_name = data['real_name']
if 'phone_number' in data:
user.phone_number = data['phone_number']
if 'language' in data:
user.language = data['language']
if 'theme_preference' in data:
if data['theme_preference'] not in ['light', 'dark', 'system']:
return jsonify({'error': 'Invalid theme preference'}), 400
user.theme_preference = data['theme_preference']
if 'email' in data:
if data['email']:
existing = db.session.query(User).filter_by(email=data['email']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Email already exists'}), 400
user.email = data['email']
if 'employee_id' in data:
if data['employee_id']:
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
if existing and existing.id != user.id:
return jsonify({'error': 'Employee ID already exists'}), 400
user.employee_id = data['employee_id']
if 'department' in data:
user.department = data['department']
db.session.commit()
return jsonify({'message': 'Profile updated successfully'})
try:
return _run_db_with_retry(_update_profile, label='user.profile.update')
except (OperationalError, DatabaseError) as exc:
db.session.rollback()
current_app.logger.warning('user.profile.update retry failed: %s', exc)
return jsonify({'error': 'Database connection failed'}), 503
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@@ -2055,17 +2101,30 @@ def get_announcements():
"""
Get active announcements (Public)
"""
try:
anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all()
def _load_announcements():
anns = (
db.session.query(
Announcement.id,
Announcement.title,
Announcement.content,
Announcement.created_at,
)
.filter(Announcement.is_active.is_(True))
.order_by(Announcement.created_at.desc())
.all()
)
return jsonify([{
'id': a.id,
'title': a.title,
'content': a.content,
'created_at': a.created_at.isoformat()
} for a in anns])
except Exception as e:
import traceback
return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500
try:
return _run_db_with_retry(_load_announcements, label='user.announcements')
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('user.announcements retry failed: %s', exc)
return jsonify({'error': 'Database connection failed'}), 503
@user_bp.route('/announcements', methods=['POST'])
def create_announcement():
+56 -29
View File
@@ -6,6 +6,7 @@ from typing import Any, Optional
import jwt
import requests
from flask import current_app, g, request
from sqlalchemy.exc import DatabaseError, OperationalError
from app import db
from app.models import User
@@ -156,43 +157,69 @@ def _extract_unverified_claims(token: str) -> dict:
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
# Resolution order keeps compatibility with different token claim conventions.
user_id = claims.get('user_id') or claims.get('id')
if user_id is not None:
try:
user = db.session.get(User, int(user_id))
def _lookup() -> Optional[User]:
user_id = claims.get('user_id') or claims.get('id')
if user_id is not None:
try:
user = db.session.get(User, int(user_id))
if user:
return user
except (TypeError, ValueError):
pass
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
if username:
user = db.session.query(User).filter_by(username=str(username)).first()
if user:
return user
except (TypeError, ValueError):
pass
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
if username:
user = db.session.query(User).filter_by(username=str(username)).first()
if user:
return user
email = claims.get('email')
if email:
user = db.session.query(User).filter_by(email=str(email)).first()
if user:
return user
return None
email = claims.get('email')
if email:
user = db.session.query(User).filter_by(email=str(email)).first()
if user:
return user
return None
try:
return _lookup()
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s', request.path, exc)
db.session.rollback()
db.session.remove()
try:
db.engine.dispose()
except Exception:
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
return _lookup()
def _legacy_header_user() -> Optional[User]:
user_id = request.headers.get('X-User-Id')
if user_id:
try:
user = db.session.get(User, int(user_id))
if user:
return user
except (TypeError, ValueError):
pass
def _lookup() -> Optional[User]:
user_id = request.headers.get('X-User-Id')
if user_id:
try:
user = db.session.get(User, int(user_id))
if user:
return user
except (TypeError, ValueError):
pass
username = request.headers.get('X-Username')
if username:
return db.session.query(User).filter_by(username=username).first()
return None
username = request.headers.get('X-Username')
if username:
return db.session.query(User).filter_by(username=username).first()
return None
try:
return _lookup()
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s', request.path, exc)
db.session.rollback()
db.session.remove()
try:
db.engine.dispose()
except Exception:
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
return _lookup()
def get_current_user() -> Optional[User]:
+5 -3
View File
@@ -16,6 +16,9 @@ load_dotenv(_BACKEND_DIR / '.env')
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key')
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'sync').strip().lower()
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
# 数据库连接池配置
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': 20,
@@ -37,6 +40,7 @@ class Config:
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
# External integration API (resolve original source file links by Dify IDs)
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE', 'http://192.168.100.230:8891')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
@@ -104,9 +108,7 @@ class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
#'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
#'postgresql://postgres:123456@localhost:5432/hxops_db',
'postgresql://postgres:1qaz%40WSX@localhost:5432/hxops',
)
+186 -1
View File
@@ -1,6 +1,6 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
@@ -338,6 +338,191 @@ class AppSetting(Base):
)
class KbGroup(Base):
"""
知识库分组
用途:承载数据清洗/知识库管理模块中的分组/知识库
"""
__tablename__ = 'kb_groups'
__table_args__ = (
UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'),
Index('ix_kb_groups_department_active', 'department_id', 'is_active'),
Index('ix_kb_groups_dify_dataset_id', 'dify_dataset_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(128), index=True)
description: Mapped[Optional[str]] = mapped_column(Text)
department_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
dify_dataset_id: Mapped[Optional[str]] = mapped_column(String(128))
dify_dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
documents: Mapped[List["KbDocument"]] = relationship(
"KbDocument",
back_populates="group",
cascade="all, delete-orphan",
)
class KbDocument(Base):
"""
知识库逻辑文档
用途:表示一个文档条目,不直接等同于某一次上传文件
"""
__tablename__ = 'kb_documents'
__table_args__ = (
UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'),
Index('ix_kb_documents_group_status', 'group_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
group_id: Mapped[int] = mapped_column(ForeignKey('kb_groups.id'), index=True)
title: Mapped[str] = mapped_column(String(255))
description: Mapped[Optional[str]] = mapped_column(Text)
status: Mapped[str] = mapped_column(String(32), default='draft', index=True)
source_type: Mapped[Optional[str]] = mapped_column(String(32))
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
group: Mapped["KbGroup"] = relationship("KbGroup", back_populates="documents")
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
versions: Mapped[List["KbDocumentVersion"]] = relationship(
"KbDocumentVersion",
back_populates="document",
cascade="all, delete-orphan",
order_by="desc(KbDocumentVersion.version_no)",
)
class KbDocumentVersion(Base):
"""
知识库文档版本
用途:记录每次上传、清洗、同步产生的版本信息
"""
__tablename__ = 'kb_document_versions'
__table_args__ = (
UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'),
Index('ix_kb_document_versions_doc_status', 'document_id', 'status'),
Index('ix_kb_document_versions_sha256', 'sha256'),
)
id: Mapped[int] = mapped_column(primary_key=True)
document_id: Mapped[int] = mapped_column(ForeignKey('kb_documents.id'), index=True)
version_no: Mapped[int] = mapped_column(Integer)
status: Mapped[str] = mapped_column(String(32), default='uploaded', index=True)
is_current: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
source_file_name: Mapped[str] = mapped_column(String(255))
source_file_path: Mapped[str] = mapped_column(Text)
source_file_ext: Mapped[Optional[str]] = mapped_column(String(32))
source_file_size: Mapped[Optional[int]] = mapped_column(Integer)
cleaned_file_path: Mapped[Optional[str]] = mapped_column(Text)
cleaned_preview_path: Mapped[Optional[str]] = mapped_column(Text)
sha256: Mapped[Optional[str]] = mapped_column(String(64))
word_count: Mapped[int] = mapped_column(Integer, default=0)
error_message: Mapped[Optional[str]] = mapped_column(Text)
warnings_json: Mapped[Optional[dict]] = mapped_column(JSON)
uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
converted_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
document: Mapped["KbDocument"] = relationship("KbDocument", back_populates="versions")
uploaded_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[uploaded_by_id])
jobs: Mapped[List["KbJob"]] = relationship(
"KbJob",
back_populates="document_version",
cascade="all, delete-orphan",
)
sync_records: Mapped[List["KbDifySyncRecord"]] = relationship(
"KbDifySyncRecord",
back_populates="document_version",
cascade="all, delete-orphan",
order_by="desc(KbDifySyncRecord.updated_at)",
)
class KbJob(Base):
"""
知识库后台任务
用途:记录上传、清洗、同步等后台任务执行情况
"""
__tablename__ = 'kb_jobs'
__table_args__ = (
Index('ix_kb_jobs_status_created', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
job_type: Mapped[str] = mapped_column(String(32), index=True)
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
queue_job_id: Mapped[Optional[str]] = mapped_column(String(64))
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
progress: Mapped[int] = mapped_column(Integer, default=0)
message: Mapped[Optional[str]] = mapped_column(Text)
error_message: Mapped[Optional[str]] = mapped_column(Text)
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
document_version: Mapped[Optional["KbDocumentVersion"]] = relationship(
"KbDocumentVersion",
back_populates="jobs",
)
class KbDifySyncRecord(Base):
"""
知识库 Dify 同步记录
用途:记录本地文档版本与 Dify 远端文档之间的同步映射
"""
__tablename__ = 'kb_dify_sync_records'
__table_args__ = (
UniqueConstraint(
'document_version_id',
'remote_document_id',
name='uq_kb_dify_sync_records_version_remote'
),
Index('ix_kb_dify_sync_records_dataset_id', 'dataset_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
document_version_id: Mapped[int] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
dataset_id: Mapped[str] = mapped_column(String(128))
dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
remote_document_id: Mapped[str] = mapped_column(String(128))
remote_document_name: Mapped[Optional[str]] = mapped_column(String(255))
status: Mapped[str] = mapped_column(String(32), default='pending', index=True)
sync_hash: Mapped[Optional[str]] = mapped_column(String(64))
error_message: Mapped[Optional[str]] = mapped_column(Text)
synced_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
document_version: Mapped["KbDocumentVersion"] = relationship(
"KbDocumentVersion",
back_populates="sync_records",
)
synced_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[synced_by_id])
class WecomCallbackAudit(Base):
"""
企业微信回调审计表
+26 -15
View File
@@ -38,22 +38,33 @@ class DifyService:
"""Dify service wrapper."""
@staticmethod
def build_chat_messages_url(raw_base_url: str) -> str:
def _build_chat_messages_url(base_url: str) -> str:
"""
统一构建 Dify chat-messages URL,兼容以下输入:
- http(s)://host
- http(s)://host/v1
- http(s)://host/chat-messages
- http(s)://host/v1/chat-messages
Build the Dify chat-messages endpoint URL from a base URL.
Our config/agent base_url may be:
- https://api.dify.ai/v1
- http://host:port
- http://host:port/v1
- (user mistake) http://host:port/v1/chat-messages
This helper normalizes common mistakes and prevents duplicate `/v1/v1/...`.
"""
base_url = (raw_base_url or '').strip().rstrip('/')
if not base_url:
return ''
if base_url.endswith('/v1/chat-messages') or base_url.endswith('/chat-messages'):
return base_url
if base_url.endswith('/v1'):
return f'{base_url}/chat-messages'
return f'{base_url}/v1/chat-messages'
base = str(base_url or "").strip().rstrip("/")
if not base:
# Keep old behavior: downstream will fail with a request error.
return "/v1/chat-messages"
# User mistake hardening: strip endpoint suffix if someone stored it as base_url.
if base.endswith("/v1/chat-messages"):
base = base[: -len("/v1/chat-messages")].rstrip("/")
elif base.endswith("/chat-messages"):
base = base[: -len("/chat-messages")].rstrip("/")
# Config.DIFY_API_BASE defaults to ".../v1". Avoid double "/v1".
if base.endswith("/v1"):
return f"{base}/chat-messages"
return f"{base}/v1/chat-messages"
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
@@ -78,7 +89,7 @@ class DifyService:
"""
# Prefer agent-specific base URL; fallback to global config.
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
url = DifyService.build_chat_messages_url(base_url)
url = DifyService._build_chat_messages_url(base_url)
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
+47 -8
View File
@@ -3,9 +3,10 @@ Integration API client for resolving original source-file download links.
"""
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import requests
from flask import current_app
from flask import current_app, has_app_context, has_request_context, request
from app.config import Config
@@ -13,6 +14,44 @@ from app.config import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _is_loopback_url(url: str) -> bool:
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
return host in {"127.0.0.1", "localhost", "::1"}
@staticmethod
def get_api_key() -> str:
if has_app_context():
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
return str(Config.INTEGRATION_API_KEY or "").strip()
@staticmethod
def get_base_url() -> str:
mode = "local"
if has_app_context():
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
else:
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
public_base = ""
if mode != "external":
# For server-side lookups inside containers/workers, an explicit integration
# endpoint is more reliable than a public loopback URL like 127.0.0.1:5002.
if configured and (
not has_request_context()
or IntegrationApiService._is_loopback_url(public_base)
):
return configured
if public_base:
return public_base
if has_request_context():
return request.host_url.rstrip("/")
return configured
@staticmethod
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
return (str(dataset_id), str(remote_document_id))
@@ -60,8 +99,8 @@ class IntegrationApiService:
if cached and IntegrationApiService._is_cache_valid(cached):
return cached
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
api_key = Config.INTEGRATION_API_KEY
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return None
@@ -82,7 +121,7 @@ class IntegrationApiService:
IntegrationApiService._cache[cache_key] = payload
return payload
except Exception as e:
if current_app:
if has_app_context():
current_app.logger.warning(f"Integration API lookup failed: {e}")
return None
@@ -121,8 +160,8 @@ class IntegrationApiService:
if not unresolved:
return results
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
api_key = Config.INTEGRATION_API_KEY
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return results
@@ -136,7 +175,7 @@ class IntegrationApiService:
try:
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
if resp.status_code != 200:
if current_app:
if has_app_context():
current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code
)
@@ -187,7 +226,7 @@ class IntegrationApiService:
return results
except Exception as e:
if current_app:
if has_app_context():
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup when batch call errors.
for item in unresolved:
@@ -0,0 +1,3 @@
"""
知识库清洗服务包
"""
@@ -0,0 +1,305 @@
"""
backend/app/services/knowledge_cleaning/dify_sync_service.py
文件用途:知识库文档版本到 Dify 的最小同步服务
"""
from __future__ import annotations
from datetime import datetime
import hashlib
from pathlib import Path
import requests
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
class KbDifySyncError(RuntimeError):
pass
class KbDifySyncService:
def __init__(self) -> None:
settings = get_kb_dify_settings()
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
self.timeout = 60
def _headers(self) -> dict[str, str]:
if not self.base_url:
raise KbDifySyncError('DIFY_API_BASE 未配置')
if not self.api_key:
raise KbDifySyncError('DIFY_API_KEY 未配置')
return {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json',
}
def _request(self, method: str, path: str, **kwargs):
url = f'{self.base_url}{path}'
try:
response = requests.request(
method,
url,
headers=self._headers(),
timeout=self.timeout,
**kwargs,
)
except requests.RequestException as exc:
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
if response.status_code >= 400:
raise KbDifySyncError(
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
)
if response.status_code == 204:
return None
return response.json()
def list_datasets(self) -> list[dict]:
payload = self._request('GET', '/datasets')
return payload.get('data', []) if isinstance(payload, dict) else []
def create_dataset(self, *, name: str, description: str | None) -> dict:
payload = {
'name': name,
'description': description or '',
'permission': self.permission,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'retrieval_model': {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': 3,
'score_threshold_enabled': False,
'score_threshold': None,
},
}
return self._request('POST', '/datasets', json=payload)
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
if group.dify_dataset_id:
return group.dify_dataset_id, group.dify_dataset_name or group.name
dataset_name = group.dify_dataset_name or group.name
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
if existing:
group.dify_dataset_id = existing.get('id')
group.dify_dataset_name = existing.get('name') or dataset_name
db.session.commit()
return group.dify_dataset_id, group.dify_dataset_name
created = self.create_dataset(name=dataset_name, description=group.description)
group.dify_dataset_id = created.get('id')
group.dify_dataset_name = created.get('name') or dataset_name
db.session.commit()
return group.dify_dataset_id, group.dify_dataset_name
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
payload = {
'name': name,
'text': text,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'process_rule': {'mode': 'automatic'},
}
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
payload = {
'name': name,
'text': text,
'process_rule': {'mode': 'automatic'},
}
return self._request(
'POST',
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
json=payload,
)
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
self._request(
'DELETE',
f'/datasets/{dataset_id}/documents/{document_id}',
)
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
for value in candidate_paths:
if not value:
continue
path = Path(value)
if not path.exists():
continue
text = path.read_text(encoding='utf-8', errors='ignore').strip()
if text:
return text, str(path)
raise KbDifySyncError('没有可用于同步的文本结果')
def _is_remote_document_missing(error_text: str) -> bool:
return (
'404' in error_text
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
)
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
version = db.session.get(KbDocumentVersion, document_version_id)
if not version or not version.document or not version.document.group:
raise KbDifySyncError('文档版本或关联分组不存在')
group = version.document.group
document = version.document
text, source_path = _load_sync_text(version)
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
service = KbDifySyncService()
dataset_id, dataset_name = service.ensure_dataset(group)
existing_record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_id == document.id,
KbDifySyncRecord.remote_document_id.isnot(None),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
remote_document_id = None
remote_document_name = None
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
try:
payload = service.get_document(
dataset_id=dataset_id,
document_id=existing_record.remote_document_id,
)
remote_document_id = payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('name') or existing_record.remote_document_name or document.title
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
raise
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or document.title
elif existing_record and existing_record.dataset_id == dataset_id:
try:
payload = service.update_document_by_text(
dataset_id=dataset_id,
document_id=existing_record.remote_document_id,
name=document.title,
text=text,
)
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
raise
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('document', {}).get('name') or document.title
else:
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or document.title
if not remote_document_id:
raise KbDifySyncError('Dify 未返回远端文档 ID')
record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_version_id == version.id,
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
status='synced',
sync_hash=sync_hash,
synced_by_id=synced_by_id,
)
db.session.add(record)
else:
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = 'synced'
record.sync_hash = sync_hash
record.error_message = None
record.synced_by_id = synced_by_id
record.synced_at = datetime.utcnow()
db.session.commit()
return {
'dataset_id': dataset_id,
'dataset_name': dataset_name,
'remote_document_id': remote_document_id,
'remote_document_name': remote_document_name,
'sync_hash': sync_hash,
'source_path': source_path,
}
def delete_document_from_dify(document_id: int) -> dict:
records = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_id == document_id,
KbDifySyncRecord.remote_document_id.isnot(None),
KbDifySyncRecord.dataset_id.isnot(None),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.all()
)
if not records:
return {'deleted': True, 'remote_document_count': 0}
service = KbDifySyncService()
deleted_count = 0
visited: set[tuple[str, str]] = set()
for record in records:
key = (str(record.dataset_id), str(record.remote_document_id))
if key in visited:
continue
visited.add(key)
try:
service.delete_document(dataset_id=key[0], document_id=key[1])
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
raise
record.status = 'deleted'
record.error_message = None
record.synced_at = datetime.utcnow()
deleted_count += 1
db.session.commit()
return {'deleted': True, 'remote_document_count': deleted_count}
@@ -0,0 +1,242 @@
"""
backend/app/services/knowledge_cleaning/dify_sync_service.py
文件用途:知识库文档版本到 Dify 的最小同步服务
"""
from __future__ import annotations
from datetime import datetime
import hashlib
from pathlib import Path
import requests
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
class KbDifySyncError(RuntimeError):
pass
class KbDifySyncService:
def __init__(self) -> None:
settings = get_kb_dify_settings()
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
self.timeout = 60
def _headers(self) -> dict[str, str]:
if not self.base_url:
raise KbDifySyncError('DIFY_API_BASE 未配置')
if not self.api_key:
raise KbDifySyncError('DIFY_API_KEY 未配置')
return {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json',
}
def _request(self, method: str, path: str, **kwargs):
url = f'{self.base_url}{path}'
try:
response = requests.request(
method,
url,
headers=self._headers(),
timeout=self.timeout,
**kwargs,
)
except requests.RequestException as exc:
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
if response.status_code >= 400:
raise KbDifySyncError(
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
)
if response.status_code == 204:
return None
return response.json()
def list_datasets(self) -> list[dict]:
payload = self._request('GET', '/datasets')
return payload.get('data', []) if isinstance(payload, dict) else []
def create_dataset(self, *, name: str, description: str | None) -> dict:
payload = {
'name': name,
'description': description or '',
'permission': self.permission,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'retrieval_model': {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': 3,
'score_threshold_enabled': False,
'score_threshold': None,
},
}
return self._request('POST', '/datasets', json=payload)
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
if group.dify_dataset_id:
return group.dify_dataset_id, group.dify_dataset_name or group.name
dataset_name = group.dify_dataset_name or group.name
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
if existing:
group.dify_dataset_id = existing.get('id')
group.dify_dataset_name = existing.get('name') or dataset_name
db.session.commit()
return group.dify_dataset_id, group.dify_dataset_name
created = self.create_dataset(name=dataset_name, description=group.description)
group.dify_dataset_id = created.get('id')
group.dify_dataset_name = created.get('name') or dataset_name
db.session.commit()
return group.dify_dataset_id, group.dify_dataset_name
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
payload = {
'name': name,
'text': text,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'process_rule': {'mode': 'automatic'},
}
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
payload = {
'name': name,
'text': text,
'process_rule': {'mode': 'automatic'},
}
return self._request(
'POST',
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
json=payload,
)
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
for value in candidate_paths:
if not value:
continue
path = Path(value)
if not path.exists():
continue
text = path.read_text(encoding='utf-8', errors='ignore').strip()
if text:
return text, str(path)
raise KbDifySyncError('没有可用于同步的文本结果')
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
version = db.session.get(KbDocumentVersion, document_version_id)
if not version or not version.document or not version.document.group:
raise KbDifySyncError('文档版本或关联分组不存在')
group = version.document.group
document = version.document
text, source_path = _load_sync_text(version)
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
service = KbDifySyncService()
dataset_id, dataset_name = service.ensure_dataset(group)
existing_record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_id == document.id,
KbDifySyncRecord.remote_document_id.isnot(None),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
remote_document_id = None
remote_document_name = None
if existing_record and existing_record.sync_hash == sync_hash:
remote_document_id = existing_record.remote_document_id
remote_document_name = existing_record.remote_document_name
elif existing_record and existing_record.dataset_id == dataset_id:
try:
payload = service.update_document_by_text(
dataset_id=dataset_id,
document_id=existing_record.remote_document_id,
name=document.title,
text=text,
)
except KbDifySyncError as exc:
error_text = str(exc)
remote_missing = (
'404' in error_text
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
)
if not remote_missing:
raise
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('document', {}).get('name') or document.title
else:
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or document.title
if not remote_document_id:
raise KbDifySyncError('Dify 未返回远端文档 ID')
record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_version_id == version.id,
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
status='synced',
sync_hash=sync_hash,
synced_by_id=synced_by_id,
)
db.session.add(record)
else:
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = 'synced'
record.sync_hash = sync_hash
record.error_message = None
record.synced_by_id = synced_by_id
record.synced_at = datetime.utcnow()
db.session.commit()
return {
'dataset_id': dataset_id,
'dataset_name': dataset_name,
'remote_document_id': remote_document_id,
'remote_document_name': remote_document_name,
'sync_hash': sync_hash,
'source_path': source_path,
}
@@ -0,0 +1,88 @@
"""
backend/app/services/knowledge_cleaning/edkb_adapter.py
文件用途:edkb_system 轻量适配层
"""
from __future__ import annotations
import shutil
import tempfile
from pathlib import Path
TEXT_EXTS = {'.txt', '.md'}
def _find_generated_markdown(output_root: Path) -> Path:
# Look for md files directly inside output_root or inside any of its subdirectories
# Note that edkb_system puts output inside a directory matching the parent dir name, which might be tmp_dir
candidates = [path for path in output_root.rglob('*.md') if not path.name.startswith('_')]
if not candidates:
raise RuntimeError('No markdown output produced by edkb_system.')
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _write_text_result(source_path: Path, target_dir: Path) -> dict:
target_dir.mkdir(parents=True, exist_ok=True)
cleaned_path = target_dir / 'document.md'
content = source_path.read_text(encoding='utf-8', errors='ignore')
cleaned_path.write_text(content, encoding='utf-8')
return {
'mode': 'plain_text',
'cleaned_file_path': str(cleaned_path),
'cleaned_preview_path': str(cleaned_path),
'word_count': len(content.split()),
}
def build_clean_result(source_path: Path, target_dir: Path) -> dict:
"""
优先产出真实文本结果:
- txt/md:直接抽取文本;
- 其它格式:尝试走 edkb_system;
- 失败时由调用方决定是否回退。
"""
suffix = source_path.suffix.lower()
if suffix in TEXT_EXTS:
return _write_text_result(source_path, target_dir)
from edkb_system.config import SystemConfig
from edkb_system.controller import build_knowledge
target_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='edkb_', dir=str(target_dir.parent)) as tmp_dir:
tmp_root = Path(tmp_dir)
output_dir = tmp_root / 'output'
cache_dir = tmp_root / 'cache'
output_dir.mkdir(parents=True, exist_ok=True)
cache_dir.mkdir(parents=True, exist_ok=True)
# IMPORTANT: copy the source file into tmp_root so that its parent directory is predictable
# edkb_system seems to output to output_dir / <parent_dir_name> / <filename>.md
# ALSO IMPORTANT: ensure the file has its original suffix, otherwise edkb_system might fail or output nothing
original_name = getattr(source_path, "original_filename", None)
if not original_name:
original_name = source_path.name
if "." not in original_name and hasattr(source_path, "suffix_hint"):
original_name += source_path.suffix_hint
tmp_source_path = tmp_root / original_name
shutil.copy2(source_path, tmp_source_path)
config = SystemConfig.load(None)
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
failures = [item for item in result if item.get('status') == 'failed']
if failures:
raise RuntimeError(failures[0].get('error') or 'edkb_system failed.')
markdown_source = _find_generated_markdown(output_dir)
cleaned_path = target_dir / 'document.md'
shutil.copy2(markdown_source, cleaned_path)
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
return {
'mode': 'edkb_system',
'cleaned_file_path': str(cleaned_path),
'cleaned_preview_path': str(cleaned_path),
'word_count': len(content.split()),
}
@@ -0,0 +1,63 @@
"""
backend/app/services/knowledge_cleaning/queue_service.py
文件用途:知识库任务调度最小实现
"""
from __future__ import annotations
from flask import current_app
from app import db
from app.models import KbJob
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
"""
最小任务调度器:
- sync: 上传后立即在请求内执行;
- worker: 仅保留 queued,等待独立 worker 轮询;
- manual: 保留 queued,等待管理台手动执行。
"""
mode = str(current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')).strip().lower()
job = db.session.get(KbJob, job_id)
if not job:
return False, 'job_not_found'
if mode == 'sync':
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
if job.job_type == 'clean':
return run_clean_job(job_id)
if job.job_type == 'path_upload':
return run_path_upload_job(job_id)
return False, f'unsupported_sync_job:{job.job_type}'
if mode == 'worker':
return True, 'queued_for_worker'
return True, 'queued_manual'
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
return enqueue_kb_job(job_id)
def process_next_kb_job() -> tuple[bool, str]:
job = (
db.session.query(KbJob)
.filter(KbJob.job_type.in_(('path_upload', 'clean')), KbJob.status == 'queued')
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.first()
)
if not job:
return False, 'no_job'
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
if job.job_type == 'path_upload':
return run_path_upload_job(job.id)
return run_clean_job(job.id)
def process_next_clean_job() -> tuple[bool, str]:
return process_next_kb_job()
@@ -0,0 +1,75 @@
"""
backend/app/services/knowledge_cleaning/settings_service.py
文件用途:知识库 Dify 设置读写服务
"""
from __future__ import annotations
import os
from flask import current_app
from app import db
from app.env_persistence import persist_env_settings
from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion
SETTING_DEFAULTS = {
'DIFY_API_BASE': '',
'DIFY_API_KEY': '',
'KB_DIFY_PERMISSION': 'only_me',
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
'KB_DIFY_DOC_FORM': 'text_model',
}
def _get_setting_value(key: str) -> str:
row = db.session.get(AppSetting, key)
if row and row.value is not None:
return row.value
config_value = current_app.config.get(key)
if config_value is not None:
return str(config_value)
return str(os.getenv(key, SETTING_DEFAULTS.get(key, '')))
def get_kb_dify_settings() -> dict:
payload = {key: _get_setting_value(key) for key in SETTING_DEFAULTS}
payload['dify_api_configured'] = bool(payload.get('DIFY_API_KEY'))
return payload
def save_kb_dify_settings(values: dict[str, object]) -> dict:
allowed = {key: values[key] for key in SETTING_DEFAULTS if key in values}
persisted = persist_env_settings(allowed)
return {
**get_kb_dify_settings(),
**persisted,
'dify_api_configured': bool((persisted.get('DIFY_API_KEY') or _get_setting_value('DIFY_API_KEY')).strip()),
}
def get_kb_dify_health_payload() -> dict:
settings = get_kb_dify_settings()
base_url = settings.get('DIFY_API_BASE') or ''
api_key = settings.get('DIFY_API_KEY') or ''
payload = {
'dify_base_url': base_url,
'dify_api_configured': bool(api_key),
'api': {
'configured': bool(api_key),
'reachable': False,
'dataset_count': None,
'error': None,
},
'local_sync_health': {
'dataset_bound_groups': db.session.query(KbGroup).filter(KbGroup.dify_dataset_id.isnot(None)).count(),
'sync_records': db.session.query(KbDifySyncRecord).count(),
'syncing_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'syncing').count(),
'synced_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'synced').count(),
'failed_sync_records': db.session.query(KbDifySyncRecord).filter(KbDifySyncRecord.status == 'failed').count(),
'pending_sync_jobs': db.session.query(KbJob).filter(KbJob.job_type == 'sync_dify', KbJob.status == 'queued').count(),
},
}
return payload
@@ -0,0 +1,471 @@
"""
backend/app/services/knowledge_cleaning/tasks.py
文件用途:知识库任务执行第一版
"""
from __future__ import annotations
from datetime import datetime
import hashlib
from pathlib import Path
import shutil
import zipfile
from flask import current_app
from app import db
from app.models import KbDocument, KbDocumentVersion, KbJob
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
from app.services.knowledge_cleaning.dify_sync_service import (
KbDifySyncError,
sync_document_version_to_dify,
)
from werkzeug.utils import secure_filename
def _utc_now() -> datetime:
return datetime.utcnow()
def _infer_missing_extension(source_path: Path) -> str:
if zipfile.is_zipfile(source_path):
try:
with zipfile.ZipFile(source_path) as archive:
names = archive.namelist()
except Exception:
names = []
if any(name.startswith('xl/') for name in names):
return '.xlsx'
if any(name.startswith('word/') for name in names):
return '.docx'
if any(name.startswith('ppt/') for name in names):
return '.pptx'
return '.zip'
try:
header = source_path.read_bytes()[:8]
except Exception:
return ''
if header.startswith(b'\xd0\xcf\x11\xe0'):
return '.xls'
return ''
def _normalized_source_filename(version: KbDocumentVersion, source_path: Path) -> str:
raw_name = Path(version.source_file_name or source_path.name).name
if Path(raw_name).suffix:
return raw_name
ext = version.source_file_ext
if ext:
normalized_ext = ext if str(ext).startswith('.') else f'.{ext}'
else:
normalized_ext = _infer_missing_extension(source_path)
return f'{raw_name}{normalized_ext}' if normalized_ext else raw_name
def _hash_file(source_path: Path) -> tuple[str, int]:
sha = hashlib.sha256()
size = 0
with source_path.open('rb') as handle:
while True:
chunk = handle.read(1024 * 1024)
if not chunk:
break
sha.update(chunk)
size += len(chunk)
return sha.hexdigest(), size
def _safe_storage_filename(filename: str) -> str:
candidate = Path(filename or '').name.strip()
if not candidate:
return 'uploaded_file'
safe_stem = secure_filename(Path(candidate).stem) or 'uploaded_file'
suffix = Path(candidate).suffix.lower()
return f'{safe_stem}{suffix}'
def _kb_storage_root() -> Path:
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
root.mkdir(parents=True, exist_ok=True)
return root
def _get_or_create_document(*, group_id: int, title: str, description: str | None, user_id: int | None) -> KbDocument:
document = (
db.session.query(KbDocument)
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
.first()
)
if document and document.is_deleted:
document.is_deleted = False
if document:
document.description = description
document.updated_by_id = user_id
return document
document = KbDocument(
group_id=group_id,
title=title,
description=description,
status='draft',
source_type='upload',
created_by_id=user_id,
updated_by_id=user_id,
)
db.session.add(document)
db.session.flush()
return document
def _find_existing_active_document(*, group_id: int, title: str) -> KbDocument | None:
return (
db.session.query(KbDocument)
.filter(
KbDocument.group_id == group_id,
KbDocument.title == title,
KbDocument.is_deleted.is_(False),
)
.first()
)
def _next_version_no(document: KbDocument) -> int:
versions = list(getattr(document, 'versions', []) or [])
if not versions:
return 1
return max(item.version_no for item in versions) + 1
def _register_document_version_from_staged_file(
*,
group_id: int,
relative_path: str,
staged_path: Path,
original_name: str,
user_id: int | None,
) -> tuple[KbDocument, KbDocumentVersion, KbJob]:
display_name = Path(original_name or relative_path).name or Path(relative_path).name or 'uploaded_file'
if _find_existing_active_document(group_id=group_id, title=display_name):
raise FileExistsError('上传失败,文件已存在')
document = _get_or_create_document(
group_id=group_id,
title=display_name,
description=display_name,
user_id=user_id,
)
version_no = _next_version_no(document)
source_file_name = _safe_storage_filename(original_name)
ext = Path(source_file_name).suffix.lower().lstrip('.') or None
version_dir = _kb_storage_root() / f'group_{group_id:04d}' / f'document_{document.id:06d}' / f'v{version_no:03d}'
version_dir.mkdir(parents=True, exist_ok=True)
target_path = version_dir / source_file_name
shutil.copy2(staged_path, target_path)
sha256, file_size = _hash_file(target_path)
for existing in document.versions:
if existing.is_current:
existing.is_current = False
version = KbDocumentVersion(
document_id=document.id,
version_no=version_no,
status='uploaded',
is_current=True,
source_file_name=source_file_name,
source_file_path=str(target_path),
source_file_ext=ext,
source_file_size=file_size,
sha256=sha256,
uploaded_by_id=user_id,
)
db.session.add(version)
db.session.flush()
document.source_type = 'upload'
document.status = 'uploaded'
document.updated_by_id = user_id
upload_job = KbJob(
job_type='upload',
status='success',
group_id=group_id,
document_id=document.id,
document_version_id=version.id,
progress=100,
message=f'已通过上传路径导入文件:{relative_path}',
payload_json={
'source_file_name': source_file_name,
'relative_path': relative_path,
'source_file_size': file_size,
},
result_json={
'sha256': sha256,
'stored_path': str(target_path),
},
created_by_id=user_id,
started_at=version.created_at,
finished_at=version.created_at,
)
clean_job = KbJob(
job_type='clean',
status='queued',
group_id=group_id,
document_id=document.id,
document_version_id=version.id,
progress=0,
message='等待清洗任务执行',
payload_json={
'document_version_id': version.id,
'source_file_name': source_file_name,
'relative_path': relative_path,
},
created_by_id=user_id,
)
db.session.add(upload_job)
db.session.add(clean_job)
db.session.commit()
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
enqueue_clean_job(clean_job.id)
return document, version, clean_job
def run_path_upload_job(job_id: int) -> tuple[bool, str]:
job = db.session.get(KbJob, job_id)
if not job:
return False, '任务不存在'
if job.job_type != 'path_upload':
return False, '当前任务不是 path_upload 类型'
payload = dict(job.payload_json or {})
items = list(payload.get('files') or [])
total = max(int(payload.get('total_files') or len(items) or 0), 1)
result = dict(job.result_json or {})
result.setdefault('total', total)
result.setdefault('success', 0)
result.setdefault('failed', 0)
result.setdefault('staged', len(items))
job.status = 'running'
job.progress = min(job.progress or 0, 5)
job.message = '后台开始批量导入上传路径文件'
job.started_at = job.started_at or _utc_now()
db.session.commit()
success_count = 0
fail_count = 0
processed = 0
for item in items:
if item.get('status') in ('success', 'failed'):
processed += 1
if item.get('status') == 'success':
success_count += 1
else:
fail_count += 1
continue
staged_path = Path(str(item.get('staged_path') or ''))
item['status'] = 'uploading'
item['error'] = None
payload['current_file'] = item.get('relative_path') or item.get('original_name')
job.payload_json = payload
job.message = f'正在导入:{payload["current_file"]}'
db.session.commit()
try:
if not staged_path.exists():
raise FileNotFoundError('暂存文件不存在')
document, version, _clean_job = _register_document_version_from_staged_file(
group_id=job.group_id,
relative_path=str(item.get('relative_path') or item.get('original_name') or staged_path.name),
staged_path=staged_path,
original_name=str(item.get('original_name') or staged_path.name),
user_id=job.created_by_id,
)
item['status'] = 'success'
item['document_id'] = document.id
item['version_id'] = version.id
item['error'] = None
success_count += 1
except Exception as exc:
item['status'] = 'failed'
item['error'] = str(exc)
fail_count += 1
processed += 1
result['success'] = success_count
result['failed'] = fail_count
result['processed'] = processed
result['items'] = items
job.payload_json = payload
job.result_json = result
job.progress = min(int(processed * 100 / total), 100)
db.session.commit()
payload['current_file'] = ''
job.payload_json = payload
job.result_json = result
job.progress = 100
job.finished_at = _utc_now()
if fail_count > 0:
job.status = 'failed'
job.message = f'路径上传完成,成功 {success_count} 条,失败 {fail_count} 条'
job.error_message = f'部分文件上传失败:{fail_count} 条'
db.session.commit()
return False, 'partial_failed'
job.status = 'success'
job.message = f'路径上传完成,成功 {success_count} 条'
job.error_message = None
db.session.commit()
return True, 'ok'
def run_clean_job(job_id: int) -> tuple[bool, str]:
"""
第一版最小清洗任务执行器。
当前先不接 edkb_system,只做以下动作:
1. 把 queued 的 clean 任务改为 running/success;
2. 为版本生成 cleaned_preview_path;
3. 更新版本状态为 cleaned;
4. 为下一步接真实清洗链路预留结构。
"""
job = db.session.get(KbJob, job_id)
if not job:
return False, '任务不存在'
if job.job_type != 'clean':
return False, '当前任务不是 clean 类型'
version = db.session.get(KbDocumentVersion, job.document_version_id)
if not version:
job.status = 'failed'
job.error_message = '关联文档版本不存在'
job.finished_at = _utc_now()
db.session.commit()
return False, '关联文档版本不存在'
source_path = Path(version.source_file_path)
if not source_path.exists():
job.status = 'failed'
job.error_message = '原始文件不存在,无法执行 clean'
version.status = 'failed'
version.error_message = '原始文件不存在,无法执行 clean'
job.finished_at = _utc_now()
db.session.commit()
return False, '原始文件不存在'
job.status = 'running'
job.progress = 20
job.message = '开始执行最小清洗任务'
job.started_at = _utc_now()
version.status = 'processing'
db.session.commit()
target_dir = source_path.parent
warnings = []
try:
normalized_name = _normalized_source_filename(version, source_path)
staged_source = target_dir / normalized_name
if staged_source != source_path:
shutil.copy2(source_path, staged_source)
source_path = staged_source
result = build_clean_result(source_path, target_dir)
job_message = '真实清洗结果已生成'
except Exception as exc:
preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt'
preview_path.write_text(
'\n'.join([
f'source_file={source_path.name}',
f'source_size={version.source_file_size or 0}',
'clean_status=placeholder_success',
f'fallback_reason={str(exc)}',
]),
encoding='utf-8',
)
result = {
'mode': 'placeholder_clean',
'cleaned_file_path': None,
'cleaned_preview_path': str(preview_path),
'word_count': 0,
}
warnings.append({'message': f'edkb_fallback={str(exc)}'})
job_message = 'edkb_system 未就绪,已回退到占位清洗结果'
version.cleaned_file_path = result.get('cleaned_file_path')
version.cleaned_preview_path = result.get('cleaned_preview_path')
version.word_count = int(result.get('word_count') or 0)
version.status = 'cleaned'
version.converted_at = _utc_now()
version.error_message = None
version.warnings_json = warnings or None
if version.document:
version.document.status = 'ready'
job.status = 'success'
job.progress = 100
job.message = job_message
job.error_message = None
job.result_json = result
job.finished_at = _utc_now()
db.session.commit()
return True, 'ok'
def run_sync_job(job_id: int) -> tuple[bool, str]:
job = db.session.get(KbJob, job_id)
if not job:
return False, '任务不存在'
if job.job_type != 'sync_dify':
return False, '当前任务不是 sync_dify 类型'
version = db.session.get(KbDocumentVersion, job.document_version_id)
if not version:
job.status = 'failed'
job.error_message = '关联文档版本不存在'
job.finished_at = _utc_now()
db.session.commit()
return False, '关联文档版本不存在'
job.status = 'running'
job.progress = 20
job.message = '开始同步到 Dify'
job.started_at = _utc_now()
db.session.commit()
try:
result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id)
except KbDifySyncError as exc:
version.status = 'ready'
job.status = 'failed'
job.progress = 100
job.error_message = str(exc)
job.message = '同步到 Dify 失败'
job.finished_at = _utc_now()
db.session.commit()
return False, str(exc)
except Exception as exc:
version.status = 'ready'
job.status = 'failed'
job.progress = 100
job.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
job.message = '同步到 Dify 失败'
job.finished_at = _utc_now()
db.session.commit()
return False, str(exc)
version.status = 'synced'
job.status = 'success'
job.progress = 100
job.message = '已同步到 Dify'
job.error_message = None
job.result_json = result
job.finished_at = _utc_now()
db.session.commit()
return True, 'ok'
+137 -8
View File
@@ -2,13 +2,13 @@ import json
import os
import re
import time
from flask import current_app, has_app_context
from pathlib import Path
from flask import current_app
class Text2SQLService:
_schema_text = None
_oracle_client_init_attempted = False
_oracle_client_init_error = None
_oracle_client_mode = "unknown"
_oracle_client_initialized = False
_jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar"
@staticmethod
def _backend_dir() -> str:
@@ -151,6 +151,122 @@ class Text2SQLService:
text = (error_message or "").upper()
return any(code in text for code in ("ORA-00904", "ORA-00942", "INVALID IDENTIFIER", "TABLE OR VIEW DOES NOT EXIST"))
@classmethod
def _get_oracle_client_dir(cls) -> str | None:
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
if env_dir and os.path.exists(env_dir):
return env_dir
linux_candidates = [
"/opt/oracle/instantclient",
"/opt/oracle/instantclient_19_28",
"/opt/oracle/instantclient_19_27",
]
for path in linux_candidates:
if os.path.exists(path):
return path
return cls._find_oracle_client_dir()
@classmethod
def _init_oracle_client(cls, oracledb) -> None:
if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
return
import platform
import shutil
import tempfile
target_lib_dir = cls._get_oracle_client_dir()
if platform.system() == 'Windows' and target_lib_dir:
# OCI C-library fails to load if path contains non-ASCII.
if not target_lib_dir.isascii():
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
os.makedirs(temp_dir, exist_ok=True)
shutil.copytree(target_lib_dir, safe_lib_dir)
target_lib_dir = safe_lib_dir
if target_lib_dir:
oracledb.init_oracle_client(lib_dir=target_lib_dir)
else:
oracledb.init_oracle_client()
cls._oracle_client_initialized = True
@classmethod
def _jdbc_dir(cls) -> Path:
return Path(cls._backend_dir()) / "jdbc"
@classmethod
def _ensure_jdbc_driver_jar(cls) -> str:
env_path = (os.getenv("ERP_JDBC_JAR") or "").strip()
if env_path and os.path.exists(env_path):
return env_path
jar_dir = cls._jdbc_dir()
jar_dir.mkdir(parents=True, exist_ok=True)
jar_path = jar_dir / "ojdbc8-19.25.0.0.jar"
if jar_path.exists():
return str(jar_path)
import requests
driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url
with requests.get(driver_url, stream=True, timeout=120) as resp:
resp.raise_for_status()
with open(jar_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=1024 * 256):
if chunk:
f.write(chunk)
return str(jar_path)
@staticmethod
def _dsn_to_jdbc_url(dsn: str) -> str:
dsn = (dsn or "").strip()
if not dsn:
raise ValueError("ERP_DB_DSN is empty")
if dsn.startswith("jdbc:oracle:thin:@"):
return dsn
if dsn.startswith("("):
return f"jdbc:oracle:thin:@{dsn}"
match = re.match(r"^(?P<host>[^:/]+)(?::(?P<port>\d+))?/(?P<service>.+)$", dsn)
if match:
host = match.group("host")
port = match.group("port") or "1521"
service = match.group("service")
return f"jdbc:oracle:thin:@//{host}:{port}/{service}"
return f"jdbc:oracle:thin:@{dsn}"
@classmethod
def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str):
import jaydebeapi
jar_path = cls._ensure_jdbc_driver_jar()
jdbc_url = cls._dsn_to_jdbc_url(dsn)
connection = jaydebeapi.connect(
"oracle.jdbc.OracleDriver",
jdbc_url,
{
"user": user,
"password": password,
"oracle.jdbc.timezoneAsRegion": "false",
},
jar_path,
)
cursor = connection.cursor()
try:
cursor.execute(sql)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchall() if columns else []
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_schema(cls):
if cls._schema_text is None:
@@ -392,9 +508,14 @@ class Text2SQLService:
user = "EXT_VIEW_USER"
password = "extviewuser"
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
cls._ensure_oracle_client_initialized(oracledb)
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
try:
# Old ERP Oracle versions require python-oracledb thick mode.
cls._init_oracle_client(oracledb)
except Exception as e:
if current_app:
current_app.logger.warning(f"Failed to init thick mode: {e}")
try:
connection = oracledb.connect(user=user, password=password, dsn=dsn)
@@ -409,7 +530,15 @@ class Text2SQLService:
return columns, rows
except Exception as e:
return ["Error"], [[cls._format_connection_error(str(e))]]
error_text = str(e)
if current_app:
current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}")
if "DPY-3010" in error_text or "DPI-1047" in error_text:
try:
return cls._execute_sql_via_jdbc(sql, user, password, dsn)
except Exception as jdbc_error:
return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]]
return ["Error"], [[error_text]]
@classmethod
def format_result(cls, columns, rows, sql, original_query):