From 8f69131872cbe5c032d3159b6b91b5c9d3f05588 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Wed, 3 Jun 2026 19:24:35 +0800 Subject: [PATCH 1/6] feat(chat): add SiliconFlow ASR for agent voice input Replace Web Speech API with MediaRecorder upload to POST /api/speech/transcribe, calling SenseVoice via the existing GJL API credentials. Co-authored-by: Cursor --- .env.shared | 2 + backend/app/__init__.py | 2 + backend/app/api/speech.py | 40 ++++ backend/app/services/speech_asr.py | 75 +++++++ .../src/composables/useAudioTranscription.ts | 204 ++++++++++++++++++ .../src/composables/useSpeechRecognition.ts | 156 -------------- frontend/src/i18n.ts | 12 ++ frontend/src/types/speech-recognition.d.ts | 45 ---- frontend/src/views/ChatView.vue | 29 +-- 9 files changed, 350 insertions(+), 215 deletions(-) create mode 100644 backend/app/api/speech.py create mode 100644 backend/app/services/speech_asr.py create mode 100644 frontend/src/composables/useAudioTranscription.ts delete mode 100644 frontend/src/composables/useSpeechRecognition.ts delete mode 100644 frontend/src/types/speech-recognition.d.ts diff --git a/.env.shared b/.env.shared index a1620261..cf21c3e2 100644 --- a/.env.shared +++ b/.env.shared @@ -68,6 +68,8 @@ DIFY_API_BASE=https://api.dify.ai/v1 GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu GJL_API_BASE=https://api.siliconflow.cn/v1 GJL_MODEL=deepseek-ai/DeepSeek-V3 +# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR +ASR_MODEL=FunAudioLLM/SenseVoiceSmall # HR SQL Server Configuration HR_SQLSERVER_HOST=192.168.100.191 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index f7762e24..0f67bc06 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -56,6 +56,7 @@ def create_app(config_name='default'): from app.api.schedule_admin import schedule_admin_bp from app.api.workspace_schedule import workspace_schedule_bp from app.api.internal_jobs import internal_jobs_bp + from app.api.speech import speech_bp # 聊天相关接口 app.register_blueprint(chat_bp, url_prefix='/api/chat') @@ -72,6 +73,7 @@ def create_app(config_name='default'): app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') + 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 diff --git a/backend/app/api/speech.py b/backend/app/api/speech.py new file mode 100644 index 00000000..95e9d0d2 --- /dev/null +++ b/backend/app/api/speech.py @@ -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, + }) diff --git a/backend/app/services/speech_asr.py b/backend/app/services/speech_asr.py new file mode 100644 index 00000000..750482cc --- /dev/null +++ b/backend/app/services/speech_asr.py @@ -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 diff --git a/frontend/src/composables/useAudioTranscription.ts b/frontend/src/composables/useAudioTranscription.ts new file mode 100644 index 00000000..fbaab8fd --- /dev/null +++ b/frontend/src/composables/useAudioTranscription.ts @@ -0,0 +1,204 @@ +import { ref, computed, onBeforeUnmount } from 'vue'; +import { getAuthHeaders } from '../utils/auth'; + +export type AudioTranscriptionErrorKey = + | 'chat.voiceRequiresHttps' + | 'chat.voiceNotSupported' + | 'chat.voicePermissionDenied' + | 'chat.voiceRecordTooShort' + | 'chat.voiceTranscriptionFailed'; + +const isSecureContextForMic = (): boolean => { + if (typeof window === 'undefined') return false; + if (window.isSecureContext) return true; + const host = window.location.hostname; + return host === 'localhost' || host === '127.0.0.1'; +}; + +const canUseMediaRecorder = (): boolean => { + if (typeof window === 'undefined') return false; + return Boolean(window.MediaRecorder && navigator.mediaDevices?.getUserMedia); +}; + +export const getVoiceUnavailableErrorKey = (): AudioTranscriptionErrorKey | null => { + if (!isSecureContextForMic()) return 'chat.voiceRequiresHttps'; + if (!canUseMediaRecorder()) return 'chat.voiceNotSupported'; + return null; +}; + +const pickMimeType = (): string => { + const candidates = [ + 'audio/webm;codecs=opus', + 'audio/webm', + 'audio/mp4', + 'audio/ogg;codecs=opus', + ]; + for (const type of candidates) { + if (MediaRecorder.isTypeSupported(type)) return type; + } + return ''; +}; + +export function useAudioTranscription(options: { + onResult: (text: string) => void; + onError: (key: AudioTranscriptionErrorKey) => void; +}) { + const isRecording = ref(false); + const isTranscribing = ref(false); + const isSupported = computed(() => getVoiceUnavailableErrorKey() === null); + const isBusy = computed(() => isRecording.value || isTranscribing.value); + + let mediaStream: MediaStream | null = null; + let mediaRecorder: MediaRecorder | null = null; + let chunks: Blob[] = []; + let baseText = ''; + let skipTranscription = false; + + const cleanupStream = () => { + if (mediaStream) { + mediaStream.getTracks().forEach((track) => track.stop()); + mediaStream = null; + } + mediaRecorder = null; + chunks = []; + }; + + const stopRecording = () => { + if (mediaRecorder && mediaRecorder.state !== 'inactive') { + mediaRecorder.stop(); + return; + } + isRecording.value = false; + cleanupStream(); + }; + + const transcribeBlob = async (blob: Blob, mimeType: string) => { + if (blob.size < 800) { + options.onError('chat.voiceRecordTooShort'); + return; + } + + isTranscribing.value = true; + try { + const ext = mimeType.includes('mp4') ? 'm4a' : 'webm'; + const formData = new FormData(); + formData.append('audio', blob, `recording.${ext}`); + + const response = await fetch('/api/speech/transcribe', { + method: 'POST', + headers: { ...getAuthHeaders() }, + body: formData, + }); + + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + const errMsg = payload?.error?.message || payload?.message || `Request failed (${response.status})`; + throw new Error(errMsg); + } + + const text = String(payload.text || '').trim(); + if (!text) { + options.onError('chat.voiceRecordTooShort'); + return; + } + + const prefix = baseText.trim(); + options.onResult(prefix ? `${prefix} ${text}` : text); + } catch { + options.onError('chat.voiceTranscriptionFailed'); + } finally { + isTranscribing.value = false; + } + }; + + const startRecording = async (existingText = '') => { + if (isBusy.value) return; + + const unavailable = getVoiceUnavailableErrorKey(); + if (unavailable) { + options.onError(unavailable); + return; + } + + baseText = existingText; + + try { + mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true }); + } catch (err) { + const denied = err instanceof DOMException && ( + err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError' + ); + options.onError(denied ? 'chat.voicePermissionDenied' : 'chat.voiceTranscriptionFailed'); + return; + } + + chunks = []; + const mimeType = pickMimeType(); + try { + mediaRecorder = mimeType + ? new MediaRecorder(mediaStream, { mimeType }) + : new MediaRecorder(mediaStream); + } catch { + cleanupStream(); + options.onError('chat.voiceNotSupported'); + return; + } + + mediaRecorder.ondataavailable = (event) => { + if (event.data.size > 0) chunks.push(event.data); + }; + + mediaRecorder.onstop = async () => { + isRecording.value = false; + const type = mediaRecorder?.mimeType || mimeType || 'audio/webm'; + const blob = new Blob(chunks, { type }); + const shouldSkip = skipTranscription; + skipTranscription = false; + cleanupStream(); + if (shouldSkip) return; + await transcribeBlob(blob, type); + }; + + mediaRecorder.onerror = () => { + isRecording.value = false; + cleanupStream(); + options.onError('chat.voiceTranscriptionFailed'); + }; + + mediaRecorder.start(); + isRecording.value = true; + }; + + const toggle = (existingText = '') => { + if (isTranscribing.value) return; + if (isRecording.value) { + stopRecording(); + return; + } + void startRecording(existingText); + }; + + const cancel = () => { + skipTranscription = true; + if (mediaRecorder && mediaRecorder.state !== 'inactive') { + mediaRecorder.stop(); + } else { + cleanupStream(); + } + isRecording.value = false; + isTranscribing.value = false; + }; + + onBeforeUnmount(cancel); + + return { + isRecording, + isTranscribing, + isSupported, + isBusy, + startRecording, + stopRecording, + toggle, + cancel, + }; +} diff --git a/frontend/src/composables/useSpeechRecognition.ts b/frontend/src/composables/useSpeechRecognition.ts deleted file mode 100644 index 39a68a2e..00000000 --- a/frontend/src/composables/useSpeechRecognition.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { ref, computed, onBeforeUnmount, type Ref } from 'vue'; - -export type SpeechRecognitionErrorKey = - | 'chat.voiceNotSupported' - | 'chat.voiceRequiresHttps' - | 'chat.voicePermissionDenied' - | 'chat.voiceNoSpeech' - | 'chat.voiceAudioCapture' - | 'chat.voiceNetworkError' - | 'chat.voiceServiceNotAllowed' - | 'chat.voiceRecognitionFailed'; - -type SpeechRecognitionCtor = new () => SpeechRecognition; - -const getSpeechRecognitionCtor = (): SpeechRecognitionCtor | null => { - if (typeof window === 'undefined') return null; - const w = window as Window & { - SpeechRecognition?: SpeechRecognitionCtor; - webkitSpeechRecognition?: SpeechRecognitionCtor; - }; - return w.SpeechRecognition || w.webkitSpeechRecognition || null; -}; - -export const mapLocaleToSpeechLang = (locale: string): string => { - const map: Record = { - 'zh-CN': 'zh-CN', - 'zh-TW': 'zh-TW', - en: 'en-US', - th: 'th-TH', - }; - return map[locale] || 'zh-CN'; -}; - -const isSecureContextForSpeech = (): boolean => { - if (typeof window === 'undefined') return false; - if (window.isSecureContext) return true; - const host = window.location.hostname; - return host === 'localhost' || host === '127.0.0.1'; -}; - -/** 语音不可用时的提示 key;HTTPS/localhost 且浏览器有 API 时返回 null */ -export const getVoiceUnavailableErrorKey = (): SpeechRecognitionErrorKey | null => { - if (!isSecureContextForSpeech()) return 'chat.voiceRequiresHttps'; - if (!getSpeechRecognitionCtor()) return 'chat.voiceNotSupported'; - return null; -}; - -const mapErrorToKey = (error: string): SpeechRecognitionErrorKey => { - switch (error) { - case 'not-allowed': - return 'chat.voicePermissionDenied'; - case 'service-not-allowed': - return 'chat.voiceServiceNotAllowed'; - case 'no-speech': - return 'chat.voiceNoSpeech'; - case 'audio-capture': - return 'chat.voiceAudioCapture'; - case 'network': - return 'chat.voiceNetworkError'; - default: - return 'chat.voiceRecognitionFailed'; - } -}; - -export function useSpeechRecognition(options: { - lang: Ref; - onResult: (text: string) => void; - onError: (key: SpeechRecognitionErrorKey) => void; -}) { - const isListening = ref(false); - const isSupported = computed(() => getVoiceUnavailableErrorKey() === null); - - let recognition: SpeechRecognition | null = null; - let baseText = ''; - - const stop = () => { - if (recognition) { - try { - recognition.abort(); - } catch { - // ignore abort errors - } - recognition = null; - } - isListening.value = false; - }; - - const start = (existingText = '') => { - if (isListening.value) return; - - const unavailable = getVoiceUnavailableErrorKey(); - if (unavailable) { - options.onError(unavailable); - return; - } - - const Ctor = getSpeechRecognitionCtor()!; - - stop(); - baseText = existingText; - - const instance = new Ctor(); - instance.continuous = true; - instance.interimResults = true; - instance.lang = mapLocaleToSpeechLang(options.lang.value); - - instance.onstart = () => { - isListening.value = true; - }; - - instance.onresult = (event: SpeechRecognitionEvent) => { - let sessionTranscript = ''; - for (let i = 0; i < event.results.length; i++) { - sessionTranscript += event.results[i]?.[0]?.transcript || ''; - } - options.onResult(`${baseText}${sessionTranscript}`); - }; - - instance.onerror = (event: SpeechRecognitionErrorEvent) => { - if (event.error === 'aborted') return; - options.onError(mapErrorToKey(event.error)); - stop(); - }; - - instance.onend = () => { - isListening.value = false; - recognition = null; - }; - - recognition = instance; - try { - recognition.start(); - } catch { - options.onError('chat.voiceRecognitionFailed'); - stop(); - } - }; - - const toggle = (existingText = '') => { - if (isListening.value) { - stop(); - return; - } - start(existingText); - }; - - onBeforeUnmount(stop); - - return { - isListening, - isSupported, - start, - stop, - toggle, - }; -} diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 9d85770e..489ee9b4 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -1267,6 +1267,9 @@ const messages = { voiceNetworkError: 'Voice recognition network error', voiceServiceNotAllowed: 'Voice recognition service is not allowed', voiceRecognitionFailed: 'Voice recognition failed. Please try again', + voiceTranscribing: 'Transcribing...', + voiceRecordTooShort: 'Recording too short or no speech detected', + voiceTranscriptionFailed: 'Speech recognition failed. Please try again', collapseBrowser: 'Collapse Browser', openBrowser: 'Open Browser', kb: { @@ -2737,6 +2740,9 @@ const messages = { voiceNetworkError: '语音识别网络错误', voiceServiceNotAllowed: '不允许使用语音识别服务', voiceRecognitionFailed: '语音识别失败,请重试', + voiceTranscribing: '正在识别…', + voiceRecordTooShort: '录音太短或未检测到语音', + voiceTranscriptionFailed: '语音识别失败,请重试', collapseBrowser: '收起浏览器', openBrowser: '打开浏览器', kb: { @@ -4066,6 +4072,9 @@ const messages = { voiceNetworkError: '語音辨識網路錯誤', voiceServiceNotAllowed: '不允許使用語音辨識服務', voiceRecognitionFailed: '語音辨識失敗,請重試', + voiceTranscribing: '正在辨識…', + voiceRecordTooShort: '錄音太短或未偵測到語音', + voiceTranscriptionFailed: '語音辨識失敗,請重試', collapseBrowser: '收起瀏覽器', openBrowser: '打開瀏覽器', kb: { @@ -5312,6 +5321,9 @@ const messages = { voiceNetworkError: 'เกิดข้อผิดพลาดเครือข่ายในการรู้จำเสียง', voiceServiceNotAllowed: 'ไม่อนุญาตให้ใช้บริการรู้จำเสียง', voiceRecognitionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง', + voiceTranscribing: 'กำลังแปลงเสียง...', + voiceRecordTooShort: 'การบันทึกสั้นเกินไปหรือไม่พบเสียงพูด', + voiceTranscriptionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง', collapseBrowser: 'ย่อเบราว์เซอร์', openBrowser: 'เปิดเบราว์เซอร์', kb: { diff --git a/frontend/src/types/speech-recognition.d.ts b/frontend/src/types/speech-recognition.d.ts deleted file mode 100644 index 239add32..00000000 --- a/frontend/src/types/speech-recognition.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -interface SpeechRecognitionAlternative { - transcript: string; - confidence: number; -} - -interface SpeechRecognitionResult { - readonly isFinal: boolean; - readonly length: number; - item(index: number): SpeechRecognitionAlternative; - [index: number]: SpeechRecognitionAlternative; -} - -interface SpeechRecognitionResultList { - readonly length: number; - item(index: number): SpeechRecognitionResult; - [index: number]: SpeechRecognitionResult; -} - -interface SpeechRecognitionEvent extends Event { - readonly resultIndex: number; - readonly results: SpeechRecognitionResultList; -} - -interface SpeechRecognitionErrorEvent extends Event { - readonly error: string; - readonly message: string; -} - -interface SpeechRecognition extends EventTarget { - continuous: boolean; - interimResults: boolean; - lang: string; - start(): void; - stop(): void; - abort(): void; - onstart: ((this: SpeechRecognition, ev: Event) => void) | null; - onend: ((this: SpeechRecognition, ev: Event) => void) | null; - onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null; - onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null; -} - -interface Window { - SpeechRecognition?: new () => SpeechRecognition; - webkitSpeechRecognition?: new () => SpeechRecognition; -} diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 4f9298ff..d87599d4 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -21,7 +21,7 @@ import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue'; import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue'; import { useMessage } from '../composables/useMessage'; import { useIsMobile } from '../composables/useIsMobile'; -import { getVoiceUnavailableErrorKey, useSpeechRecognition } from '../composables/useSpeechRecognition'; +import { getVoiceUnavailableErrorKey, useAudioTranscription } from '../composables/useAudioTranscription'; import { useTheme } from '../composables/useTheme'; import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth'; import { copyTextToClipboard } from '../utils/clipboard'; @@ -664,11 +664,11 @@ const copiedIndex = ref(null); const { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage } = useChat(); const input = ref(''); const { - isListening: isVoiceListening, + isRecording: isVoiceRecording, + isTranscribing: isVoiceTranscribing, toggle: toggleVoiceInput, - stop: stopVoiceInput, -} = useSpeechRecognition({ - lang: locale, + cancel: cancelVoiceInput, +} = useAudioTranscription({ onResult: (text) => { input.value = text; }, @@ -678,7 +678,7 @@ const { }); const handleVoiceFeatureClick = () => { - if (isThinking.value) return; + if (isThinking.value || isVoiceTranscribing.value) return; const unavailable = getVoiceUnavailableErrorKey(); if (unavailable) { msg.warning(t(unavailable)); @@ -688,7 +688,7 @@ const handleVoiceFeatureClick = () => { }; watch(isThinking, (thinking) => { - if (thinking) stopVoiceInput(); + if (thinking) cancelVoiceInput(); }); const currentAgent = ref(null); @@ -2484,7 +2484,7 @@ const syncChatStateForRoute = async () => { const syncToken = ++routeSyncToken; resetChatStateForAgentChange(); - stopVoiceInput(); + cancelVoiceInput(); setLastChatAgentId(agentId); syncOpenAgentRegistration(); @@ -3285,10 +3285,10 @@ const showChatRating = ref(false); v-model="input" @keydown.enter.prevent="handleSend" rows="1" - :placeholder="isVoiceListening ? $t('chat.voiceListening') : $t('chat.askAnything')" + :placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')" class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent" style="min-height: 44px; max-height: 220px;" - :disabled="isThinking" + :disabled="isThinking || isVoiceTranscribing" spellcheck="false" autocorrect="off" autocapitalize="off" @@ -3323,12 +3323,13 @@ const showChatRating = ref(false);
- +
-
+
From f8de4630a556075dc0f84be193d7efcd08cb1706 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Thu, 4 Jun 2026 12:47:21 +0800 Subject: [PATCH 4/6] =?UTF-8?q?feat=EF=BC=9A=201.=20=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=90=8E=E5=8F=B0=E6=94=AF=E6=8C=81=E4=B8=BA=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=20Agent=20=E5=BA=94=E7=94=A8=E4=B8=8A=E4=BC=A0=E5=92=8C?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E8=A7=86=E9=A2=91=E3=80=81PDF=20=E7=AD=89?= =?UTF-8?q?=E6=96=B0=E6=89=8B=E6=8C=87=E5=8D=97=E8=B5=84=E6=96=99=E3=80=82?= =?UTF-8?q?=202.=20=E5=89=8D=E7=AB=AF=E8=81=8A=E5=A4=A9=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E5=90=8E=E5=8F=B0=E9=85=8D=E7=BD=AE=EF=BC=8C?= =?UTF-8?q?=E5=8A=A8=E6=80=81=E5=B1=95=E7=A4=BA=E2=80=9C=E6=96=B0=E6=89=8B?= =?UTF-8?q?=E6=8C=87=E5=8D=97=E2=80=9D=E5=85=A5=E5=8F=A3=E3=80=82=203.=20?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=82=B9=E5=87=BB=E5=90=8E=E5=8F=AF=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E5=9C=A8=E7=B3=BB=E7=BB=9F=E5=86=85=E9=A2=84=E8=A7=88?= =?UTF-8?q?=E8=A7=86=E9=A2=91=E6=88=96=20PDF=20=E6=96=87=E6=A1=A3=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.dev | 5 +- backend/app/api/admin.py | 102 +++++- backend/app/api/agents.py | 46 ++- backend/app/config.py | 10 + backend/app/models.py | 23 ++ .../f6f91cb46944_add_agent_guides_table.py | 74 ++++ backend/requirements.txt | 2 +- docs/demand.md | 33 ++ docs/funclist.md | 27 ++ docs/tec.md | 44 +++ frontend/src/api/admin.ts | 30 ++ frontend/src/api/user.ts | 2 + .../src/app/router/routes/admin.routes.ts | 328 ++++++++++++------ frontend/src/config.ts | 1 + .../features/admin/components/AdminNav.vue | 3 +- .../src/features/admin/constants/modules.ts | 3 +- .../src/features/admin/types/admin.types.ts | 1 + frontend/src/i18n.ts | 5 +- frontend/src/views/ChatView.vue | 125 ++++++- 19 files changed, 742 insertions(+), 122 deletions(-) create mode 100644 backend/migrations/versions/f6f91cb46944_add_agent_guides_table.py diff --git a/.env.dev b/.env.dev index 5ac490a6..d4990ec8 100644 --- a/.env.dev +++ b/.env.dev @@ -48,9 +48,10 @@ GUNICORN_WORKERS=10 # MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO) # 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000 # 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致 -MINIO_ENDPOINT=host.docker.internal:9000 +MINIO_ENDPOINT=127.0.0.1:9000 MINIO_BUCKET=image-hosting-service MINIO_ACCESS_KEY=minio_testing_admin MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx MINIO_SECURE=false -MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 +MINIO_PUBLIC_BASE_URL=http://127.0.0.1:9000 +#MINIO_PUBLIC_BASE_URL=http://192.168.1.100/HX工作目录/0602/hxops/backend/data diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 4c1dce56..7bb86df6 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -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/', 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/', 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(): diff --git a/backend/app/api/agents.py b/backend/app/api/agents.py index 650e1a96..d9a1633f 100644 --- a/backend/app/api/agents.py +++ b/backend/app/api/agents.py @@ -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('//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/', methods=['GET']) +def serve_guide_file(filename): + return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename) + diff --git a/backend/app/config.py b/backend/app/config.py index e4bde29b..5d1921de 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -160,6 +160,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 @@ -180,9 +188,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, } diff --git a/backend/app/models.py b/backend/app/models.py index 6f8ca90c..be24f758 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -679,3 +679,26 @@ class ScheduleRun(Base): task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id]) +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]) + + diff --git a/backend/migrations/versions/f6f91cb46944_add_agent_guides_table.py b/backend/migrations/versions/f6f91cb46944_add_agent_guides_table.py new file mode 100644 index 00000000..bed4e28f --- /dev/null +++ b/backend/migrations/versions/f6f91cb46944_add_agent_guides_table.py @@ -0,0 +1,74 @@ +"""add agent_guides table + +Revision ID: f6f91cb46944 +Revises: d0e1f2a3b4c5 +Create Date: 2026-06-04 09:32:18.390108 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f6f91cb46944' +down_revision = 'd0e1f2a3b4c5' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('agent_guides', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('agent_id', sa.Integer(), nullable=False), + sa.Column('file_name', sa.String(length=255), nullable=False), + sa.Column('file_type', sa.String(length=50), nullable=False), + sa.Column('file_path', sa.String(length=500), nullable=False), + sa.Column('file_size', sa.Integer(), nullable=True), + sa.Column('remark', sa.Text(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('status', sa.Integer(), nullable=False), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('agent_guides', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_agent_guides_agent_id'), ['agent_id'], unique=False) + + with op.batch_alter_table('schedule_runs', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_schedule_runs_id')) + + with op.batch_alter_table('schedule_tasks', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_schedule_tasks_id')) + + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('uq_users_wecom_unionid')) + batch_op.drop_index(batch_op.f('uq_users_wecom_userid')) + batch_op.create_unique_constraint(None, ['wecom_unionid']) + batch_op.create_unique_constraint(None, ['wecom_userid']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='unique') + batch_op.drop_constraint(None, type_='unique') + batch_op.create_index(batch_op.f('uq_users_wecom_userid'), ['wecom_userid'], unique=True) + batch_op.create_index(batch_op.f('uq_users_wecom_unionid'), ['wecom_unionid'], unique=True) + + with op.batch_alter_table('schedule_tasks', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_schedule_tasks_id'), ['id'], unique=False) + + with op.batch_alter_table('schedule_runs', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_schedule_runs_id'), ['id'], unique=False) + + with op.batch_alter_table('agent_guides', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_agent_guides_agent_id')) + + op.drop_table('agent_guides') + # ### end Alembic commands ### diff --git a/backend/requirements.txt b/backend/requirements.txt index c6acd8ae..99abc2e2 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -35,4 +35,4 @@ lxml==6.0.2 typer==0.17.4 croniter pyyaml -minio>=7.2.0 +minio==7.2.20 diff --git a/docs/demand.md b/docs/demand.md index eb592514..475bb082 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -336,3 +336,36 @@ 5. 移动端右上角可见个人设置图标按钮 6. 点击右上角按钮可进入个人设置页面 7. PC 端布局与行为无任何变化 + + +--- + +## 15. 平台应用新手指南需求 + +### 15.1 项目背景 + +目前用户在使用部分复杂的 Agent 应用时,由于缺乏直观的操作引导,容易产生困惑。通过在应用内提供视频、PDF 等多媒体说明文档,可以实现“即学即用”,降低用户学习成本。 + +### 15.2 需求目标 + +1. 管理后台支持为不同 Agent 应用上传和管理视频、PDF 等新手指南资料。 +2. 前端聊天界面根据后台配置,动态展示“新手指南”入口。 +3. 用户点击后可直接在系统内预览视频或 PDF 文档。 + +### 15.3 详细需求 + +#### NR-01 管理后台-平台应用说明管理 +- 支持选择系统内已发布的 Agent 应用。 +- 支持上传视频(MP4/WebM)和文档(PDF),上传至 MinIO(mimo)服务。 +- 维护资料信息:名称、备注、状态(启用/禁用)、排序等。 + +#### NR-02 客户端-新手指南入口与展示 +- 在 Chat 对话界面的左上角(应用 Title 旁边),新增【新手指南】按钮。 +- 根据后台接口返回,若存在启用状态的指南,则显示入口,否则隐藏。 +- 点击后弹出预览浮层(Modal/Drawer),支持多文件标签页切换。 +- 弹窗内直接内联播放视频或渲染 PDF(无需下载)。 + +### 15.4 验收标准 +1. 管理员能成功上传并管理应用的指南文件。 +2. 客户端正确根据配置动态展示或隐藏入口。 +3. 客户端能正常播放指南视频和预览 PDF 文档。 diff --git a/docs/funclist.md b/docs/funclist.md index ae726b9d..457de7db 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -377,3 +377,30 @@ - 点击右上角按钮可进入个人设置页面 - PC 端布局与行为无任何变化 - 旋转屏幕后布局实时切换 + + +--- + +## 8. 新手指南功能清单 + +### 8.1 功能总览 + +| 功能项 | 说明 | 状态 | 优先级 | +| --- | --- | --- | --- | +| 指南资料上传与管理 | 管理台上传视频、PDF,并关联 Agent,支持启用/禁用 | 待建设 | P0 | +| 客户端动态入口 | 聊天页左上角动态获取并展示“新手指南”按钮 | 待建设 | P0 | +| 指南预览弹窗 | 客户端弹窗内嵌播放视频、渲染 PDF,支持多文件切换 | 待建设 | P0 | + +### 8.2 详细功能拆分 + +#### F-11 指南资料上传与管理 (Admin) +- **目标**:管理员为 Agent 配置多媒体指南。 +- **功能点**:文件直传 MinIO (mimo服务),数据保存至 PostgreSQL `agent_guides` 表;支持资料的增删改查、排序和状态切换。 + +#### F-12 客户端动态入口 (Client) +- **目标**:根据当前 Agent 是否有指南资料动态显示入口。 +- **功能点**:进入对话页面时请求指南列表接口,有数据则渲染【新手指南】按钮。 + +#### F-13 指南预览弹窗 (Client) +- **目标**:用户在聊天界面快速查阅指南。 +- **功能点**:视频使用 HTML5 播放器,PDF 使用 `@vue-office/pdf` 渲染,支持 Tabs 切换多份指南。 diff --git a/docs/tec.md b/docs/tec.md index eb8f5cea..9852b9ab 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -731,3 +731,47 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth; - 所有移动端适配逻辑均以 `v-if="isMobile"` 或三元表达式控制,`isMobile` 在 PC 横屏时始终为 `false` - 路由守卫对 `/workspace` 等直接访问不做拦截,PC 端行为不变 - PC 端侧边栏、导航栏、布局结构无任何 CSS 或 DOM 变更 + + +--- + +## 17. 平台应用新手指南技术架构 + +### 17.1 整体技术栈 +- **前端**:Vue 3 + TailwindCSS,原生 `
- {{ currentAgent?.name || 'AI' }} +
+ {{ currentAgent?.name || 'AI' }} + +
我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。 @@ -2783,6 +2821,14 @@ const showChatRating = ref(false);
AI
{{ currentAgent?.name || 'AI' }} +
+
+ +
+
+ +
+
+ +
+ +
+ +
+ +

请选择左侧指南进行查阅

+
+
+
+ + + +