DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(media): add DashScope providers (#1016)
XZHd9538192d204
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex fdb24566e..28e6ad192 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -299,10 +299,16 @@ class VoiceProviderSpec:is_local: bool = False-# Voice providers in the OpenAI-compatible cluster. A single adapter covers all-# of these; bespoke providers (DashScope native, ElevenLabs, Gemini, Deepgram)-# would register their own ``adapter`` value once implemented.+# Voice providers either use the shared OpenAI-compatible adapter or a native+# protocol adapter registered by name (currently DashScope TTS/STT).TTS_PROVIDERS: dict[str, VoiceProviderSpec] = {+ "dashscope": VoiceProviderSpec(+ label="Aliyun DashScope",+ default_api_base="https://dashscope.aliyuncs.com/api/v1",+ adapter="dashscope",+ default_model="qwen3-tts-flash",+ default_voice="Cherry",+ ),"openai": VoiceProviderSpec(label="OpenAI",default_api_base="https://api.openai.com/v1",@@ -351,6 +357,12 @@ TTS_PROVIDERS: dict[str, VoiceProviderSpec] = {}STT_PROVIDERS: dict[str, VoiceProviderSpec] = {+ "dashscope": VoiceProviderSpec(+ label="Aliyun DashScope",+ default_api_base="https://dashscope.aliyuncs.com/api/v1",+ adapter="dashscope",+ default_model="paraformer-v2",+ ),"openai": VoiceProviderSpec(label="OpenAI",default_api_base="https://api.openai.com/v1",@@ -393,6 +405,8 @@ STT_PROVIDERS: dict[str, VoiceProviderSpec] = {# Provider-name aliases accepted from older/loose catalog values.VOICE_PROVIDER_ALIASES = {+ "aliyun": "dashscope",+ "bailian": "dashscope","azure": "azure_openai","aoai": "azure_openai","openai_compatible": "custom",@@ -429,6 +443,12 @@ class GenerationProviderSpec:# Image-generation providers in the OpenAI-compatible cluster. A single adapter# covers all of these; ``default_model`` is only a Settings prefill hint.IMAGEGEN_PROVIDERS: dict[str, GenerationProviderSpec] = {+ "dashscope": GenerationProviderSpec(+ label="Aliyun DashScope",+ default_api_base="https://dashscope.aliyuncs.com/api/v1",+ adapter="dashscope",+ default_model="wanx2.1-t2i-turbo",+ ),"openai": GenerationProviderSpec(label="OpenAI",default_api_base="https://api.openai.com/v1",@@ -475,6 +495,12 @@ IMAGEGEN_PROVIDERS: dict[str, GenerationProviderSpec] = {# Video-generation providers. Text-to-video has no synchronous standard; these# all use the async-task adapter (submit → poll → download).VIDEOGEN_PROVIDERS: dict[str, GenerationProviderSpec] = {+ "dashscope": GenerationProviderSpec(+ label="Aliyun DashScope",+ default_api_base="https://dashscope.aliyuncs.com/api/v1",+ adapter="dashscope",+ default_model="wanx2.1-t2v-turbo",+ ),"volcengine": GenerationProviderSpec(label="Volcengine Ark (Seedance)",default_api_base="https://ark.cn-beijing.volces.com/api/v3",@@ -491,6 +517,8 @@ VIDEOGEN_PROVIDERS: dict[str, GenerationProviderSpec] = {# Provider-name aliases accepted from older/loose catalog values.GENERATION_PROVIDER_ALIASES = {+ "aliyun": "dashscope",+ "bailian": "dashscope","ark": "volcengine","volces": "volcengine","doubao": "volcengine",diff --git a/deeptutor/services/imagegen/adapters/__init__.py b/deeptutor/services/imagegen/adapters/__init__.pyindex caedc6ba4..114857bb8 100644--- a/deeptutor/services/imagegen/adapters/__init__.py+++ b/deeptutor/services/imagegen/adapters/__init__.py@@ -9,6 +9,7 @@ from __future__ import annotationsfrom deeptutor.services.generation_http import GenerationProviderErrorfrom deeptutor.services.imagegen.adapters.chat_completions import ChatCompletionsImagegenAdapter+from deeptutor.services.imagegen.adapters.dashscope import DashScopeImagegenAdapterfrom deeptutor.services.imagegen.adapters.openai_compat import OpenAICompatImagegenAdapterfrom deeptutor.services.imagegen.base import BaseImagegenAdapter@@ -17,6 +18,7 @@ IMAGEGEN_ADAPTERS: dict[str, BaseImagegenAdapter] = {"openai_compat": OpenAICompatImagegenAdapter(),# Chat-completions image output (OpenRouter Flux / Gemini image, …)."chat_completions": ChatCompletionsImagegenAdapter(),+ "dashscope": DashScopeImagegenAdapter(),}@@ -27,4 +29,8 @@ def get_imagegen_adapter(name: str) -> BaseImagegenAdapter:return adapter-__all__ = ["IMAGEGEN_ADAPTERS", "get_imagegen_adapter"]+__all__ = [+ "IMAGEGEN_ADAPTERS",+ "get_imagegen_adapter",+ "DashScopeImagegenAdapter",+]diff --git a/deeptutor/services/imagegen/adapters/dashscope.py b/deeptutor/services/imagegen/adapters/dashscope.pynew file mode 100644index 000000000..85e306590--- /dev/null+++ b/deeptutor/services/imagegen/adapters/dashscope.py@@ -0,0 +1,143 @@+"""Aliyun DashScope native text-to-image adapter."""++from __future__ import annotations++import asyncio+import logging+import time+from typing import Any++import httpx++from deeptutor.services.generation_http import (+ GenerationProviderError,+ build_auth_headers,+ join_api_path,+ raise_for_provider,+)+from deeptutor.services.imagegen.base import BaseImagegenAdapter+from deeptutor.services.imagegen.config import ImagegenConfig++logger = logging.getLogger(__name__)++_SUBMIT_PATH = "services/aigc/image-synthesis"+++class DashScopeImagegenAdapter(BaseImagegenAdapter):+ """Submit a DashScope image task, poll it, and materialize image bytes."""++ async def generate(+ self, prompt: str, config: ImagegenConfig, *, n: int = 1+ ) -> list[tuple[bytes, str]]:+ if not config.base_url:+ raise GenerationProviderError("No endpoint URL configured for image generation.")+ headers = self._headers(config)+ payload = self._submit_payload(prompt, config, n=max(1, n))+ submit_url = join_api_path(config.base_url, _SUBMIT_PATH)+ logger.debug("DashScope image submit url=%s model=%s", submit_url, config.model)+ try:+ async with httpx.AsyncClient(timeout=config.request_timeout) as client:+ resp = await client.post(submit_url, headers=headers, json=payload)+ raise_for_provider(resp, "DashScope image task submission")+ task_id = self._task_id(resp)+ results = await self._poll(client, config, headers, task_id)+ images = []+ for result in results:+ images.append(await self._materialize(client, result))+ except httpx.HTTPError as exc:+ raise GenerationProviderError(f"DashScope image request error: {exc}") from exc+ if not images:+ raise GenerationProviderError("DashScope image task returned no images.")+ return images++ @staticmethod+ def _headers(config: ImagegenConfig) -> dict[str, str]:+ return {+ "Content-Type": "application/json",+ "X-DashScope-Async": "enable",+ **build_auth_headers(config.auth_style, config.api_key),+ **(config.extra_headers or {}),+ }++ @staticmethod+ def _submit_payload(prompt: str, config: ImagegenConfig, *, n: int) -> dict[str, Any]:+ parameters: dict[str, Any] = {"n": max(1, n)}+ if config.size:+ parameters["size"] = config.size.lower().replace("x", "*")+ if config.style:+ parameters["style"] = config.style+ return {+ "model": config.model,+ "input": {"prompt": prompt},+ "parameters": parameters,+ }++ @staticmethod+ def _raise_dashscope_error(data: dict[str, Any], action: str) -> None:+ if data.get("code") not in (None, "", 0, "0") or data.get("success") is False:+ code = data.get("code") or "unknown"+ message = data.get("message") or "no detail provided"+ raise GenerationProviderError(f"{action} failed ({code}): {message}")++ @staticmethod+ def _task_id(resp: httpx.Response) -> str:+ data = resp.json()+ if not isinstance(data, dict):+ raise GenerationProviderError("Malformed DashScope image submission response.")+ DashScopeImagegenAdapter._raise_dashscope_error(data, "DashScope image task submission")+ output = data.get("output")+ if isinstance(output, dict) and isinstance(output.get("task_id"), str):+ return output["task_id"]+ raise GenerationProviderError("DashScope image submission returned no task id.")++ async def _poll(+ self,+ client: httpx.AsyncClient,+ config: ImagegenConfig,+ headers: dict[str, str],+ task_id: str,+ ) -> list[dict[str, Any]]:+ poll_url = join_api_path(config.base_url, f"tasks/{task_id}")+ deadline = time.monotonic() + config.poll_timeout+ while True:+ resp = await client.get(poll_url, headers=headers)+ raise_for_provider(resp, "DashScope image task status")+ data = resp.json()+ if not isinstance(data, dict):+ raise GenerationProviderError("Malformed DashScope image task response.")+ self._raise_dashscope_error(data, "DashScope image task status")+ output = data.get("output")+ if not isinstance(output, dict):+ raise GenerationProviderError("Malformed DashScope image task response.")+ status = str(output.get("task_status") or "").lower()+ if status in {"succeeded", "success"}:+ results = output.get("results")+ if not isinstance(results, list):+ raise GenerationProviderError("Successful DashScope image task had no results.")+ return [item for item in results if isinstance(item, dict)]+ if status in {"failed", "canceled", "cancelled", "expired", "unknown"}:+ message = output.get("message") or "no detail provided"+ raise GenerationProviderError(f"DashScope image task {status}: {message}")+ if time.monotonic() >= deadline:+ raise GenerationProviderError(+ f"DashScope image task {task_id} timed out after {config.poll_timeout}s "+ f"(last status: {status or 'unknown'})."+ )+ await asyncio.sleep(config.poll_interval)++ @staticmethod+ async def _materialize(client: httpx.AsyncClient, result: dict[str, Any]) -> tuple[bytes, str]:+ url = result.get("url")+ if not isinstance(url, str) or not url:+ raise GenerationProviderError("DashScope image result had no URL.")+ resp = await client.get(url)+ raise_for_provider(resp, "DashScope image download")+ if not resp.content:+ raise GenerationProviderError("DashScope image download returned empty data.")+ content_type = resp.headers.get("content-type") or "image/png"+ if not content_type.startswith("image/"):+ content_type = "image/png"+ return resp.content, content_type+++__all__ = ["DashScopeImagegenAdapter"]diff --git a/deeptutor/services/imagegen/config.py b/deeptutor/services/imagegen/config.pyindex 0ade91f06..9fee75f35 100644--- a/deeptutor/services/imagegen/config.py+++ b/deeptutor/services/imagegen/config.py@@ -34,6 +34,8 @@ class ImagegenConfig:response_format: str = "" # "" | "url" | "b64_json"# Image generation is slow; allow generous wall-clock per request.request_timeout: int = 120+ poll_interval: float = 2.0+ poll_timeout: int = 300__all__ = ["ImagegenConfig"]diff --git a/deeptutor/services/videogen/adapters/__init__.py b/deeptutor/services/videogen/adapters/__init__.pyindex ffc7dc443..a8c925794 100644--- a/deeptutor/services/videogen/adapters/__init__.py+++ b/deeptutor/services/videogen/adapters/__init__.py@@ -10,10 +10,12 @@ from __future__ import annotationsfrom deeptutor.services.generation_http import GenerationProviderErrorfrom deeptutor.services.videogen.adapters.async_task import AsyncTaskVideogenAdapter+from deeptutor.services.videogen.adapters.dashscope import DashScopeVideogenAdapterfrom deeptutor.services.videogen.base import BaseVideogenAdapterVIDEOGEN_ADAPTERS: dict[str, BaseVideogenAdapter] = {"async_task": AsyncTaskVideogenAdapter(),+ "dashscope": DashScopeVideogenAdapter(),}@@ -24,4 +26,8 @@ def get_videogen_adapter(name: str) -> BaseVideogenAdapter:return adapter-__all__ = ["VIDEOGEN_ADAPTERS", "get_videogen_adapter"]+__all__ = [+ "VIDEOGEN_ADAPTERS",+ "get_videogen_adapter",+ "DashScopeVideogenAdapter",+]diff --git a/deeptutor/services/videogen/adapters/dashscope.py b/deeptutor/services/videogen/adapters/dashscope.pynew file mode 100644index 000000000..4719accc2--- /dev/null+++ b/deeptutor/services/videogen/adapters/dashscope.py@@ -0,0 +1,164 @@+"""Aliyun DashScope native text-to-video adapter."""++from __future__ import annotations++import asyncio+import logging+import time+from typing import Any++import httpx++from deeptutor.services.generation_http import (+ GenerationProviderError,+ build_auth_headers,+ join_api_path,+ raise_for_provider,+)+from deeptutor.services.videogen.base import BaseVideogenAdapter, ProgressFn+from deeptutor.services.videogen.config import VideogenConfig++logger = logging.getLogger(__name__)++_SUBMIT_PATH = "services/aigc/video-generation"+++class DashScopeVideogenAdapter(BaseVideogenAdapter):+ """Run a DashScope video-generation task and download the rendered file."""++ async def submit_task(self, prompt: str, config: VideogenConfig) -> str:+ if not config.base_url:+ raise GenerationProviderError("No endpoint URL configured for video generation.")+ submit_url = join_api_path(config.base_url, _SUBMIT_PATH)+ logger.debug("DashScope video submit url=%s model=%s", submit_url, config.model)+ try:+ async with httpx.AsyncClient(timeout=config.request_timeout) as client:+ resp = await client.post(+ submit_url, headers=self._headers(config), json=self._payload(prompt, config)+ )+ raise_for_provider(resp, "DashScope video task submission")+ return self._task_id(resp)+ except httpx.HTTPError as exc:+ raise GenerationProviderError(f"DashScope video submission error: {exc}") from exc++ async def generate(+ self,+ prompt: str,+ config: VideogenConfig,+ *,+ progress: ProgressFn | None = None,+ ) -> tuple[bytes, str]:+ task_id = await self.submit_task(prompt, config)+ await self._notify(progress, f"Submitted DashScope video task (id={task_id}).")+ headers = self._headers(config)+ try:+ async with httpx.AsyncClient(timeout=config.request_timeout) as client:+ video_url = await self._poll(client, config, headers, task_id, progress)+ await self._notify(progress, "Downloading rendered DashScope video...")+ resp = await client.get(video_url)+ raise_for_provider(resp, "DashScope video download")+ except httpx.HTTPError as exc:+ raise GenerationProviderError(f"DashScope video request error: {exc}") from exc+ if not resp.content:+ raise GenerationProviderError("DashScope video download returned empty data.")+ content_type = resp.headers.get("content-type") or "video/mp4"+ if not content_type.startswith("video/"):+ content_type = "video/mp4"+ return resp.content, content_type++ @staticmethod+ def _headers(config: VideogenConfig) -> dict[str, str]:+ return {+ "Content-Type": "application/json",+ "X-DashScope-Async": "enable",+ **build_auth_headers(config.auth_style, config.api_key),+ **(config.extra_headers or {}),+ }++ @staticmethod+ def _payload(prompt: str, config: VideogenConfig) -> dict[str, Any]:+ parameters: dict[str, Any] = {}+ if config.aspect_ratio:+ parameters["ratio"] = config.aspect_ratio+ if config.duration:+ try:+ parameters["duration"] = int(config.duration)+ except ValueError as exc:+ raise GenerationProviderError(+ f"Invalid DashScope video duration: {config.duration!r}"+ ) from exc+ if config.resolution:+ parameters["resolution"] = config.resolution+ return {+ "model": config.model,+ "input": {"prompt": prompt},+ "parameters": parameters,+ }++ @staticmethod+ def _raise_dashscope_error(data: dict[str, Any], action: str) -> None:+ if data.get("code") not in (None, "", 0, "0") or data.get("success") is False:+ code = data.get("code") or "unknown"+ message = data.get("message") or "no detail provided"+ raise GenerationProviderError(f"{action} failed ({code}): {message}")++ @staticmethod+ def _task_id(resp: httpx.Response) -> str:+ data = resp.json()+ if not isinstance(data, dict):+ raise GenerationProviderError("Malformed DashScope video submission response.")+ DashScopeVideogenAdapter._raise_dashscope_error(data, "DashScope video task submission")+ output = data.get("output")+ if isinstance(output, dict) and isinstance(output.get("task_id"), str):+ return output["task_id"]+ raise GenerationProviderError("DashScope video submission returned no task id.")++ async def _poll(+ self,+ client: httpx.AsyncClient,+ config: VideogenConfig,+ headers: dict[str, str],+ task_id: str,+ progress: ProgressFn | None,+ ) -> str:+ poll_url = join_api_path(config.base_url, f"tasks/{task_id}")+ deadline = time.monotonic() + config.poll_timeout+ polls = 0+ while True:+ resp = await client.get(poll_url, headers=headers)+ raise_for_provider(resp, "DashScope video task status")+ data = resp.json()+ if not isinstance(data, dict):+ raise GenerationProviderError("Malformed DashScope video task response.")+ self._raise_dashscope_error(data, "DashScope video task status")+ output = data.get("output")+ if not isinstance(output, dict):+ raise GenerationProviderError("Malformed DashScope video task response.")+ status = str(output.get("task_status") or "").lower()+ video_url = output.get("video_url")+ if status in {"succeeded", "success"}:+ if not isinstance(video_url, str) or not video_url:+ raise GenerationProviderError("Successful DashScope video task had no URL.")+ return video_url+ if status in {"failed", "canceled", "cancelled", "expired", "unknown"}:+ message = output.get("message") or "no detail provided"+ raise GenerationProviderError(f"DashScope video task {status}: {message}")+ if time.monotonic() >= deadline:+ raise GenerationProviderError(+ f"DashScope video task {task_id} timed out after {config.poll_timeout}s "+ f"(last status: {status or 'unknown'})."+ )+ polls += 1+ if polls % 3 == 0:+ await self._notify(+ progress, f"Still rendering video... (status: {status or 'pending'})"+ )+ await asyncio.sleep(config.poll_interval)++ @staticmethod+ async def _notify(progress: ProgressFn | None, message: str) -> None:+ if progress is not None:+ await progress(message)+++__all__ = ["DashScopeVideogenAdapter"]diff --git a/deeptutor/services/voice/adapters/__init__.py b/deeptutor/services/voice/adapters/__init__.pyindex a8f9de99a..34878a1a2 100644--- a/deeptutor/services/voice/adapters/__init__.py+++ b/deeptutor/services/voice/adapters/__init__.py@@ -8,6 +8,10 @@ OpenRouter, Azure OpenAI and local vLLM/LM Studio; add bespoke providersfrom __future__ import annotations+from deeptutor.services.voice.adapters.dashscope import (+ DashScopeSTTAdapter,+ DashScopeTTSAdapter,+)from deeptutor.services.voice.adapters.openai_compat import (OpenAICompatSTTAdapter,OpenAICompatTTSAdapter,@@ -18,10 +22,12 @@ from deeptutor.services.voice.base import BaseSTTAdapter, BaseTTSAdapter, VoicePTTS_ADAPTERS: dict[str, BaseTTSAdapter] = {"openai_compat": OpenAICompatTTSAdapter(),"openrouter_tts": OpenRouterTTSAdapter(),+ "dashscope": DashScopeTTSAdapter(),}STT_ADAPTERS: dict[str, BaseSTTAdapter] = {"openai_compat": OpenAICompatSTTAdapter(),+ "dashscope": DashScopeSTTAdapter(),}@@ -44,4 +50,6 @@ __all__ = ["STT_ADAPTERS","get_tts_adapter","get_stt_adapter",+ "DashScopeSTTAdapter",+ "DashScopeTTSAdapter",]diff --git a/deeptutor/services/voice/adapters/dashscope.py b/deeptutor/services/voice/adapters/dashscope.pynew file mode 100644index 000000000..9dd229384--- /dev/null+++ b/deeptutor/services/voice/adapters/dashscope.py@@ -0,0 +1,337 @@+"""Native Aliyun DashScope voice adapters."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+import tempfile+from typing import Any+from urllib.parse import urlsplit+import uuid++import aiohttp+import httpx++from deeptutor.services.voice.base import (+ BaseSTTAdapter,+ BaseTTSAdapter,+ VoiceProviderError,+ VoiceProviderHTTPError,+ build_auth_headers,+ join_audio_path,+)+from deeptutor.services.voice.config import STTConfig, TTSConfig++_TTS_PATH = "services/aigc/multimodal-generation/generation"+_AUDIO_CONTENT_TYPES = {+ "mp3": "audio/mpeg",+ "wav": "audio/wav",+ "opus": "audio/opus",+ "pcm": "audio/pcm",+}+++def _provider_error(resp: httpx.Response, action: str) -> None:+ if resp.status_code < 400:+ return+ detail = (resp.text or "").strip()[:400]+ raise VoiceProviderHTTPError(+ f"{action} failed with HTTP {resp.status_code}" + (f": {detail}" if detail else "."),+ status_code=resp.status_code,+ body=resp.text,+ )+++def _dashscope_error(data: dict[str, Any], action: str) -> None:+ if data.get("code") not in (None, "", 0, "0") or data.get("success") is False:+ code = data.get("code") or "unknown"+ message = data.get("message") or "no detail provided"+ raise VoiceProviderError(f"{action} failed ({code}): {message}")+++class DashScopeTTSAdapter(BaseTTSAdapter):+ """Generate speech with Qwen TTS and download the returned audio URL."""++ async def synthesize(self, text: str, config: TTSConfig) -> tuple[bytes, str]:+ if not config.base_url:+ raise VoiceProviderError("No endpoint URL configured for TTS.")+ url = join_audio_path(config.base_url, _TTS_PATH)+ headers = {+ "Content-Type": "application/json",+ **build_auth_headers(config.auth_style, config.api_key),+ **(config.extra_headers or {}),+ }+ payload: dict[str, Any] = {+ "model": config.model,+ "input": {"text": text},+ }+ if config.voice:+ payload["input"]["voice"] = config.voice++ try:+ async with httpx.AsyncClient(timeout=config.request_timeout) as client:+ resp = await client.post(url, headers=headers, json=payload)+ _provider_error(resp, "DashScope TTS")+ data = self._json_object(resp)+ _dashscope_error(data, "DashScope TTS")+ audio_url = self._audio_url(data)+ audio_resp = await client.get(audio_url)+ _provider_error(audio_resp, "DashScope audio download")+ except (httpx.HTTPError, ValueError) as exc:+ raise VoiceProviderError(f"DashScope TTS request error: {exc}") from exc++ if not audio_resp.content:+ raise VoiceProviderError("DashScope TTS returned empty audio.")+ content_type = audio_resp.headers.get("content-type") or self._url_content_type(+ audio_url, config.response_format+ )+ if not content_type.startswith("audio/"):+ content_type = _AUDIO_CONTENT_TYPES.get(+ (config.response_format or "wav").lower(), "audio/wav"+ )+ return audio_resp.content, content_type++ @staticmethod+ def _json_object(resp: httpx.Response) -> dict[str, Any]:+ data = resp.json()+ if not isinstance(data, dict):+ raise VoiceProviderError("DashScope TTS returned a malformed response.")+ return data++ @staticmethod+ def _audio_url(data: dict[str, Any]) -> str:+ output = data.get("output")+ if isinstance(output, dict):+ audio = output.get("audio")+ if isinstance(audio, dict):+ url = audio.get("url")+ if isinstance(url, str) and url:+ return url+ raise VoiceProviderError("DashScope TTS response had no audio URL.")++ @staticmethod+ def _url_content_type(url: str, response_format: str) -> str:+ suffix = Path(urlsplit(url).path).suffix.lstrip(".").lower()+ return _AUDIO_CONTENT_TYPES.get(suffix) or _AUDIO_CONTENT_TYPES.get(+ (response_format or "wav").lower(), "audio/wav"+ )+++class DashScopeSTTAdapter(BaseSTTAdapter):+ """Transcribe local audio over DashScope's native recognition WebSocket."""++ async def transcribe(+ self,+ audio: bytes,+ config: STTConfig,+ *,+ filename: str = "audio.webm",+ content_type: str = "application/octet-stream",+ ) -> str:+ if not audio:+ raise VoiceProviderError("No audio data to transcribe.")+ wav_audio = await self._prepare_wav(audio, filename, content_type)+ if not wav_audio:+ raise VoiceProviderError("Audio conversion returned an empty file.")+ if not config.api_key:+ raise VoiceProviderError("No API key configured for DashScope STT.")++ timeout = aiohttp.ClientTimeout(total=config.request_timeout)+ try:+ async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:+ async with session.ws_connect(+ self._websocket_url(config.base_url),+ headers={+ "Authorization": f"Bearer {config.api_key}",+ **(config.extra_headers or {}),+ },+ heartbeat=30,+ ) as websocket:+ return await self._run_recognition(websocket, wav_audio, config)+ except (aiohttp.ClientError, asyncio.TimeoutError) as exc:+ raise VoiceProviderError(f"DashScope STT request error: {exc}") from exc++ async def _prepare_wav(self, audio: bytes, filename: str, content_type: str) -> bytes:+ source_suffix = self._audio_suffix(filename, content_type)+ if self._is_canonical_wav(audio):+ return audio+ with tempfile.TemporaryDirectory(prefix="deeptutor-dashscope-stt-") as directory:+ source = Path(directory) / f"audio.{source_suffix}"+ target = Path(directory) / "audio.wav"+ source.write_bytes(audio)+ try:+ process = await asyncio.create_subprocess_exec(+ "ffmpeg",+ "-hide_banner",+ "-loglevel",+ "error",+ "-i",+ str(source),+ "-vn",+ "-acodec",+ "pcm_s16le",+ "-ar",+ "16000",+ "-ac",+ "1",+ str(target),+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ except OSError as exc:+ raise VoiceProviderError(+ "ffmpeg is required to normalize audio for DashScope STT."+ ) from exc+ _, stderr = await process.communicate()+ if process.returncode != 0:+ detail = stderr.decode("utf-8", errors="replace").strip()[:400]+ raise VoiceProviderError(+ "Could not convert browser audio to WAV for DashScope STT"+ + (f": {detail}" if detail else ".")+ )+ return target.read_bytes()++ @staticmethod+ def _is_canonical_wav(audio: bytes) -> bool:+ if len(audio) < 44 or audio[:4] != b"RIFF" or audio[8:12] != b"WAVE":+ return False+ sample_rate = int.from_bytes(audio[24:28], "little")+ channels = int.from_bytes(audio[22:24], "little")+ bits_per_sample = int.from_bytes(audio[34:36], "little")+ return sample_rate == 16000 and channels == 1 and bits_per_sample == 16++ @staticmethod+ def _audio_suffix(filename: str, content_type: str) -> str:+ suffix = Path(filename).suffix.lstrip(".").lower()+ if suffix in {"wav", "mp3", "aac", "ogg", "opus", "flac", "m4a", "webm"}:+ return suffix+ media_type = (content_type or "").split(";", 1)[0].strip().lower()+ return {+ "audio/wav": "wav",+ "audio/mpeg": "mp3",+ "audio/aac": "aac",+ "audio/ogg": "ogg",+ "audio/opus": "opus",+ "audio/webm": "webm",+ "audio/mp4": "m4a",+ }.get(media_type, "webm")++ @staticmethod+ def _websocket_url(base_url: str) -> str:+ parsed = urlsplit((base_url or "").strip())+ if not parsed.netloc:+ raise VoiceProviderError("No endpoint URL configured for DashScope STT.")+ if parsed.scheme in {"ws", "wss"}:+ return base_url+ if "/api-ws/" in parsed.path:+ return parsed._replace(scheme="wss").geturl()+ return f"wss://{parsed.netloc}/api-ws/v1/inference"++ @staticmethod+ def _start_payload(+ config: STTConfig, task_id: str, *, sample_rate: int = 16000+ ) -> dict[str, Any]:+ return {+ "header": {+ "task_id": task_id,+ "action": "run-task",+ "streaming": "duplex",+ },+ "payload": {+ "model": config.model,+ "task_group": "audio",+ "task": "asr",+ "function": "recognition",+ "input": {},+ "parameters": {"format": "wav", "sample_rate": sample_rate},+ },+ }++ async def _run_recognition(+ self,+ websocket: Any,+ audio: bytes,+ config: STTConfig,+ ) -> str:+ task_id = uuid.uuid4().hex+ await websocket.send_str(self._json(self._start_payload(config, task_id)))++ started = await websocket.receive()+ self._require_started(started, task_id)++ for offset in range(0, len(audio), 12800):+ await websocket.send_bytes(audio[offset : offset + 12800])+ await websocket.send_str(+ self._json(+ {+ "header": {+ "task_id": task_id,+ "action": "finish-task",+ "streaming": "duplex",+ },+ "payload": {"input": {}},+ }+ )+ )++ texts: list[str] = []+ while True:+ message = await websocket.receive()+ message_type = getattr(message, "type", None)+ if message_type in {aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR}:+ raise VoiceProviderError("DashScope STT websocket closed unexpectedly.")+ if message_type != aiohttp.WSMsgType.TEXT:+ continue+ data = message.json()+ if not isinstance(data, dict):+ raise VoiceProviderError("DashScope STT returned a malformed websocket event.")+ header = data.get("header") or {}+ event = header.get("event")+ if event == "result-generated":+ texts.extend(self._sentence_texts((data.get("payload") or {}).get("output")))+ elif event == "task-failed":+ code = header.get("error_code") or "unknown"+ detail = header.get("error_message") or "no detail provided"+ raise VoiceProviderError(f"DashScope STT failed ({code}): {detail}")+ elif event == "task-finished":+ texts.extend(self._sentence_texts((data.get("payload") or {}).get("output")))+ break+ return "".join(texts).strip()++ @staticmethod+ def _sentence_texts(output: Any) -> list[str]:+ if isinstance(output, dict):+ sentence = output.get("sentence")+ values = sentence if isinstance(sentence, list) else [sentence]+ return [+ text+ for item in values+ if isinstance(item, dict)+ for text in [item.get("text")]+ if isinstance(text, str)+ ]+ return []++ @staticmethod+ def _require_started(message: Any, task_id: str) -> None:+ if getattr(message, "type", None) != aiohttp.WSMsgType.TEXT:+ raise VoiceProviderError("DashScope STT websocket closed before task started.")+ data = message.json()+ header = data.get("header") or {}+ if header.get("task_id") != task_id:+ raise VoiceProviderError("DashScope STT returned an unexpected task id.")+ if header.get("event") == "task-failed":+ raise VoiceProviderError(+ "DashScope STT failed to start: "+ + str(header.get("error_message") or "no detail provided")+ )+ if header.get("event") != "task-started":+ raise VoiceProviderError("DashScope STT returned an unexpected start event.")++ @staticmethod+ def _json(value: dict[str, Any]) -> str:+ return json.dumps(value, ensure_ascii=False)+++__all__ = ["DashScopeSTTAdapter", "DashScopeTTSAdapter"]diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex ea935657e..e7192a986 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -578,6 +578,26 @@ def test_embedding_provider_choices_use_full_endpoint_urls() -> None:assert "custom_openai_sdk" not in embedding+def test_media_and_voice_provider_choices_include_dashscope() -> None:+ choices = settings_router._provider_choices()+ services = ("tts", "stt", "imagegen", "videogen")+ dashscope = {+ service: {item["value"]: item for item in choices[service]}["dashscope"]+ for service in services+ }++ assert set(dashscope) == set(services)+ assert all(item["label"] == "Aliyun DashScope" for item in dashscope.values())+ assert all(+ item["base_url"] == "https://dashscope.aliyuncs.com/api/v1" for item in dashscope.values()+ )+ assert dashscope["tts"]["default_model"] == "qwen3-tts-flash"+ assert dashscope["tts"]["default_voice"] == "Cherry"+ assert dashscope["stt"]["default_model"] == "paraformer-v2"+ assert dashscope["imagegen"]["default_model"] == "wanx2.1-t2i-turbo"+ assert dashscope["videogen"]["default_model"] == "wanx2.1-t2v-turbo"++def test_llm_provider_choices_include_atlascloud() -> None:llm = {item["value"]: item for item in settings_router._provider_choices()["llm"]}diff --git a/tests/services/test_media_gen.py b/tests/services/test_media_gen.pyindex 39d611c66..4454c37bb 100644--- a/tests/services/test_media_gen.py+++ b/tests/services/test_media_gen.py@@ -25,10 +25,12 @@ from deeptutor.services.generation_http import ()from deeptutor.services.imagegen import generate_imagefrom deeptutor.services.imagegen.adapters.chat_completions import ChatCompletionsImagegenAdapter+from deeptutor.services.imagegen.adapters.dashscope import DashScopeImagegenAdapterfrom deeptutor.services.imagegen.adapters.openai_compat import OpenAICompatImagegenAdapterfrom deeptutor.services.imagegen.config import ImagegenConfigfrom deeptutor.services.videogen import generate_video, probe_videofrom deeptutor.services.videogen.adapters.async_task import AsyncTaskVideogenAdapter+from deeptutor.services.videogen.adapters.dashscope import DashScopeVideogenAdapterfrom deeptutor.services.videogen.config import VideogenConfig@@ -147,6 +149,98 @@ async def test_imagegen_adapter_raises_on_http_error(monkeypatch: pytest.MonkeyPawait OpenAICompatImagegenAdapter().generate("x", config)+async def test_dashscope_imagegen_task_polls_and_downloads(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def post_router(url: str, _kwargs: Any) -> httpx.Response:+ assert url == "https://dashscope.aliyuncs.com/api/v1/services/aigc/image-synthesis"+ return httpx.Response(200, json={"output": {"task_id": "image-task"}})++ def get_router(url: str, _kwargs: Any) -> httpx.Response:+ if url.endswith("/tasks/image-task"):+ return httpx.Response(+ 200,+ json={+ "output": {+ "task_status": "SUCCEEDED",+ "results": [{"url": "https://cdn.example.com/image.png"}],+ }+ },+ )+ return httpx.Response(200, content=b"IMAGEDATA", headers={"content-type": "image/png"})++ captured = _patch_http(monkeypatch, post=post_router, get=get_router)+ config = ImagegenConfig(+ model="wanx2.1-t2i-turbo",+ provider_name="dashscope",+ adapter="dashscope",+ base_url="https://dashscope.aliyuncs.com/api/v1",+ api_key="dash-key",+ size="1024x1024",+ poll_interval=0.0,+ )++ images = await DashScopeImagegenAdapter().generate("a cat", config, n=2)++ assert images == [(b"IMAGEDATA", "image/png")]+ post = captured["posts"][0]+ assert post["headers"]["X-DashScope-Async"] == "enable"+ assert post["headers"]["Authorization"] == "Bearer dash-key"+ assert post["json"] == {+ "model": "wanx2.1-t2i-turbo",+ "input": {"prompt": "a cat"},+ "parameters": {"n": 2, "size": "1024*1024"},+ }+ assert captured["gets"][0]["url"] == ("https://dashscope.aliyuncs.com/api/v1/tasks/image-task")+ assert captured["gets"][1]["url"] == "https://cdn.example.com/image.png"+++async def test_dashscope_imagegen_task_failure_is_actionable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def post_router(url: str, _kwargs: Any) -> httpx.Response:+ return httpx.Response(200, json={"output": {"task_id": "image-failed"}})++ failed = httpx.Response(+ 200,+ json={"output": {"task_status": "FAILED", "message": "content policy blocked"}},+ )+ _patch_http(monkeypatch, post=post_router, get=failed)+ config = ImagegenConfig(+ model="wanx2.1-t2i-turbo",+ adapter="dashscope",+ base_url="https://dashscope.aliyuncs.com/api/v1",+ api_key="dash-key",+ poll_interval=0.0,+ )++ with pytest.raises(GenerationProviderError, match="content policy blocked"):+ await DashScopeImagegenAdapter().generate("unsafe prompt", config)+++async def test_dashscope_imagegen_http200_protocol_error_is_actionable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ post = httpx.Response(200, json={"code": "InvalidParameter", "message": "unsupported size"})+ _patch_http(monkeypatch, post=post)+ config = ImagegenConfig(+ model="wanx2.1-t2i-turbo",+ adapter="dashscope",+ base_url="https://dashscope.aliyuncs.com/api/v1",+ api_key="dash-key",+ size="1x1",+ )++ with pytest.raises(+ GenerationProviderError,+ match=r"DashScope image task submission failed \(InvalidParameter\): unsupported size",+ ):+ await DashScopeImagegenAdapter().generate("x", config)++# ── videogen adapter ────────────────────────────────────────────────────────@@ -198,6 +292,75 @@ async def test_videogen_adapter_raises_on_failed_task(monkeypatch: pytest.Monkeyawait AsyncTaskVideogenAdapter().generate("x", config)+async def test_dashscope_videogen_task_polls_and_downloads(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ progress_messages: list[str] = []++ async def progress(message: str) -> None:+ progress_messages.append(message)++ def post_router(url: str, kwargs: Any) -> httpx.Response:+ assert url == "https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation"+ assert kwargs["headers"]["X-DashScope-Async"] == "enable"+ assert kwargs["json"] == {+ "model": "wanx2.1-t2v-turbo",+ "input": {"prompt": "a wave"},+ "parameters": {"ratio": "16:9", "duration": 5, "resolution": "720p"},+ }+ return httpx.Response(200, json={"output": {"task_id": "video-task"}})++ def get_router(url: str, _kwargs: Any) -> httpx.Response:+ if url.endswith("/tasks/video-task"):+ return httpx.Response(+ 200,+ json={"output": {"task_status": "SUCCEEDED", "video_url": "https://cdn/v.mp4"}},+ )+ return httpx.Response(200, content=b"MP4DATA", headers={"content-type": "video/mp4"})++ _patch_http(monkeypatch, post=post_router, get=get_router)+ config = VideogenConfig(+ model="wanx2.1-t2v-turbo",+ provider_name="dashscope",+ adapter="dashscope",+ base_url="https://dashscope.aliyuncs.com/api/v1",+ api_key="dash-key",+ aspect_ratio="16:9",+ duration="5",+ resolution="720p",+ poll_interval=0.0,+ )++ video, content_type = await DashScopeVideogenAdapter().generate(+ "a wave", config, progress=progress+ )++ assert video == b"MP4DATA"+ assert content_type == "video/mp4"+ assert progress_messages[0].startswith("Submitted DashScope video task")+++async def test_dashscope_videogen_http200_protocol_error_is_actionable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ post = httpx.Response(200, json={"success": False, "message": "model quota exceeded"})+ _patch_http(monkeypatch, post=post)+ config = VideogenConfig(+ model="wanx2.1-t2v-turbo",+ adapter="dashscope",+ base_url="https://dashscope.aliyuncs.com/api/v1",+ api_key="dash-key",+ )++ with pytest.raises(+ GenerationProviderError,+ match=r"DashScope video task submission failed \(unknown\): model quota exceeded",+ ):+ await DashScopeVideogenAdapter().generate("x", config)++# ── catalog resolution ──────────────────────────────────────────────────────@@ -278,6 +441,25 @@ def test_resolve_videogen_config_uses_async_task_adapter() -> None:assert cfg.aspect_ratio == "9:16"+def test_resolve_dashscope_media_configs() -> None:+ catalog = _media_catalog()+ catalog["services"]["imagegen"]["profiles"][0]["binding"] = "aliyun"+ catalog["services"]["imagegen"]["profiles"][0]["models"][0]["model"] = "wanx2.1-t2i-turbo"+ catalog["services"]["videogen"]["profiles"][0]["binding"] = "bailian"+ catalog["services"]["videogen"]["profiles"][0]["models"][0]["model"] = "wanx2.1-t2v-turbo"++ image = resolve_imagegen_runtime_config(catalog=catalog)+ video = resolve_videogen_runtime_config(catalog=catalog)++ assert image.provider_name == "dashscope"+ assert image.adapter == "dashscope"+ assert image.model == "wanx2.1-t2i-turbo"+ assert video.provider_name == "dashscope"+ assert video.adapter == "dashscope"+ assert video.model == "wanx2.1-t2v-turbo"+ assert image.base_url == video.base_url == "https://dashscope.aliyuncs.com/api/v1"++def test_resolve_imagegen_config_raises_without_model() -> None:catalog = {"version": 1, "services": {"imagegen": {"profiles": []}}}with pytest.raises(ValueError, match="No active image-generation model"):diff --git a/tests/services/test_voice.py b/tests/services/test_voice.pyindex df3fad7e8..34c6ae7c4 100644--- a/tests/services/test_voice.py+++ b/tests/services/test_voice.py@@ -8,9 +8,11 @@ config resolution.from __future__ import annotationsimport base64+from dataclasses import dataclassimport jsonfrom typing import Any+import aiohttpimport httpximport pytest@@ -19,6 +21,10 @@ from deeptutor.services.config.provider_runtime import (resolve_tts_runtime_config,)from deeptutor.services.voice import synthesize_speech, transcribe_audio+from deeptutor.services.voice.adapters.dashscope import (+ DashScopeSTTAdapter,+ DashScopeTTSAdapter,+)from deeptutor.services.voice.adapters.openai_compat import (OpenAICompatSTTAdapter,OpenAICompatTTSAdapter,@@ -50,6 +56,56 @@ def _capture_post(monkeypatch: pytest.MonkeyPatch, response: httpx.Response) ->return captured+def _capture_http(+ monkeypatch: pytest.MonkeyPatch,+ *,+ post: Any,+ get: Any,+) -> dict[str, Any]:+ captured: dict[str, Any] = {"posts": [], "gets": []}++ async def fake_post(self: httpx.AsyncClient, url: str, **kwargs: Any) -> httpx.Response:+ captured["posts"].append({"url": url, **kwargs})+ response = post(url, kwargs) if callable(post) else post+ response.request = httpx.Request("POST", url)+ return response++ async def fake_get(self: httpx.AsyncClient, url: str, **kwargs: Any) -> httpx.Response:+ captured["gets"].append({"url": url, **kwargs})+ response = get(url, kwargs) if callable(get) else get+ response.request = httpx.Request("GET", url)+ return response++ monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)+ monkeypatch.setattr(httpx.AsyncClient, "get", fake_get)+ return captured+++@dataclass+class _FakeWSMessage:+ data: dict[str, Any]+ type: aiohttp.WSMsgType = aiohttp.WSMsgType.TEXT++ def json(self) -> dict[str, Any]:+ return self.data+++class _FakeWebSocket:+ def __init__(self, messages: list[dict[str, Any]]) -> None:+ self.messages = list(messages)+ self.strings: list[str] = []+ self.chunks: list[bytes] = []++ async def send_str(self, value: str) -> None:+ self.strings.append(value)++ async def send_bytes(self, value: bytes) -> None:+ self.chunks.append(value)++ async def receive(self) -> _FakeWSMessage:+ return _FakeWSMessage(self.messages.pop(0))++# ── text cleaning ─────────────────────────────────────────────────────────@@ -143,6 +199,39 @@ async def test_tts_adapter_raises_on_http_error(monkeypatch: pytest.MonkeyPatch)await OpenAICompatTTSAdapter().synthesize("hi", config)+async def test_dashscope_tts_posts_native_shape_and_downloads_audio(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ post = httpx.Response(+ 200, json={"output": {"audio": {"url": "https://cdn.example.com/audio.wav"}}}+ )+ download = httpx.Response(200, content=b"WAVDATA", headers={"content-type": "audio/wav"})+ captured = _capture_http(monkeypatch, post=post, get=download)+ config = TTSConfig(+ model="qwen3-tts-flash",+ provider_name="dashscope",+ adapter="dashscope",+ base_url="https://dashscope.aliyuncs.com/api/v1",+ api_key="dash-key",+ voice="Cherry",+ )++ audio, content_type = await DashScopeTTSAdapter().synthesize("hello", config)++ assert audio == b"WAVDATA"+ assert content_type == "audio/wav"+ assert captured["posts"][0]["url"] == (+ "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"+ )+ assert captured["posts"][0]["json"] == {+ "model": "qwen3-tts-flash",+ "input": {"text": "hello", "voice": "Cherry"},+ }+ assert captured["posts"][0]["headers"]["Authorization"] == "Bearer dash-key"+ assert captured["gets"][0]["url"] == "https://cdn.example.com/audio.wav"++@pytest.mark.asyncioasync def test_openrouter_tts_falls_back_to_chat_audio_stream(monkeypatch: pytest.MonkeyPatch,@@ -260,6 +349,58 @@ async def test_stt_adapter_strips_codec_parameters(monkeypatch: pytest.MonkeyPatassert captured["files"]["file"][2] == "audio/webm"+async def test_dashscope_stt_recognition_websocket_shape() -> None:+ task_id: str | None = None+ websocket = _FakeWebSocket(+ [+ {"header": {"event": "task-started"}},+ {+ "header": {"event": "result-generated"},+ "payload": {"output": {"sentence": [{"text": "hello "}, {"text": "world"}]}},+ },+ {"header": {"event": "task-finished"}},+ ]+ )++ # The fake pops start before the adapter knows its generated id. Patch the+ # id check with a dynamic side-effect-like object by deriving it from send.+ original_send = websocket.send_str++ async def record_start(value: str) -> None:+ nonlocal task_id+ await original_send(value)+ if task_id is None:+ task_id = json.loads(value)["header"]["task_id"]+ websocket.messages[0] = {"header": {"task_id": task_id, "event": "task-started"}}++ websocket.send_str = record_start # type: ignore[method-assign]+ config = STTConfig(+ model="paraformer-v2",+ provider_name="dashscope",+ adapter="dashscope",+ base_url="https://dashscope.aliyuncs.com/api/v1",+ api_key="dash-key",+ )++ text = await DashScopeSTTAdapter()._run_recognition(websocket, b"RIFFxxxx", config)++ assert text == "hello world"+ start = json.loads(websocket.strings[0])+ assert start["payload"]["model"] == "paraformer-v2"+ assert start["payload"]["parameters"] == {"format": "wav", "sample_rate": 16000}+ assert websocket.chunks == [b"RIFFxxxx"]+ assert json.loads(websocket.strings[-1])["header"]["action"] == "finish-task"+++def test_dashscope_stt_url_and_errors() -> None:+ adapter = DashScopeSTTAdapter()+ assert adapter._websocket_url("https://dashscope.aliyuncs.com/api/v1") == (+ "wss://dashscope.aliyuncs.com/api-ws/v1/inference"+ )+ assert adapter._sentence_texts({"sentence": {"text": "single"}}) == ["single"]++@pytest.mark.asyncioasync def test_stt_adapter_openrouter_base64(monkeypatch: pytest.MonkeyPatch) -> None:resp = httpx.Response(200, json={"text": "from base64"})@@ -341,6 +482,31 @@ def test_resolve_stt_config_picks_openrouter_base64_style() -> None:assert cfg.base_url == "https://openrouter.ai/api/v1"+def test_resolve_dashscope_voice_configs() -> None:+ catalog = _voice_catalog()+ catalog["services"]["tts"]["profiles"][0]["binding"] = "aliyun"+ catalog["services"]["tts"]["profiles"][0]["models"][0] = {+ "id": "m1",+ "model": "qwen3-tts-flash",+ "voice": "",+ }+ catalog["services"]["stt"]["profiles"][0]["binding"] = "bailian"+ catalog["services"]["stt"]["profiles"][0]["models"][0]["model"] = "paraformer-v2"++ tts = resolve_tts_runtime_config(catalog=catalog)+ stt = resolve_stt_runtime_config(catalog=catalog)++ assert tts.provider_name == "dashscope"+ assert tts.adapter == "dashscope"+ assert tts.model == "qwen3-tts-flash"+ assert tts.voice == "Cherry"+ assert tts.base_url == "https://dashscope.aliyuncs.com/api/v1"+ assert stt.provider_name == "dashscope"+ assert stt.adapter == "dashscope"+ assert stt.model == "paraformer-v2"+ assert stt.base_url == tts.base_url++def test_resolve_tts_config_picks_openrouter_adapter() -> None:catalog = _voice_catalog()catalog["services"]["tts"]["profiles"][0]["binding"] = "openrouter"