The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): fold streaming TTS provider bodies — inline single-use locals, drop async shim, squeeze import blanks
Teknium67a6769c6905
diff --git a/tools/tts_streaming.py b/tools/tts_streaming.pyindex a84625048f4..b08255d7cbd 100644--- a/tools/tts_streaming.py+++ b/tools/tts_streaming.py@@ -32,7 +32,6 @@ def _resolve_key(env_var: str, provider_id: str) -> str:"""try:from tools.tts_tool import _resolve_provider_key-return _resolve_provider_key(env_var, provider_id) or ""except Exception:return get_env_value(env_var) or ""@@ -98,8 +97,7 @@ class SentenceChunker:def flush(self) -> List[str]:"""Drain the tail (end-of-text or long-idle flush)."""- tail = _THINK_BLOCK_RE.sub("", self.buf).strip()- self.buf = ""+ tail, self.buf = _THINK_BLOCK_RE.sub("", self.buf).strip(), ""return [tail] if tail else []@@ -164,11 +162,7 @@ def resolve_streaming_provider("""pinned = str((tts_config.get("streaming") or {}).get("provider") or "").lower().strip()if pinned == "auto":- for name in _PROVIDER_PRIORITY:- inst = _try_instantiate(name, tts_config)- if inst is not None:- return inst- return None+ return next((inst for name in _PROVIDER_PRIORITY if (inst := _try_instantiate(name, tts_config))), None)return _try_instantiate(pinned or (preferred or _get_provider(tts_config)).lower().strip(), tts_config)@@ -198,26 +192,23 @@ class ElevenLabsStreamer(StreamingTTSProvider):from tools.tts_tool_providers import (DEFAULT_ELEVENLABS_STREAMING_MODEL_ID, DEFAULT_ELEVENLABS_VOICE_ID, _elevenlabs_environment_kwargs,)-client = _import_elevenlabs()(api_key=_resolve_key("ELEVENLABS_API_KEY", "elevenlabs"), **_elevenlabs_environment_kwargs(self.section),)- voice_id = self.section.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID)- model_id = self.section.get(- "streaming_model_id", self.section.get("model_id", DEFAULT_ELEVENLABS_STREAMING_MODEL_ID),- )yield from client.text_to_speech.convert(- text=text, voice_id=voice_id, model_id=model_id, output_format="pcm_24000",+ text=text, voice_id=self.section.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID),+ model_id=self.section.get("streaming_model_id",+ self.section.get("model_id", DEFAULT_ELEVENLABS_STREAMING_MODEL_ID)),+ output_format="pcm_24000",)def _openai_config_api_key() -> str:"""Return ``tts.openai.api_key`` from config.yaml, or empty string."""try:- openai_cfg = (_load_tts_config().get("openai") or {})+ return (_load_tts_config().get("openai") or {}).get("api_key") or ""except Exception:return ""- return openai_cfg.get("api_key") or ""@register("openai")@@ -232,7 +223,6 @@ class OpenAIStreamer(StreamingTTSProvider):def stream(self, text: str) -> Iterator[bytes]:from openai import OpenAI-client = OpenAI(api_key=(self.section.get("api_key") or resolve_openai_audio_api_key()),base_url=(self.section.get("base_url") or get_env_value("OPENAI_BASE_URL") or None),@@ -257,13 +247,10 @@ class GeminiStreamer(StreamingTTSProvider):def stream(self, text: str) -> Iterator[bytes]:import base64import json as _json-import requests-from tools.tts_tool_providers import (DEFAULT_GEMINI_TTS_BASE_URL, DEFAULT_GEMINI_TTS_MODEL, DEFAULT_GEMINI_TTS_VOICE,)-api_key = _gemini_key()model = str(self.section.get("model", DEFAULT_GEMINI_TTS_MODEL)).strip() or DEFAULT_GEMINI_TTS_MODELvoice = str(self.section.get("voice", DEFAULT_GEMINI_TTS_VOICE)).strip() or DEFAULT_GEMINI_TTS_VOICE@@ -288,13 +275,11 @@ class GeminiStreamer(StreamingTTSProvider):if not line or not line.startswith("data: "):continuetry:- event = _json.loads(line[len("data: "):])- parts = event["candidates"][0]["content"]["parts"]+ parts = _json.loads(line[len("data: "):])["candidates"][0]["content"]["parts"]except (ValueError, KeyError, IndexError, TypeError):continuefor part in parts:- inline = part.get("inlineData") or part.get("inline_data") or {}- b64 = inline.get("data", "")+ b64 = (part.get("inlineData") or part.get("inline_data") or {}).get("data", "")if not b64:continuetry:@@ -320,9 +305,7 @@ class XAIStreamer(StreamingTTSProvider):def available() -> bool:try:from tools.xai_http import resolve_xai_http_credentials-- creds = resolve_xai_http_credentials()- return bool(str(creds.get("api_key") or "").strip())+ return bool(str(resolve_xai_http_credentials().get("api_key") or "").strip())except Exception:return False@@ -332,21 +315,16 @@ class XAIStreamer(StreamingTTSProvider):def _collect_async(self, text: str) -> List[bytes]:import asyncio- return asyncio.run(self._drain_async(text))-- async def _drain_async(self, text: str) -> List[bytes]:- return [frame async for frame in self._async_frames(text)]+ async def _drain() -> List[bytes]:+ return [frame async for frame in self._async_frames(text)]+ return asyncio.run(_drain())async def _async_frames(self, text: str):import json as _json-import websockets-from tools.tts_tool_providers import DEFAULT_XAI_VOICE_IDfrom tools.xai_http import resolve_xai_http_credentials-- creds = resolve_xai_http_credentials()- api_key = str(creds.get("api_key") or "").strip()+ api_key = str(resolve_xai_http_credentials().get("api_key") or "").strip()if not api_key:raise RuntimeError("No xAI credentials for streaming TTS")voice = str(self.section.get("voice_id", DEFAULT_XAI_VOICE_ID)).strip() or DEFAULT_XAI_VOICE_ID@@ -367,15 +345,13 @@ class XAIStreamer(StreamingTTSProvider):returncontinueetype = envelope.get("type")- if etype == "done":- returnif etype == "error":logger.warning("xAI WS error envelope: %s", envelope.get("error") or envelope.get("message") or envelope,)+ if etype in ("done", "error"):returnexcept Exception as exc:- if exc.__class__.__name__ == "ConnectionClosed":- return- logger.warning("xAI WS receive failed: %s", exc)+ if exc.__class__.__name__ != "ConnectionClosed":+ logger.warning("xAI WS receive failed: %s", exc)return