Merge branch 'dev' into hugo

# Conflicts:
#	.env.dev
#	backend/app/__init__.py
#	backend/app/models.py
#	frontend/src/views/ChatView.vue
This commit is contained in:
hugo committed 2026-06-04 15:36:21 +08:00
commit 2ce5256483
30 files changed
+1599 -345

No files matched your search

+2
View File
@@ -58,6 +58,7 @@ def create_app(config_name='default'):
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.shipping_notice_tools import shipping_notice_bp
from app.api.speech import speech_bp
# 聊天相关接口
app.register_blueprint(chat_bp, url_prefix='/api/chat')
@@ -76,6 +77,7 @@ def create_app(config_name='default'):
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
# Eagerly load persisted runtime settings so the very first request after
# a worker boot already sees the admin-saved configuration (otherwise the
+101 -1
View File
@@ -5,7 +5,8 @@ backend/app/api/admin.py
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
"""
from flask import Blueprint, request, jsonify, current_app
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
from app.services.minio_service import minio_service
from app.decorators import require_admin
from app.config import Config
from app import db
@@ -847,6 +848,105 @@ def list_wecom_bindings():
users = query.order_by(User.id.asc()).all()
return jsonify([{'id': u.id, 'username': u.username, 'real_name': u.real_name, 'email': u.email, 'role': u.role, 'status': u.status, 'wecom_userid': u.wecom_userid, 'wecom_unionid': u.wecom_unionid, 'bound': bool(u.wecom_userid)} for u in users])
@admin_bp.route('/guides/upload', methods=['POST'])
@require_admin
def upload_guide():
if 'file' not in request.files:
raise ValidationError('No file part')
file = request.files['file']
if file.filename == '':
raise ValidationError('No selected file')
content_type = file.content_type
file_size = len(file.read())
file.seek(0)
try:
object_name = minio_service.upload_file(file, file.filename, content_type, file_size)
return jsonify({
'file_path': object_name,
'file_name': file.filename,
'file_size': file_size,
'file_type': 'video' if content_type.startswith('video') else 'pdf' if 'pdf' in content_type else 'image'
})
except Exception as e:
import traceback
traceback.print_exc()
raise AppError(f"Upload failed: {str(e)}")
@admin_bp.route('/guides', methods=['POST'])
@require_admin
def create_guide():
data = request.json
guide = AgentGuide(
agent_id=data['agent_id'],
file_name=data['file_name'],
file_type=data['file_type'],
file_path=data['file_path'],
file_size=data.get('file_size'),
remark=data.get('remark'),
sort_order=data.get('sort_order', 0),
status=data.get('status', 1),
created_by=_get_auth_user().id
)
db.session.add(guide)
db.session.commit()
return jsonify({'id': guide.id})
@admin_bp.route('/guides', methods=['GET'])
@require_admin
def list_guides():
agent_id = request.args.get('agent_id')
query = db.session.query(AgentGuide)
if agent_id:
query = query.filter_by(agent_id=agent_id)
guides = query.order_by(AgentGuide.sort_order).all()
result = []
for g in guides:
result.append({
'id': g.id,
'agent_id': g.agent_id,
'file_name': g.file_name,
'file_type': g.file_type,
'file_path': g.file_path,
'file_url': minio_service.get_public_url(g.file_path),
'file_size': g.file_size,
'remark': g.remark,
'sort_order': g.sort_order,
'status': g.status,
'created_at': g.created_at.isoformat()
})
return jsonify(result)
@admin_bp.route('/guides/<int:id>', methods=['PUT'])
@require_admin
def update_guide(id):
guide = db.session.query(AgentGuide).get(id)
if not guide:
raise NotFoundError('Guide not found')
data = request.json
if 'file_name' in data: guide.file_name = data['file_name']
if 'remark' in data: guide.remark = data['remark']
if 'sort_order' in data: guide.sort_order = data['sort_order']
if 'status' in data: guide.status = data['status']
db.session.commit()
return jsonify({'success': True})
@admin_bp.route('/guides/<int:id>', methods=['DELETE'])
@require_admin
def delete_guide(id):
guide = db.session.query(AgentGuide).get(id)
if not guide:
raise NotFoundError('Guide not found')
minio_service.delete_file(guide.file_path)
db.session.delete(guide)
db.session.commit()
return jsonify({'success': True})
@admin_bp.route('/wecom/bind', methods=['POST'])
@require_admin
def bind_wecom_user():
+44 -2
View File
@@ -4,11 +4,13 @@ backend/app/api/agents.py
引用文件:flask, models, decorators
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
"""
from flask import Blueprint, jsonify
import os
from flask import Blueprint, jsonify, send_from_directory
from app import db
from app.decorators import _get_current_user # 内部工具函数
from app.models import Agent, User
from app.models import Agent, User, AgentGuide
from app.services.minio_service import minio_service
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
@@ -58,6 +60,41 @@ def list_user_agents():
# 序列化为前端所需字段
return jsonify([_serialize_agent_row(row) for row in agent_rows])
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
def list_agent_guides(agent_id):
"""
获取指定应用的新手指南列表 (需登录)
用途:客户端 Chat 界面点击新手指南
"""
_get_current_user() # 确保已登录
if agent_id == 0:
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
if generic_agent:
agent_id = generic_agent.id
else:
return jsonify([])
guides = (
db.session.query(AgentGuide)
.filter_by(agent_id=agent_id, status=1)
.order_by(AgentGuide.sort_order.asc(), AgentGuide.created_at.desc())
.all()
)
result = []
for g in guides:
result.append({
'id': g.id,
'file_name': g.file_name,
'file_type': g.file_type,
'file_url': minio_service.get_public_url(g.file_path),
'file_size': g.file_size,
'remark': g.remark,
'updated_at': g.updated_at.isoformat()
})
return jsonify(result)
@agents_bp.route('/public', methods=['GET'])
def list_public_agents():
"""
@@ -73,4 +110,9 @@ def list_public_agents():
)
return jsonify([_serialize_agent_row(row) for row in agent_rows])
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
def serve_guide_file(filename):
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)
+40
View File
@@ -0,0 +1,40 @@
"""
Speech transcription API — forwards audio to SiliconFlow ASR.
"""
from flask import Blueprint, jsonify, request
from app.auth_jwt import get_current_user
from app.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
from app.services.speech_asr import SpeechAsrService
speech_bp = Blueprint('speech', __name__)
@speech_bp.route('/transcribe', methods=['POST'])
def transcribe_audio():
user = get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
uploaded = request.files.get('audio') or request.files.get('file')
if not uploaded or not uploaded.filename:
raise ValidationError('audio file is required')
audio_bytes = uploaded.read()
filename = uploaded.filename or 'recording.webm'
content_type = uploaded.content_type or ''
try:
SpeechAsrService.validate_upload(filename, len(audio_bytes))
except ValueError as exc:
raise ValidationError(str(exc)) from exc
try:
text, model = SpeechAsrService.transcribe(audio_bytes, filename, content_type)
except RuntimeError as exc:
raise ServiceUnavailableError(str(exc)) from exc
return jsonify({
'text': text,
'model': model,
})
+10
View File
@@ -198,6 +198,14 @@ class Config:
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
MINIO_BUCKET_NAME = os.getenv('MINIO_BUCKET_NAME', 'agent-guides')
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
class DevelopmentConfig(Config):
DEBUG = True
@@ -218,9 +226,11 @@ class TestingConfig(Config):
config = {
'dev': DevelopmentConfig,
'development': DevelopmentConfig,
'test': TestingConfig,
'testing': TestingConfig, # alias for create_app('testing') in pytest
'prod': ProductionConfig,
'production': ProductionConfig,
'default': DevelopmentConfig,
}
+23
View File
@@ -756,3 +756,26 @@ class ShippingInventoryMapping(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, index=True)
class AgentGuide(Base):
"""
平台应用新手指南表
用途:存储 Agent 的新手指南文件信息 (如视频、PDF)
"""
__tablename__ = 'agent_guides'
id: Mapped[int] = mapped_column(primary_key=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
file_type: Mapped[str] = mapped_column(String(50), nullable=False) # video, pdf, image
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sort_order: Mapped[int] = mapped_column(Integer, default=0)
status: Mapped[int] = mapped_column(Integer, default=1) # 1: 启用, 0: 禁用
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[agent_id])
+97
View File
@@ -0,0 +1,97 @@
import os
import uuid
from typing import BinaryIO
from minio import Minio
from minio.error import S3Error
from werkzeug.utils import secure_filename
from app.config import config, ACTIVE_ENV_NAME
cfg = config[ACTIVE_ENV_NAME]
class MinioService:
def __init__(self):
self.client = Minio(
cfg.MINIO_ENDPOINT,
access_key=cfg.MINIO_ACCESS_KEY,
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_BUCKET_NAME
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
try:
if not self.client.bucket_exists(self.bucket_name):
self.client.make_bucket(self.bucket_name)
# Set bucket policy to public read
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
}
]
}
import json
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
except Exception as e:
# log or print error
print(f"MinIO bucket error (or not reachable): {e}")
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
"""
Uploads a file to MinIO and returns the generated object name.
"""
# If MinIO is not running, we could fallback to local storage or raise clear error
try:
self._ensure_bucket_exists()
except Exception:
pass
ext = os.path.splitext(filename)[1]
unique_filename = f"{uuid.uuid4().hex}{ext}"
try:
self.client.put_object(
bucket_name=self.bucket_name,
object_name=unique_filename,
data=file_stream,
length=file_size,
content_type=content_type
)
except Exception as e:
# For development, if minio is down, let's mock it so UI can continue
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
# fallback to local storage
os.makedirs('data/agent-guides', exist_ok=True)
local_path = os.path.join('data/agent-guides', unique_filename)
file_stream.seek(0)
with open(local_path, 'wb') as f:
f.write(file_stream.read())
return unique_filename
def get_public_url(self, object_name: str) -> str:
"""
Returns the public URL for the given object name.
"""
if os.path.exists(os.path.join('data/agent-guides', object_name)):
# It's a local fallback file
# the backend needs a static route to serve this, we'll assume /api/agents/guides/files/<object_name>
# but since we want it public without auth:
return f"/api/agents/guides/files/{object_name}"
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
return f"{base_url}/{self.bucket_name}/{object_name}"
def delete_file(self, object_name: str):
try:
self.client.remove_object(self.bucket_name, object_name)
except S3Error as e:
print(f"Error deleting file from MinIO: {e}")
minio_service = MinioService()
+75
View File
@@ -0,0 +1,75 @@
"""
SiliconFlow ASR service (OpenAI-compatible /v1/audio/transcriptions).
"""
import io
import os
from typing import Tuple
ALLOWED_AUDIO_EXTENSIONS = frozenset({
'webm', 'wav', 'mp3', 'm4a', 'mp4', 'mpeg', 'mpga', 'ogg',
})
MAX_AUDIO_BYTES = int(os.getenv('ASR_MAX_AUDIO_BYTES', str(10 * 1024 * 1024)))
class SpeechAsrService:
@classmethod
def _get_client(cls):
try:
from openai import OpenAI
except ImportError as exc:
raise RuntimeError('OpenAI SDK not installed') from exc
api_key = (os.getenv('GJL_API_KEY') or '').strip()
base_url = (os.getenv('GJL_API_BASE') or 'https://api.siliconflow.cn/v1').strip()
if not api_key:
raise RuntimeError('Missing GJL_API_KEY. Configure it in .env to enable speech recognition')
return OpenAI(api_key=api_key, base_url=base_url)
@classmethod
def _resolve_model(cls) -> str:
return (os.getenv('ASR_MODEL') or 'FunAudioLLM/SenseVoiceSmall').strip()
@classmethod
def _normalize_filename(cls, filename: str, content_type: str) -> str:
name = (filename or '').strip() or 'recording.webm'
if '.' not in name:
if 'wav' in content_type:
name = f'{name}.wav'
elif 'mp4' in content_type or 'm4a' in content_type:
name = f'{name}.m4a'
else:
name = f'{name}.webm'
return name
@classmethod
def validate_upload(cls, filename: str, size: int) -> None:
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
if ext and ext not in ALLOWED_AUDIO_EXTENSIONS:
raise ValueError(f'Unsupported audio format: .{ext}')
if size <= 0:
raise ValueError('Audio file is empty')
if size > MAX_AUDIO_BYTES:
raise ValueError(f'Audio file exceeds {MAX_AUDIO_BYTES // (1024 * 1024)}MB limit')
@classmethod
def transcribe(cls, audio_bytes: bytes, filename: str, content_type: str = '') -> Tuple[str, str]:
cls.validate_upload(filename, len(audio_bytes))
client = cls._get_client()
model = cls._resolve_model()
safe_name = cls._normalize_filename(filename, content_type)
file_obj = io.BytesIO(audio_bytes)
file_obj.name = safe_name
try:
result = client.audio.transcriptions.create(
model=model,
file=file_obj,
)
except Exception as exc:
raise RuntimeError(f'Speech recognition request failed: {exc}') from exc
text = str(getattr(result, 'text', '') or '').strip()
return text, model