feat(tts): support Bailian workspace endpoints

This commit is contained in:
Jacob 2026-09-04 12:04:54 +08:00
parent eb4b28c59e
commit 935184b1d0
7 changed files with 174 additions and 4 deletions

View file

@ -0,0 +1,42 @@
-- 阿里百炼流式 TTS 支持业务空间 WebSocket 地址
UPDATE `ai_model_provider`
SET `fields` = JSON_ARRAY(
JSON_OBJECT('key', 'api_key', 'type', 'string', 'label', 'API密钥'),
JSON_OBJECT(
'key', 'ws_url',
'type', 'string',
'label', 'WebSocket地址(含Workspace ID)',
'default', 'wss://dashscope.aliyuncs.com/api-ws/v1/inference/'
),
JSON_OBJECT('key', 'output_dir', 'type', 'string', 'label', '输出目录'),
JSON_OBJECT('key', 'model', 'type', 'string', 'label', '模型'),
JSON_OBJECT('key', 'voice', 'type', 'string', 'label', '音色'),
JSON_OBJECT('key', 'format', 'type', 'string', 'label', '音频格式'),
JSON_OBJECT('key', 'sample_rate', 'type', 'number', 'label', '采样率'),
JSON_OBJECT('key', 'volume', 'type', 'number', 'label', '音量'),
JSON_OBJECT('key', 'rate', 'type', 'number', 'label', '语速'),
JSON_OBJECT('key', 'pitch', 'type', 'number', 'label', '音调')
)
WHERE `id` = 'SYSTEM_TTS_AliBLStreamTTS';
UPDATE `ai_model_config`
SET `config_json` = JSON_SET(
`config_json`,
'$.ws_url',
COALESCE(
NULLIF(JSON_UNQUOTE(JSON_EXTRACT(`config_json`, '$.ws_url')), ''),
'wss://dashscope.aliyuncs.com/api-ws/v1/inference/'
)
)
WHERE `id` = 'TTS_AliBLStreamTTS';
UPDATE `ai_model_config`
SET `remark` = '阿里百炼流式 TTS 配置说明:
1. API密钥填写当前业务空间可用的 DashScope API Key
2. 公有模式可使用 wss://dashscope.aliyuncs.com/api-ws/v1/inference/
3. 华北2(北京)业务空间填写 wss://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
4. 新加坡业务空间填写 wss://<WorkspaceId>.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
5. 将 <WorkspaceId> 替换为真实业务空间 ID;仅支持阿里云官方 WSS 推理地址
6. 支持 CosyVoice 流式合成及音量、语速、音调配置'
WHERE `id` = 'TTS_AliBLStreamTTS';

View file

@ -739,3 +739,10 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202608131030.sql
- changeSet:
id: 202609021000
author: JacobNg1
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202609021000.sql

View file

@ -1139,6 +1139,8 @@ TTS:
# cosyvoice-v3和部分音色需要申请开通
type: alibl_stream
api_key: 你的api_key
# 默认兼容旧地址;业务空间请替换为 wss://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
ws_url: wss://dashscope.aliyuncs.com/api-ws/v1/inference/
model: "cosyvoice-v2"
voice: "longcheng_v2"
output_dir: tmp/

View file

