Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(tts): propagate CosyVoice callback errors (#3042)
little-spoon77ac3c50ba7160
diff --git a/src/agentscope/tts/_dashscope/_cosyvoice_utils.py b/src/agentscope/tts/_dashscope/_cosyvoice_utils.pyindex b1573b597..904cc7645 100644--- a/src/agentscope/tts/_dashscope/_cosyvoice_utils.py+++ b/src/agentscope/tts/_dashscope/_cosyvoice_utils.py@@ -53,11 +53,13 @@ def _make_cosyvoice_callback_class() -> type["ResultCallback"]:self.finish_event = threading.Event()self._pcm_bytes: bytearray = bytearray()self._consumed: int = 0+ self._error: RuntimeError | None = Nonedef on_open(self) -> None:"""Handle WebSocket open by resetting audio state."""self._pcm_bytes = bytearray()self._consumed = 0+ self._error = Noneself.finish_event.clear()self.chunk_event.clear()@@ -81,6 +83,7 @@ def _make_cosyvoice_callback_class() -> type["ResultCallback"]:def on_error(self, message: Any) -> None:"""Handle synthesis error."""logger.error("CosyVoice TTS error: %s", message)+ self._error = RuntimeError(f"CosyVoice TTS error: {message}")self.finish_event.set()self.chunk_event.set()@@ -102,6 +105,8 @@ def _make_cosyvoice_callback_class() -> type["ResultCallback"]:"""Return incremental audio delta."""if block:self.finish_event.wait()+ if self._error is not None:+ raise self._errordelta = self._take_delta(header=self._consumed == 0)if delta:return _build_audio_response(delta, _MEDIA_TYPE)@@ -113,6 +118,8 @@ def _make_cosyvoice_callback_class() -> type["ResultCallback"]:"""Yield incremental audio chunks as they arrive."""header_sent = self._consumed > 0while True:+ if self._error is not None:+ raise self._errorif self.finish_event.is_set():delta = self._take_delta(header=not header_sent)if delta:@@ -149,6 +156,7 @@ def _make_cosyvoice_callback_class() -> type["ResultCallback"]:self.chunk_event.clear()self._pcm_bytes = bytearray()self._consumed = 0+ self._error = Nonedef has_audio_data(self) -> bool:"""Return whether any audio data has been received."""diff --git a/tests/tts_dashscope_test.py b/tests/tts_dashscope_test.pyindex 6c80f9c92..729301f4f 100644--- a/tests/tts_dashscope_test.py+++ b/tests/tts_dashscope_test.py@@ -1567,6 +1567,55 @@ class TestDashScopeCosyVoiceRealtimeMode(self.assertFalse(raw.startswith(b"RIFF"))self.assertEqual(raw, b"MOREPCM")+ async def test_callback_errors_reach_audio_consumers(self) -> None:+ """Failure must not finalize empty or partial audio successfully."""+ with patch.dict("sys.modules", self.mock_modules):+ from agentscope.tts._dashscope._cosyvoice_utils import (+ _make_cosyvoice_callback_class,+ )++ callback_cls = _make_cosyvoice_callback_class()+ for audio in (b"", b"PCMPCM"):+ for consumer in ("stream", "blocking", "polling"):+ with self.subTest(audio=audio, consumer=consumer):+ cb = callback_cls()+ cb.on_data(audio)+ cb.on_error("synthesis failed")+ cb.on_close()+ with self.assertRaisesRegex(+ RuntimeError,+ "^CosyVoice TTS error: synthesis failed$",+ ):+ if consumer == "stream":+ _ = [c async for c in cb.get_audio_chunks()]+ else:+ cb.get_audio_response(+ block=consumer == "blocking",+ )++ async def test_callback_new_utterance_clears_error(self) -> None:+ """Resetting or reopening must not carry a stale provider error."""+ with patch.dict("sys.modules", self.mock_modules):+ from agentscope.tts._dashscope._cosyvoice_utils import (+ _make_cosyvoice_callback_class,+ )++ callback_cls = _make_cosyvoice_callback_class()+ for reset_method in ("reset", "on_open"):+ with self.subTest(reset_method=reset_method):+ cb = callback_cls()+ cb.on_data(b"OLDPCM")+ cb.on_error("old failure")+ getattr(cb, reset_method)()+ cb.on_data(b"NEWPCM")+ cb.on_complete()+ response = cb.get_audio_response(block=True)+ self.assertEqual(+ base64.b64decode(response.content.source.data)[44:],+ b"NEWPCM",+ )+ self.assertTrue(response.is_last)+async def test_callback_reset(self) -> None:"""reset() clears all state."""with patch.dict("sys.modules", self.mock_modules):