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 <cursoragent@cursor.com>
This commit is contained in:
sophieandCursor committed 2026-06-03 19:24:35 +08:00
1 parent 445763e144
commit 8f69131872
9 files changed
+350 -215

No files matched your search

+2
View File
@@ -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
+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,
})
+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