@ -11,6 +11,7 @@ from asyncio import Task
from typing import Callable, Any
from config.logger import setup_logging
from core.utils.tts import MarkdownCleaner
from core.utils.alibl_endpoint import build_ws_connect_options, resolve_ws_url
from core.providers.tts.base import TTSProviderBase
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
@ -36,7 +37,8 @@ class TTSProvider(TTSProviderBase):
self.report_on_last = True
# WebSocket配置
self.ws_url = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
self.ws_url = resolve_ws_url(config.get("ws_url"))
self.ws_connect_options = build_ws_connect_options(self.tts_timeout)
self.ws = None
self._monitor_task = None
self.activate_session = False
@ -89,6 +91,7 @@ class TTSProvider(TTSProviderBase):
ping_interval=30,
ping_timeout=10,
close_timeout=10,
**self.ws_connect_options,
)
logger.bind(tag=TAG).debug("WebSocket连接建立成功")
@ -444,6 +447,7 @@ class TTSProvider(TTSProviderBase):
ping_timeout=10,
close_timeout=10,
max_size=10 * 1024 * 1024,
**self.ws_connect_options,
)
try:
@ -556,4 +560,4 @@ class TTSProvider(TTSProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
return []
return []

View file

@ -0,0 +1,48 @@
import re
from urllib.parse import urlsplit
DEFAULT_WS_URL = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
INFERENCE_PATH = "/api-ws/v1/inference"
HOSTNAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$")
HAPPY_EYEBALLS_DELAY = 0.25
def build_ws_connect_options(open_timeout):
return {
"open_timeout": open_timeout,
"happy_eyeballs_delay": HAPPY_EYEBALLS_DELAY,
"interleave": 1,
}
def resolve_ws_url(value):
ws_url = str(value or DEFAULT_WS_URL).strip()
parsed = urlsplit(ws_url)
hostname = (parsed.hostname or "").lower()
is_dashscope = hostname in {
"dashscope.aliyuncs.com",
"dashscope-intl.aliyuncs.com",
}
is_workspace = hostname.endswith(".maas.aliyuncs.com")
try:
port = parsed.port
except ValueError:
port = -1
if (
parsed.scheme.lower() != "wss"
or not HOSTNAME_PATTERN.fullmatch(hostname)
or not (is_dashscope or is_workspace)
or parsed.path.rstrip("/") != INFERENCE_PATH
or parsed.query
or parsed.fragment
or parsed.username
or parsed.password
or port not in {None, 443}
):
raise ValueError(
"ws_url must be an official Alibaba Cloud WSS inference endpoint"
)
return ws_url

View file

@ -11,6 +11,10 @@ import asyncio
from urllib.parse import urlparse, urlencode
from tabulate import tabulate
from config.settings import load_config
from core.utils.alibl_endpoint import (
build_ws_connect_options as build_alibl_ws_connect_options,
resolve_ws_url as resolve_alibl_ws_url,
)
description = "流式TTS语音合成首词耗时测试"
class StreamTTSPerformanceTester:
@ -108,8 +112,11 @@ class StreamTTSPerformanceTester:
voice = tts_config.get("voice", "longxiaochun_v2")
format_type = tts_config.get("format", "pcm")
sample_rate = int(tts_config.get("sample_rate", "24000"))
connect_options = build_alibl_ws_connect_options(
float(self.config.get("tts_timeout", 15))
)
ws_url = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
ws_url = resolve_alibl_ws_url(tts_config.get("ws_url"))
headers = {
"Authorization": f"Bearer {api_key}",
"X-DashScope-DataInspection": "enable",
@ -124,6 +131,7 @@ class StreamTTSPerformanceTester:
ping_timeout=10,
close_timeout=10,
max_size=10 * 1024 * 1024,
**connect_options,
) as ws:
session_id = uuid.uuid4().hex
@ -669,4 +677,4 @@ async def main():
if __name__ == "__main__":
import asyncio
asyncio.run(main())
asyncio.run(main())

View file

@ -0,0 +1,59 @@
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.utils.alibl_endpoint import (
DEFAULT_WS_URL,
build_ws_connect_options,
resolve_ws_url,
)
class AliBLWorkspaceEndpointTests(unittest.TestCase):
def test_connection_uses_happy_eyeballs(self):
self.assertEqual(
build_ws_connect_options(15),
{
"open_timeout": 15,
"happy_eyeballs_delay": 0.25,
"interleave": 1,
},
)
def test_default_endpoint_remains_backward_compatible(self):
self.assertEqual(resolve_ws_url(None), DEFAULT_WS_URL)
def test_beijing_workspace_endpoint_is_supported(self):
endpoint = (
"wss://ws-123.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference"
)
self.assertEqual(resolve_ws_url(endpoint), endpoint)
def test_singapore_workspace_endpoint_is_supported(self):
endpoint = (
"wss://ws-123.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference"
)
self.assertEqual(resolve_ws_url(endpoint), endpoint)
def test_non_alibaba_endpoint_is_rejected(self):
with self.assertRaises(ValueError):
resolve_ws_url("wss://example.com/api-ws/v1/inference")
def test_insecure_endpoint_is_rejected(self):
with self.assertRaises(ValueError):
resolve_ws_url(
"ws://ws-123.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference"
)
def test_unresolved_workspace_placeholder_is_rejected(self):
with self.assertRaises(ValueError):
resolve_ws_url(
"wss://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference"
)
if __name__ == "__main__":
unittest.main()