The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): reuse int16 aligner in speaker stream path; shared _require_key for tts providers
Tekniumaf4416a8288e
diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.pyindex a4eaf775ba6..9da7400887c 100644--- a/tools/tts_tool_providers.py+++ b/tools/tts_tool_providers.py@@ -100,6 +100,14 @@ def _section(tts_config: Dict[str, Any], key: str) -> Dict[str, Any]:return section if isinstance(section, dict) else {}+def _require_key(env_var: str, provider_id: str, hint: str) -> str:+ """Resolve *env_var* via the origin key resolver; ValueError ``"<ENV> not set. <hint>"`` when absent."""+ api_key = _origin()._resolve_provider_key(env_var, provider_id) or ""+ if not api_key:+ raise ValueError(f"{env_var} not set. {hint}")+ return api_key++# --- Bounded upstream response reading ---def _response_has_explicit_stream(response: Any) -> bool:@@ -258,13 +266,9 @@ def _elevenlabs_environment_kwargs(el_config: Dict[str, Any]) -> Dict[str, Any]:def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:- origin = _origin()- api_key = origin._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs") or ""- if not api_key:- raise ValueError("ELEVENLABS_API_KEY not set. Get one at https://elevenlabs.io/")-+ api_key = _require_key("ELEVENLABS_API_KEY", "elevenlabs", "Get one at https://elevenlabs.io/")el_config = tts_config.get("elevenlabs") or {}- client = origin._import_elevenlabs()(api_key=api_key, **_elevenlabs_environment_kwargs(el_config))+ client = _origin()._import_elevenlabs()(api_key=api_key, **_elevenlabs_environment_kwargs(el_config))audio_generator = client.text_to_speech.convert(text=text,voice_id=el_config.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID),@@ -555,16 +559,12 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any# --- Mistral (Voxtral TTS) — base64 audio, native Opus for voice bubbles ---def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:- origin = _origin()- api_key = origin._resolve_provider_key("MISTRAL_API_KEY", "mistral") or ""- if not api_key:- raise ValueError("MISTRAL_API_KEY not set. Get one at https://console.mistral.ai/")-+ api_key = _require_key("MISTRAL_API_KEY", "mistral", "Get one at https://console.mistral.ai/")mi_config = tts_config.get("mistral") or {}client_kwargs: Dict[str, Any] = {"api_key": api_key}if mi_config.get("base_url"):client_kwargs["server_url"] = mi_config["base_url"] # the Mistral SDK calls it server_url- Mistral = origin._import_mistral_client()+ Mistral = _origin()._import_mistral_client()try:with Mistral(**client_kwargs) as client:response = client.audio.speech.complete(diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.pyindex 6d7b2fd8c51..92525a8c2bd 100644--- a/tools/tts_tool_speaker.py+++ b/tools/tts_tool_speaker.py@@ -37,8 +37,8 @@ def _unlink_quietly(path: Optional[str]) -> None:pass-def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event) -> Iterator[bytes]:- """Yield int16-aligned byte chunks; a dangling odd byte is padded at the end."""+def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event, *, pad_tail: bool = True) -> Iterator[bytes]:+ """Yield int16-aligned byte chunks; a dangling odd byte is padded at the end (or dropped)."""leftover = b""for chunk in chunks:if stop_evt.is_set():@@ -48,7 +48,7 @@ def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event) -> Iif aligned_len >= 2:yield buf[:aligned_len]leftover = buf[aligned_len:] if aligned_len < len(buf) else b""- if leftover:+ if leftover and pad_tail:yield b"\x00"@@ -284,25 +284,17 @@ class _StreamerPlayback:if self._current_stream is None:self._play_sentence_via_tempfile(chunk_queue)return- pcm_leftover = b""- while True:- chunk = chunk_queue.get()- if chunk is None or self.stop_event.is_set():- return- buf = pcm_leftover + chunk- aligned_len = len(buf) - (len(buf) % 2)- if aligned_len >= 2:+ for aligned in _align_int16_chunks(iter(chunk_queue.get, None), self.stop_event, pad_tail=False):+ try:+ self._write_pcm(aligned)+ except Exception as write_exc:+ logger.warning("PortAudio write failed, attempting stream reinit: %s", write_exc)+ if not self._recover_stream():+ returntry:- self._write_pcm(buf[:aligned_len])- except Exception as write_exc:- logger.warning("PortAudio write failed, attempting stream reinit: %s", write_exc)- if not self._recover_stream():- return- try:- self._write_pcm(buf[:aligned_len])- except Exception:- pass- pcm_leftover = buf[aligned_len:] if aligned_len < len(buf) else b""+ self._write_pcm(aligned)+ except Exception:+ passdef _playback_worker(self) -> None:"""Single consumer: play audio segments from the queue in order."""