The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): share tts _origin/_section/_remove_quietly via delivery module; fold gemini json body parsing, media tag, stream reinit
Teknium45fb4040197e
diff --git a/tools/tts_tool.py b/tools/tts_tool.pyindex 5485725b6d2..51c05384268 100644--- a/tools/tts_tool.py+++ b/tools/tts_tool.py@@ -61,8 +61,8 @@ from tools.tool_backend_helpers import ( # noqa: F401 — seams patched by testfrom tools.tts_tool_delivery import ( # noqa: F401 — historical names re-exportedFALLBACK_MAX_TEXT_LENGTH, PROVIDER_MAX_TEXT_LENGTH, _resolve_max_text_length,AudioDeliveryProfile, _build_audio_delivery_files, _concat_audio_files, _convert_to_opus,- _pack_audio_files_for_delivery, _repair_ogg_container, _resolve_audio_delivery_profile,- _sniff_audio_container, _split_oversized_sentence, _split_text_for_tts, _wrap_pcm_as_wav,+ _pack_audio_files_for_delivery, _remove_quietly, _repair_ogg_container,+ _resolve_audio_delivery_profile, _sniff_audio_container, _split_oversized_sentence, _split_text_for_tts, _wrap_pcm_as_wav,)from tools.tts_tool_providers import ( # noqa: F401 — historical names re-exportedDEFAULT_ELEVENLABS_MODEL_ID, DEFAULT_ELEVENLABS_VOICE_ID, DEFAULT_GEMINI_TTS_MODEL,@@ -139,16 +139,9 @@ def _package_installed(name: str) -> bool:return False-def _check_neutts_available() -> bool:- return _package_installed("neutts")---def _check_kittentts_available() -> bool:- return _package_installed("kittentts")---def _check_piper_available() -> bool:- return _package_installed("piper")+def _check_neutts_available() -> bool: return _package_installed("neutts")+def _check_kittentts_available() -> bool: return _package_installed("kittentts")+def _check_piper_available() -> bool: return _package_installed("piper")# --- Defaults / config ---@@ -366,6 +359,12 @@ def _resolve_output_base(return file_path, None+def _media_tag(paths: List[str], voice_compatible: bool) -> str:+ """``MEDIA:<path>`` lines; the ``[[audio_as_voice]]`` marker asks the platform for a voice bubble."""+ media_tag = "\n".join(f"MEDIA:{path}" for path in paths)+ return f"[[audio_as_voice]]\n{media_tag}" if voice_compatible else media_tag++def _tool_failure(prefix: str, provider: str, exc: BaseException) -> str:"""Log and wrap a synthesis failure as the standard error envelope (traceback except for config errors)."""error_msg = f"{prefix} ({provider}): {exc}"@@ -403,16 +402,9 @@ def _text_to_speech_single(file_str = _repair_ogg_container(file_str)file_str, voice_compatible = _finalize_voice_delivery(file_str, provider, command_provider_config, want_opus)logger.info("TTS audio saved: %s (%s bytes, provider: %s)", file_str, f"{os.path.getsize(file_str):,}", provider)-- media_tag = f"MEDIA:{file_str}"- if voice_compatible:- media_tag = f"[[audio_as_voice]]\n{media_tag}"return json.dumps({- "success": True,- "file_path": file_str,- "media_tag": media_tag,- "provider": provider,- "voice_compatible": voice_compatible,+ "success": True, "file_path": file_str, "media_tag": _media_tag([file_str], voice_compatible),+ "provider": provider, "voice_compatible": voice_compatible,}, ensure_ascii=False)except ValueError as e:return _tool_failure("TTS configuration error", provider, e)@@ -510,23 +502,14 @@ def text_to_speech_tool()for path in final_paths:logger.info("TTS audio saved: %s (%s bytes, provider: %s)", path, f"{os.path.getsize(path):,}", provider)- media_tag = "\n".join(f"MEDIA:{path}" for path in final_paths)- if voice_compatible:- media_tag = f"[[audio_as_voice]]\n{media_tag}"-return json.dumps({- "success": True,- "file_path": final_paths[0],- "file_paths": final_paths,- "media_tag": media_tag,- "provider": chunk_results[0].get("provider", provider),- "voice_compatible": voice_compatible,- "chunk_count": len(chunks),- "delivery_file_count": len(final_paths),+ "success": True, "file_path": final_paths[0], "file_paths": final_paths,+ "media_tag": _media_tag(final_paths, voice_compatible),+ "provider": chunk_results[0].get("provider", provider), "voice_compatible": voice_compatible,+ "chunk_count": len(chunks), "delivery_file_count": len(final_paths),"combined_chunks": bool(combined_chunks),"delivery_profile": {- "platform": delivery_profile.platform,- "max_file_bytes": delivery_profile.max_file_bytes,+ "platform": delivery_profile.platform, "max_file_bytes": delivery_profile.max_file_bytes,"target_file_bytes": delivery_profile.target_file_bytes,},}, ensure_ascii=False)@@ -540,10 +523,7 @@ def text_to_speech_tool(final_absolute = {os.path.abspath(path) for path in final_paths}for artifact in generated_artifacts:if os.path.abspath(artifact) not in final_absolute:- try:- os.unlink(artifact)- except OSError:- pass+ _remove_quietly(artifact)# --- check_fn ---@@ -551,9 +531,9 @@ def text_to_speech_tool(def _minimax_requirements() -> bool:try:_resolve_minimax_tts_runtime(_load_tts_config())+ return Trueexcept ValueError:return False- return Truedef _xai_requirements() -> bool:diff --git a/tools/tts_tool_delivery.py b/tools/tts_tool_delivery.pyindex 34e3a834861..ced0d9b9b56 100644--- a/tools/tts_tool_delivery.py+++ b/tools/tts_tool_delivery.py@@ -32,6 +32,20 @@ from tools.tts_command_provider import (logger = logging.getLogger("tools.tts_tool")++def _origin():+ """``tools.tts_tool``, resolved per call so seams monkeypatched there still apply."""+ from tools import tts_tool++ return tts_tool+++def _section(tts_config: Any, key: str) -> Dict[str, Any]:+ """``tts.<key>`` as a dict (``null``/non-dict sections read as empty)."""+ section = tts_config.get(key) if isinstance(tts_config, dict) else None+ return section if isinstance(section, dict) else {}++# Final fallback when provider isn't recognised at all.FALLBACK_MAX_TEXT_LENGTH = 4000@@ -79,9 +93,7 @@ def _resolve_max_text_length(provider: Optional[str], tts_config: Optional[Dict[return FALLBACK_MAX_TEXT_LENGTHkey = provider.lower().strip()cfg = tts_config or {}- prov_cfg = cfg.get(key)- if not isinstance(prov_cfg, dict):- prov_cfg = {}+ prov_cfg = _section(cfg, key)override = _positive_int(prov_cfg.get("max_text_length"))if override:return override@@ -240,11 +252,13 @@ def _ffmpeg_run()-def _remove_quietly(path) -> None:- try:- os.remove(path)- except OSError:- pass+def _remove_quietly(path: Optional[str]) -> None:+ """Best-effort unlink (missing/locked files are ignored); None is a no-op."""+ if path:+ try:+ os.remove(path)+ except OSError:+ passdef _wav_sidecar_path(output_path: str) -> str:diff --git a/tools/tts_tool_lifecycle.py b/tools/tts_tool_lifecycle.pyindex cb2ca73ac7d..3443dea0587 100644--- a/tools/tts_tool_lifecycle.py+++ b/tools/tts_tool_lifecycle.py@@ -23,6 +23,7 @@ from tools.tts_command_provider import (command_env_passthrough as _command_provider_env_passthrough,render_command_template as _render_command_tts_template,)+from tools.tts_tool_delivery import _originfrom tools.tts_tool_local import (_LOCAL_TTS_MODEL_CACHES, _load_kittentts_model_for_config, _load_piper_voice_for_config,)@@ -30,14 +31,6 @@ from tools.tts_tool_plugins import _lookup_plugin_providerlogger = logging.getLogger("tools.tts_tool")--def _origin():- """``tools.tts_tool``, resolved per call so monkeypatched seams there still apply."""- from tools import tts_tool-- return tts_tool--_tts_lease_lock = threading.Lock()_tts_leases: set = set()diff --git a/tools/tts_tool_local.py b/tools/tts_tool_local.pyindex db1de1b4dfc..f32785a95aa 100644--- a/tools/tts_tool_local.py+++ b/tools/tts_tool_local.py@@ -15,7 +15,7 @@ import sysfrom pathlib import Pathfrom typing import Any, Callable, Dict, Tuple-from tools.tts_tool_delivery import _finalize_wav_output, _wav_sidecar_path+from tools.tts_tool_delivery import _finalize_wav_output, _origin, _section, _wav_sidecar_pathlogger = logging.getLogger("tools.tts_tool")@@ -24,13 +24,6 @@ DEFAULT_KITTENTTS_VOICE = "Jasper"DEFAULT_PIPER_VOICE = "en_US-lessac-medium" # balanced size/quality_NEUTTS_SAMPLES = Path(__file__).parent / "neutts_samples"--def _origin():- from tools import tts_tool-- return tts_tool--# --- Bounded model caches ---# Each cached entry is a whole loaded model (tens of MB); an unbounded dict would pin one# per distinct voice for the process lifetime. Most sessions use one or two voices and a@@ -58,10 +51,6 @@ def _tts_cache_get_or_load(cache: Dict[str, Any], key: str, load: Callable[[], Areturn value-def _section(tts_config: Any, key: str) -> Dict[str, Any]:- return (tts_config.get(key) or {}) if isinstance(tts_config, dict) else {}--def _run_helper(cmd: list, timeout: int) -> subprocess.CompletedProcess:return subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout, stdin=subprocess.DEVNULL,diff --git a/tools/tts_tool_openai.py b/tools/tts_tool_openai.pyindex 8952bffe796..725b71b264c 100644--- a/tools/tts_tool_openai.py+++ b/tools/tts_tool_openai.py@@ -17,18 +17,11 @@ from urllib.parse import urljoinfrom tools.tool_backend_helpers import (NOUS_MANAGED_PROVIDER, nous_tool_gateway_unavailable_message, selection_error,)+from tools.tts_tool_delivery import _origin, _sectionfrom tools.tts_tool_providers import _tts_response_format_from_pathlogger = logging.getLogger("tools.tts_tool")--def _origin():- """``tools.tts_tool``, resolved per call so monkeypatched seams there still apply."""- from tools import tts_tool-- return tts_tool--DEFAULT_OPENAI_MODEL = "gpt-4o-mini-tts"# The managed OpenAI audio gateway only proxies these; anything else is 400 "Unsupported".MANAGED_OPENAI_TTS_MODELS = frozenset({"gpt-4o-mini-tts"})@@ -45,19 +38,13 @@ def _managed_openai_audio_route() -> Optional[tuple]:return gateway.nous_user_token, urljoin(f"{gateway.gateway_origin.rstrip('/')}/", "v1"), True-def _openai_section(tts_config: Any, key: str) -> Dict[str, Any]:- """``tts.<key>`` as a dict (``tts.openai: null`` in YAML yields None — coalesce so .get() is safe)."""- section = tts_config.get(key) if isinstance(tts_config, dict) else None- return section if isinstance(section, dict) else {}--def _resolve_openai_audio_client_config() -> tuple[str, str, bool]:"""``(api_key, base_url, is_managed)`` for the OpenAI audio client (``is_managed`` = the restrictedNous proxy, so callers coerce the request). Strict on the stored ``tts`` selection: ``"nous"``→ managed ONLY (error if unavailable); any other → direct credentials ONLY (``tts.openai.api_key``then ``VOICE_TOOLS_OPENAI_KEY``/``OPENAI_API_KEY``); unset → config key → env key → managed."""origin = _origin()- openai_cfg = _openai_section(origin._load_tts_config(), "openai")+ openai_cfg = _section(origin._load_tts_config(), "openai")direct_base = openai_cfg.get("base_url") or DEFAULT_OPENAI_BASE_URLselected = origin.read_selection("tts")@@ -98,16 +85,10 @@ def _has_openai_audio_backend() -> bool:def _generate_openai_tts(- text: str,- output_path: str,- tts_config: Dict[str, Any],- *,- api_key: Optional[str] = None,- base_url: Optional[str] = None,- model: Optional[str] = None,- voice: Optional[str] = None,- speed: Optional[float] = None,- instructions: Optional[str] = None) -> str:+ text: str, output_path: str, tts_config: Dict[str, Any], *, api_key: Optional[str] = None,+ base_url: Optional[str] = None, model: Optional[str] = None, voice: Optional[str] = None,+ speed: Optional[float] = None, instructions: Optional[str] = None,+) -> str:"""Generate audio via the OpenAI ``audio.speech.create`` SDK shape.Explicit kwargs let OpenAI-compatible backends (DeepInfra) supply credentials/model/voice@@ -120,7 +101,7 @@ def _generate_openai_tts(if api_key is None:api_key, fallback_base, is_managed = _origin()._resolve_openai_audio_client_config()- oai_config = _openai_section(tts_config, "openai")+ oai_config = _section(tts_config, "openai")if model is None:model = oai_config.get("model", DEFAULT_OPENAI_MODEL)if voice is None:@@ -178,7 +159,7 @@ def _generate_deepinfra_tts(text: str, output_path: str, tts_config: Dict[str, Aif not api_key:raise ValueError("DEEPINFRA_API_KEY not set. Run `hermes setup` to configure, or set the env var directly.")- di_config = _openai_section(tts_config, "deepinfra")+ di_config = _section(tts_config, "deepinfra")from hermes_cli.models import deepinfra_base_url, deepinfra_model_idsmodel = di_config.get("model")@@ -192,12 +173,7 @@ def _generate_deepinfra_tts(text: str, output_path: str, tts_config: Dict[str, A)model = candidates[0]return _origin()._generate_openai_tts(- text,- output_path,- tts_config,- api_key=api_key,- base_url=deepinfra_base_url(di_config),- model=model,- voice=di_config.get("voice", DEFAULT_DEEPINFRA_TTS_VOICE),+ text, output_path, tts_config, api_key=api_key, base_url=deepinfra_base_url(di_config),+ model=model, voice=di_config.get("voice", DEFAULT_DEEPINFRA_TTS_VOICE),speed=float(di_config.get("speed", tts_config.get("speed", 1.0))),)diff --git a/tools/tts_tool_plugins.py b/tools/tts_tool_plugins.pyindex 5e8a690f429..42c94573453 100644--- a/tools/tts_tool_plugins.py+++ b/tools/tts_tool_plugins.py@@ -62,11 +62,8 @@ def _dispatch_to_plugin_provider(text: str, output_path: str, provider: str, tts# voice/model/speed/format are optional per the TTSProvider.synthesize contract;# providers fall back to their own defaults on None.cfg = tts_config if isinstance(tts_config, dict) else {}- voice = cfg.get("voice")- model = cfg.get("model")- speed = cfg.get("speed")+ voice, model, speed = cfg.get("voice"), cfg.get("model"), cfg.get("speed")fmt = cfg.get("output_format", DEFAULT_COMMAND_TTS_OUTPUT_FORMAT)-logger.info("Generating speech with plugin TTS provider '%s'...", key)written = plugin_provider.synthesize(text, output_path,diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.pyindex 43c925d3d5b..114a8a95e64 100644--- a/tools/tts_tool_providers.py+++ b/tools/tts_tool_providers.py@@ -20,19 +20,11 @@ from pathlib import Pathfrom typing import Any, Dict, Optionalfrom urllib.parse import urlparse-from tools.tts_tool_delivery import _wrap_pcm_as_wav, _write_wav_bytes_as+from tools.tts_tool_delivery import _origin, _section, _wrap_pcm_as_wav, _write_wav_bytes_asfrom tools.xai_http import hermes_xai_user_agentlogger = logging.getLogger("tools.tts_tool")--def _origin():- """``tools.tts_tool``, resolved per call so monkeypatched seams there still apply."""- from tools import tts_tool-- return tts_tool--DEFAULT_EDGE_VOICE = "en-US-AriaNeural"DEFAULT_ELEVENLABS_VOICE_ID = "pNInz6obpgDQGcFmaJgB" # AdamDEFAULT_ELEVENLABS_MODEL_ID = "eleven_multilingual_v2"@@ -71,18 +63,12 @@ _FALSE_WORDS = {"0", "false", "no", "off", "disabled"}def _config_bool(value: Any, default: bool = False) -> bool:"""Coerce common YAML/env bool spellings without treating random strings as true."""- if isinstance(value, bool):- return value- if value is None:- return default- if isinstance(value, (int, float)):+ if isinstance(value, (bool, int, float)):return bool(value)if isinstance(value, str):normalized = value.strip().lower()- if normalized in _TRUE_WORDS:- return True- if normalized in _FALSE_WORDS:- return False+ if normalized in _TRUE_WORDS or normalized in _FALSE_WORDS:+ return normalized in _TRUE_WORDSreturn default@@ -94,12 +80,6 @@ def _tts_response_format_from_path(output_path: str) -> str:return "mp3"-def _section(tts_config: Dict[str, Any], key: str) -> Dict[str, Any]:- """``tts.<key>`` as a dict (``null``/non-dict sections read as empty)."""- section = tts_config.get(key) if isinstance(tts_config, dict) else None- 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 ""@@ -157,12 +137,11 @@ def _read_tts_response_bytes(response: Any, *, label: str, limit: Optional[int]_close_response(response)-def _read_tts_response_json(response: Any, *, label: str, limit: Optional[int] = None) -> Dict[str, Any]:- raw = _read_tts_response_bytes(response, label=label, limit=limit)+def _parse_json_body(response: Any, raw: bytes) -> Dict[str, Any]:+ """JSON from the already-read *raw* body. Unit-test doubles often only provide ``.json()``;+ real ``requests`` responses took the streaming path, so production never buffers eagerly."""if raw:return json.loads(raw.decode("utf-8"))- # Unit-test doubles often only provide `.json()`; real requests.Response- # objects took the streaming path above, so production never buffers eagerly.if not _response_has_explicit_stream(response):json_reader = getattr(response, "json", None)if callable(json_reader):@@ -171,6 +150,10 @@ def _read_tts_response_json(response: Any, *, label: str, limit: Optional[int] =return {}+def _read_tts_response_json(response: Any, *, label: str, limit: Optional[int] = None) -> Dict[str, Any]:+ return _parse_json_body(response, _read_tts_response_bytes(response, label=label, limit=limit))++def _write_bytes(output_path: str, audio_bytes: bytes) -> str:with open(output_path, "wb") as f:f.write(audio_bytes)@@ -654,15 +637,10 @@ def _gemini_error_detail(response: Any) -> str:"""Best-effort ``error.message`` from a non-200 Gemini reply, else the first 300 body chars."""raw_body = _read_tts_response_bytes(response, label="Gemini TTS")try:- if raw_body:- err = json.loads(raw_body.decode("utf-8")).get("error", {})- elif not _response_has_explicit_stream(response) and callable(getattr(response, "json", None)):- err = response.json().get("error", {})- else:- err = {}- return err.get("message") or raw_body.decode("utf-8", errors="replace")[:300]+ message = _parse_json_body(response, raw_body).get("error", {}).get("message")except Exception:- return raw_body.decode("utf-8", errors="replace")[:300]+ message = None+ return message or raw_body.decode("utf-8", errors="replace")[:300]def _generate_gemini_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:@@ -706,13 +684,12 @@ def _generate_gemini_tts(text: str, output_path: str, tts_config: Dict[str, Any]headers = {"Content-Type": "application/json"}if urlparse(base_url).hostname == "generativelanguage.googleapis.com":try:- import hermes_cli as _hermes_cli+ import hermes_cli- _hermes_version = str(_hermes_cli.__version__)+ version = str(hermes_cli.__version__)except Exception:- _hermes_version = "0.0.0"- # Gemini partner-integration guidance: identify the client.- headers["X-Goog-Api-Client"] = f"hermes-agent/{_hermes_version}"+ version = "0.0.0"+ headers["X-Goog-Api-Client"] = f"hermes-agent/{version}" # partner-integration guidanceresponse = _post_json(f"{base_url}/models/{model}:generateContent", payload, headers, params={"key": api_key})if response.status_code != 200:diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.pyindex a1cebd7f2f7..dcfad75f1a8 100644--- a/tools/tts_tool_speaker.py+++ b/tools/tts_tool_speaker.py@@ -11,6 +11,7 @@ module are resolved through :func:`_origin` at call time.from __future__ import annotations+import contextlibimport loggingimport osimport platform@@ -20,22 +21,9 @@ import threadingfrom concurrent.futures import Future, ThreadPoolExecutorfrom typing import Callable, Iterable, Iterator, List, Optional-logger = logging.getLogger("tools.tts_tool")---def _origin():- from tools import tts_tool-- return tts_tool---def _unlink_quietly(path: Optional[str]) -> None:- if path:- try:- os.unlink(path)- except OSError:- pass+from tools.tts_tool_delivery import _origin, _remove_quietly as _unlink_quietly+logger = logging.getLogger("tools.tts_tool")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)."""@@ -75,10 +63,8 @@ def _play_via_tempfile(audio_iter: Iterable[bytes], stop_evt: threading.Event, slogger.warning("Temp-file TTS fallback failed: %s", exc)finally:if tmp is not None:- try:+ with contextlib.suppress(Exception):tmp.close() # idempotent; ensures close on early error- except Exception:- pass_unlink_quietly(tmp_path)@@ -195,17 +181,6 @@ class _StreamerPlayback:logger.warning("sounddevice OutputStream failed: %s", exc)return None- def _reinit_output_stream(self):- """Close the broken PortAudio stream and try to create a fresh one."""- self.close_output_stream()- try:- self.output_stream = self._create_output_stream()- logger.info("TTS: PortAudio output stream reinitialized after error")- except Exception as exc:- logger.warning("TTS: PortAudio stream reinit failed: %s", exc)- self.output_stream = None- return self.output_stream-def close_output_stream(self) -> None:"""Always release the device so a later stream can open it."""if self.output_stream is not None:@@ -262,17 +237,25 @@ class _StreamerPlayback:self._current_stream.write(self._np.frombuffer(buf, dtype="<i2").reshape(-1, 1))def _recover_stream(self) -> bool:- """Reinit the PortAudio stream after a failed write; False once ``_MAX_REINIT`` is exhausted."""- if self._reinit_count < self._MAX_REINIT:- self._reinit_count += 1- self._current_stream = self._reinit_output_stream()- return self._current_stream is not None- logger.warning(- "TTS: PortAudio reinit exhausted after %d attempts, falling back to tempfile for remaining sentences",- self._MAX_REINIT,- )- self._current_stream = None- return False+ """Close the broken PortAudio stream and open a fresh one after a failed write; False once+ ``_MAX_REINIT`` is exhausted (remaining sentences go through temp files)."""+ if self._reinit_count >= self._MAX_REINIT:+ logger.warning(+ "TTS: PortAudio reinit exhausted after %d attempts, falling back to tempfile for remaining sentences",+ self._MAX_REINIT,+ )+ self._current_stream = None+ return False+ self._reinit_count += 1+ self.close_output_stream()+ try:+ self.output_stream = self._create_output_stream()+ logger.info("TTS: PortAudio output stream reinitialized after error")+ except Exception as exc:+ logger.warning("TTS: PortAudio stream reinit failed: %s", exc)+ self.output_stream = None+ self._current_stream = self.output_stream+ return self._current_stream is not Nonedef _play_sentence_via_stream(self, chunk_queue) -> None:"""Write one sentence's PCM to PortAudio; after an unrecoverable write failure the rest is dropped."""@@ -302,8 +285,7 @@ class _StreamerPlayback:try:from tools.voice_mode import mark_audio_output_activeexcept Exception:- def mark_audio_output_active(_active):- return None+ mark_audio_output_active = lambda _active: None # noqa: E731self._np = _npself._reinit_count = 0