The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(stt): never stringify a structured STT error response into the transcript
Austin Pickett59b2aeef6c7a
diff --git a/tests/tools/test_transcription_tools.py b/tests/tools/test_transcription_tools.pyindex dccd75d7dbf..faf5707bc5a 100644--- a/tests/tools/test_transcription_tools.py+++ b/tests/tools/test_transcription_tools.py@@ -1087,6 +1087,131 @@ class TestExtractTranscriptText:assert result == "The user literally said <asr_text> while reading markup."+ def test_structured_error_object_raises_instead_of_repr(self):+ """#78098: a provider error object must not be stringified into its repr."""+ from tools.transcription_common import STTResponseError+ from tools.transcription_cloud import _extract_transcript_text++ transcription = types.SimpleNamespace(+ text=None, logprobs=None, usage=None, error="Transcription failed",+ )++ with pytest.raises(STTResponseError, match="Transcription failed") as excinfo:+ _extract_transcript_text(transcription)++ assert "text=None" not in str(excinfo.value)++ def test_structured_error_body_raises_instead_of_repr(self):+ from tools.transcription_common import STTResponseError+ from tools.transcription_cloud import _extract_transcript_text++ with pytest.raises(STTResponseError, match="Transcription failed"):+ _extract_transcript_text({"text": None, "error": "Transcription failed"})++ def test_structured_response_without_text_or_error_raises(self):+ """Neither text nor a provider error: still an error, never ``str(obj)``."""+ from tools.transcription_common import STTResponseError+ from tools.transcription_cloud import _extract_transcript_text++ with pytest.raises(STTResponseError, match="no text"):+ _extract_transcript_text(types.SimpleNamespace(text=None, error=None))+ with pytest.raises(STTResponseError, match="no text"):+ _extract_transcript_text({"text": None})++ def test_text_bearing_responses_still_normalize(self):+ from tools.transcription_cloud import _extract_transcript_text++ assert _extract_transcript_text(types.SimpleNamespace(text=" hello ")) == "hello"+ assert _extract_transcript_text({"text": " hello "}) == "hello"+ # Silence stays non-fatal: an empty *string* text is a valid empty transcript.+ assert _extract_transcript_text(types.SimpleNamespace(text="", error=None)) == ""+ assert _extract_transcript_text({"text": ""}) == ""+++class TestStructuredTranscriptionErrors:+ """#78098: every provider path surfaces a structured error as a failure envelope+ instead of reporting the response's repr as a successful transcript."""++ @staticmethod+ def _error_object():+ return types.SimpleNamespace(+ text=None, logprobs=None, usage=None, error="Transcription failed",+ )++ def test_openai_error_object_returns_failure_envelope(self, sample_wav):+ mock_client = MagicMock()+ mock_client.audio.transcriptions.create.return_value = self._error_object()++ with patch("tools.transcription_tools._HAS_OPENAI", True), \+ patch("openai.OpenAI", return_value=mock_client):+ from tools.transcription_tools import _transcribe_openai+ result = _transcribe_openai(sample_wav, "gpt-4o-transcribe", api_key="sk-test")++ assert result["success"] is False+ assert result["transcript"] == ""+ assert result["error"] == "Transcription failed"+ assert "text=None" not in result["error"]++ def test_openai_text_object_still_succeeds(self, sample_wav):+ mock_client = MagicMock()+ mock_client.audio.transcriptions.create.return_value = types.SimpleNamespace(+ text="hello world", logprobs=None, usage=None, error=None,+ )++ with patch("tools.transcription_tools._HAS_OPENAI", True), \+ patch("openai.OpenAI", return_value=mock_client):+ from tools.transcription_tools import _transcribe_openai+ result = _transcribe_openai(sample_wav, "gpt-4o-transcribe", api_key="sk-test")++ assert result["success"] is True+ assert result["transcript"] == "hello world"++ def test_groq_error_object_returns_failure_envelope(self, monkeypatch, sample_wav):+ monkeypatch.setenv("GROQ_API_KEY", "gsk-test")+ mock_client = MagicMock()+ mock_client.audio.transcriptions.create.return_value = self._error_object()++ with patch("tools.transcription_tools._HAS_OPENAI", True), \+ patch("openai.OpenAI", return_value=mock_client):+ from tools.transcription_tools import _transcribe_groq+ result = _transcribe_groq(sample_wav, "whisper-large-v3-turbo")++ assert result["success"] is False+ assert result["transcript"] == ""+ assert result["error"] == "Transcription failed"++ def test_mistral_error_object_returns_failure_envelope(+ self, monkeypatch, sample_ogg, mock_mistral_module+ ):+ monkeypatch.setenv("MISTRAL_API_KEY", "test-key")+ mock_result = MagicMock()+ mock_result.text = None+ mock_result.error = "Transcription failed"+ mock_mistral_module.audio.transcriptions.complete.return_value = mock_result++ from tools.transcription_tools import _transcribe_mistral+ result = _transcribe_mistral(sample_ogg, "voxtral-mini-latest")++ assert result["success"] is False+ assert result["transcript"] == ""+ assert result["error"] == "Transcription failed"+ assert "text=None" not in result["error"]++ def test_elevenlabs_error_body_returns_failure_envelope(self, monkeypatch, sample_ogg):+ monkeypatch.setenv("ELEVENLABS_API_KEY", "eleven-test-key")+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"text": None, "error": "Transcription failed"}++ with patch("tools.transcription_tools._load_stt_config", return_value={}), \+ patch("requests.post", return_value=mock_response):+ from tools.transcription_tools import _transcribe_elevenlabs+ result = _transcribe_elevenlabs(sample_ogg, "scribe_v2")++ assert result["success"] is False+ assert result["transcript"] == ""+ assert result["error"] == "Transcription failed"+# Shell safety — shlex.split on auto-detected templates# ============================================================================diff --git a/tools/transcription_cloud.py b/tools/transcription_cloud.pyindex 0e9369104f2..7c14eebf029 100644--- a/tools/transcription_cloud.py+++ b/tools/transcription_cloud.py@@ -20,7 +20,7 @@ from utils import is_truthy_valuefrom tools.transcription_audio import _transcode_audio_for_sttfrom tools.transcription_common import (DEFAULT_GROQ_STT_MODEL, DEFAULT_STT_MODEL, ELEVENLABS_STT_BASE_URL, GROQ_BASE_URL, GROQ_MODELS,- OPENAI_BASE_URL, OPENAI_MODELS, XAI_STT_BASE_URL, _error_result, _get_stt_section,+ OPENAI_BASE_URL, OPENAI_MODELS, STTResponseError, XAI_STT_BASE_URL, _error_result, _get_stt_section,_lazy_ensure_quietly, _log_prompt_unsupported, _ok_result)# Log-record parity with the origin module.@@ -67,6 +67,9 @@ def _with_openai_client(api_key: str, base_url: Optional[str], file_path: str, lAPIError = APIConnectionError = APITimeoutError = ()if isinstance(exc, PermissionError):return _error_result(f"Permission denied: {file_path}")+ if isinstance(exc, STTResponseError):+ # The provider's own message already reads as an error; no "Transcription failed:" prefix.+ return _error_result(str(exc))for cls, label in ((APIConnectionError, "Connection error"), (APITimeoutError, "Request timeout"),(APIError, "API error")):if isinstance(exc, cls):@@ -79,6 +82,8 @@ def _cloud_failure(exc: BaseException, file_path: str, label: str, detail: Optio"""Map a REST/SDK provider exception to the shared envelope (``label`` e.g. ``"xAI STT transcription"``)."""if isinstance(exc, PermissionError):return _error_result(f"Permission denied: {file_path}")+ if isinstance(exc, STTResponseError):+ return _error_result(str(exc))logger.error("%s failed: %s", label, exc, exc_info=True)return _error_result(f"{label} failed: {exc if detail is None else detail}")@@ -108,7 +113,9 @@ def _transcribe_groq(transcription = client.audio.transcriptions.create(file=audio_file, model=model_name,response_format="text",**_sdk_prompt_kwargs(language, prompt))- transcript_text = str(transcription).strip()+ # Shared normalizer, not ``str(transcription)``: a Groq-compatible endpoint answering with a+ # structured error object must not have its repr logged and returned as the transcript (#78098).+ transcript_text = _extract_transcript_text(transcription)logger.info("Transcribed %s via Groq API (%s, lang=%s, %d chars)",Path(file_path).name, model_name, language or "auto", len(transcript_text))return _ok_result(transcript_text, "groq")@@ -436,10 +443,27 @@ def _resolve_openai_audio_client_config() -> tuple[str, str]:def _extract_transcript_text(transcription: Any) -> str:- """Normalize text / object / dict transcription responses to a plain string."""- value = transcription if isinstance(transcription, str) else getattr(transcription, "text", None)- if not isinstance(value, str) and isinstance(transcription, dict):- value = transcription.get("text")- text = (value if isinstance(value, str) else str(transcription)).strip()+ """Normalize text / object / dict transcription responses to a plain string.++ A *structured* response (SDK object or JSON dict) whose ``text`` is missing or+ non-string must never reach ``str(transcription)``: that renders the object repr+ (``Transcription(text=None, logprobs=None, usage=None, error='...')``), which+ every caller then logged and returned as a successful transcript, and the desktop+ injected as the user's message (#78098). Such a response raises its provider+ ``error`` instead, so the callers' existing failure paths report it; a structured+ response carrying neither text nor error is an error in its own right.+ Unrecognized scalars keep the legacy stringification."""+ if isinstance(transcription, str):+ text = transcription.strip()+ else:+ is_mapping = isinstance(transcription, dict)+ value = transcription.get("text") if is_mapping else getattr(transcription, "text", None)+ if isinstance(value, str):+ text = value.strip()+ elif is_mapping or hasattr(transcription, "text"):+ error = transcription.get("error") if is_mapping else getattr(transcription, "error", None)+ raise STTResponseError(str(error) if error else "Transcription response contained no text")+ else:+ text = str(transcription).strip()match = _ASR_TEXT_RE.match(text)return match.group("text").strip() if match else textdiff --git a/tools/transcription_common.py b/tools/transcription_common.pyindex c860bdf3eb0..038e10fe9f0 100644--- a/tools/transcription_common.py+++ b/tools/transcription_common.py@@ -56,6 +56,15 @@ def _error_result(error: str, **extra: Any) -> Dict[str, Any]:return {"success": False, "transcript": "", "error": error, **extra}+class STTResponseError(ValueError):+ """A provider answered with a structured object carrying no transcript text.++ Raised by ``_extract_transcript_text`` when an SDK object or JSON body reports an+ ``error`` (or neither ``text`` nor ``error``) instead of a usable transcript. The+ message is the provider's own, so the STT failure paths surface it verbatim rather+ than stringifying the response object into its repr (#78098)."""++def _ok_result(transcript: str, provider: str) -> Dict[str, Any]:return {"success": True, "transcript": transcript, "provider": provider}