The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tts): honor the PCM sample rate reported by OpenAI-compatible endpoints
webtecnica3e212b7decdb
diff --git a/gateway/streaming_tts_consumer.py b/gateway/streaming_tts_consumer.pyindex f3d7ddd7660..af57a8d7c68 100644--- a/gateway/streaming_tts_consumer.py+++ b/gateway/streaming_tts_consumer.py@@ -24,6 +24,10 @@ _ABORT = object()_DONE = object()+class _HandleDeclined(Exception):+ """The adapter declined ``begin_streaming_tts`` when the first PCM chunk arrived."""++class StreamingTTSConsumer:"""Consumes LLM text deltas and produces streaming PCM audio for an adapter."""@@ -35,10 +39,9 @@ class StreamingTTSConsumer:# Resolved once; None => inactive, gateway falls back to whole-file TTS.self._streamer = resolve_streaming_provider(tts_config)self._chunker = SentenceChunker()- self._audio_format = audio_format or AudioFormat() if self._streamer is None else (- AudioFormat(**{f: int(getattr(self._streamer, f, getattr(AudioFormat, f)))- for f in ("sample_rate", "channels", "sample_width")})- )+ # Provisional: refreshed from the streamer when the handle opens on the first PCM chunk,+ # since an OpenAI-compatible endpoint reports its real rate only in the response (#76466).+ self._audio_format = audio_format or AudioFormat() if self._streamer is None else self._streamer_format()# Thread-safe queue of completed clauses plus the _DONE/_ABORT sentinels.self._queue: "queue.Queue[Any]" = queue.Queue(maxsize=256)self._handle: Optional[StreamingTTSHandle] = None@@ -47,6 +50,10 @@ class StreamingTTSConsumer:self._finished = self._dropped = self._suppress_whole_file = Falseself._lock, self._strip_markdown = threading.Lock(), None # stripper lazily imported+ def _streamer_format(self) -> AudioFormat:+ return AudioFormat(**{f: int(getattr(self._streamer, f, getattr(AudioFormat, f)))+ for f in ("sample_rate", "channels", "sample_width")})+active = property(lambda self: self._streamer is not None) # usable streaming providercompleted = property(lambda self: self._completed) # streaming audio fully deliveredpartial = property(lambda self: self._partial) # some audio audible before a failure/drop@@ -110,19 +117,16 @@ class StreamingTTSConsumer:def _settle(self, *, failed: bool) -> None:"""Set outcome flags from what was audible: never report completion after a failure or adropped clause; keep suppression whenever audio was audible (no replay from the start)."""- audible, degraded = self._handle.audible, failed or self._dropped+ audible, degraded = bool(self._handle and self._handle.audible), failed or self._droppedself._completed = audible and not degradedself._partial = self._partial or (audible and degraded)self._suppress_whole_file = audibleasync def _open_handle(self) -> bool:- """Open the adapter's streaming-audio handle; False when unsupported or begin failed."""- if not self.active:- return False- if not self._adapter.supports_streaming_tts(self._chat_id, self._audio_format):- name = getattr(self._adapter, "name", "?")- logger.debug("adapter %s does not support streaming TTS", name)- return False+ """Open the adapter's streaming-audio handle at the streamer's now-final format; False when+ begin failed. Called from the first PCM chunk, not before the provider answered."""+ if self._streamer is not None:+ self._audio_format = self._streamer_format()try:self._handle = await self._adapter.begin_streaming_tts(self._chat_id, self._audio_format, metadata=self._metadata@@ -135,7 +139,8 @@ class StreamingTTSConsumer:async def _run(self) -> None:"""Drain clauses until a sentinel/abort, synthesise + write each, then finalise the stream;a clause or finalise failure settles the outcome flags and aborts the adapter stream."""- if not await self._open_handle():+ if not self.active or not self._adapter.supports_streaming_tts(self._chat_id, self._audio_format):+ logger.debug("adapter %s does not support streaming TTS", getattr(self._adapter, "name", "?"))returnself._suppress_whole_file = Falsetry:@@ -150,6 +155,8 @@ class StreamingTTSConsumer:continuetry:await self._synthesise_and_write(item)+ except _HandleDeclined:+ return # nothing audible yet: gateway falls back to whole-file TTSexcept Exception as exc:logger.warning("streaming TTS clause failed: %s", exc)self._settle(failed=True)@@ -175,7 +182,7 @@ class StreamingTTSConsumer:async def _synthesise_and_write(self, clause: str) -> None:"""Synthesise one clause via the streamer and write PCM chunks."""- if self._handle is None or self._handle.aborted or self._streamer is None:+ if self._streamer is None or (self._handle is not None and self._handle.aborted):returnif self._strip_markdown is None: # lazy import: tools.tts_tool would cycle at module loadtry:@@ -189,10 +196,12 @@ class StreamingTTSConsumer:while True:# next() runs in a thread so a blocking provider never stalls the loop.chunk = await asyncio.to_thread(next, iterator, _DONE)- if chunk is _DONE or self._aborted or self._handle.aborted:+ if chunk is _DONE or self._aborted or (self._handle is not None and self._handle.aborted):returnif not chunk:continue+ if self._handle is None and not await self._open_handle():+ raise _HandleDeclined()was_audible = self._handle.audibleawait self._adapter.write_streaming_tts(self._handle, chunk)if not was_audible:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 5f0970c3936..7c507d0f69d 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1032,6 +1032,9 @@ DEFAULT_CONFIG = {# gpt-4o-mini-tts voices: alloy, ash, ballad, cedar, coral, echo, fable, marin, nova,# onyx, sage, shimmer, verse"voice": "alloy",+ # Raw PCM rate for streaming playback. OpenAI emits 24 kHz; a compatible endpoint that+ # reports its rate (X-Audio-Sample-Rate header) overrides this automatically.+ "pcm_sample_rate": 24000,},"gemini": {"model": "gemini-2.5-flash-preview-tts",diff --git a/tests/gateway/test_streaming_tts_consumer.py b/tests/gateway/test_streaming_tts_consumer.pyindex 95893da118b..a35fdbe74c6 100644--- a/tests/gateway/test_streaming_tts_consumer.py+++ b/tests/gateway/test_streaming_tts_consumer.py@@ -529,9 +529,11 @@ class TestFallbackSafety:consumer.finish()completed = await consumer.wait_complete(timeout=5.0)- # Pre-audio failure: should NOT report completed (fall back)+ # Pre-audio failure: should NOT report completed (fall back); the adapter handle is+ # only opened on the first PCM chunk (#76466), so nothing was begun or aborted.assert completed is False- assert adapter.abort_count >= 1+ assert consumer.suppress_whole_file is False+ assert adapter.begin_count == 0_run_test(run)@@ -785,3 +787,28 @@ class TestGatewayOuterFinalisationNoNameError:# This is trivially true with a holder, but was NOT true when# the consumer was a run_sync local._ = holder[0]+++class TestEndpointReportedRate:+ """Issue #76466: the adapter handle opens with the rate the provider learned from the+ endpoint's response, not the construction-time default."""++ def test_begin_uses_rate_learned_on_first_chunk(self):+ class _Learns(FakeStreamer):+ def stream(self, text):+ self.sample_rate = 44100+ yield from super().stream(text)++ async def run(loop):+ adapter = FakeVoiceAdapter()+ consumer = _make_consumer(adapter, "chat1", loop, _Learns(chunks_per_clause=2))+ assert consumer._audio_format.sample_rate == 24000 # provisional+ consumer.start()+ consumer.on_delta("A sentence. ")+ consumer.finish()+ assert await consumer.wait_complete(timeout=5.0) is True+ assert adapter.begin_count == 1+ assert adapter.handle.audio_format.sample_rate == 44100+ assert len(adapter.written_chunks) == 2++ _run_test(run)diff --git a/tests/tools/test_tts_streaming.py b/tests/tools/test_tts_streaming.pyindex 58fa2f5731d..5737990a482 100644--- a/tests/tools/test_tts_streaming.py+++ b/tests/tools/test_tts_streaming.py@@ -1006,3 +1006,102 @@ def test_sync_pipeline_cleans_temp_files(monkeypatch):assert created, "expected temp files to be created via mkstemp"leftovers = [p for p in created if os.path.exists(p)]assert not leftovers, f"temp files not cleaned: {leftovers}"+++# ── #76466: honor the endpoint-reported PCM sample rate ────────────────────++class _FakeSpeechResponse:+ """Stand-in for the OpenAI SDK streaming response context manager."""++ def __init__(self, headers, chunks):+ self.headers, self._chunks = headers, chunks++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def iter_bytes(self):+ yield from self._chunks+++def _patch_openai_speech(monkeypatch, headers):+ calls = []++ class _Speech:+ class with_streaming_response:+ @staticmethod+ def create(**kw):+ calls.append(kw)+ return _FakeSpeechResponse(headers, [b"\x01\x00" * 100])++ class _Client:+ def __init__(self, **kw):+ self.audio = MagicMock(speech=_Speech())++ import openai+ monkeypatch.setattr(openai, "OpenAI", _Client)+ return calls+++def test_openai_streamer_honors_endpoint_reported_rate_in_wav_playback(monkeypatch):+ """Issue #76466: an OpenAI-compatible endpoint answering 44.1 kHz PCM (X-Audio-Sample-Rate)+ must drive the WAV header written for playback, and the static ``pcm_sample_rate`` config is+ the pre-request expectation; neither may stay pinned to 24 kHz."""+ import wave+ from tools import tts_tool_speaker as sp++ _patch_openai_speech(monkeypatch, {"content-type": "audio/pcm", "x-audio-sample-rate": "44100"})+ streamer = ts.OpenAIStreamer({}, {"api_key": "sk-x", "pcm_sample_rate": "22050"})+ assert streamer.sample_rate == 22050 # validated static expectation (from PR #74021)++ wav_rates = []++ def _fake_play(path):+ with wave.open(path, "rb") as wf:+ wav_rates.append(wf.getframerate())++ monkeypatch.setattr(sp._StreamerPlayback, "_device_usable", lambda self: False)+ with patch("tools.voice_mode.play_audio_file", side_effect=_fake_play):+ playback = sp._StreamerPlayback(streamer, threading.Event())+ playback.speak("One sentence.")+ playback.finish()+ assert streamer.sample_rate == 44100+ assert wav_rates == [44100]++ assert ts.OpenAIStreamer({}, {"pcm_sample_rate": "bogus"}).sample_rate == 24000+ assert ts._sample_rate_from_headers({"content-type": "audio/L16; rate=16000"}) == 16000+ assert ts._sample_rate_from_headers({"content-type": "audio/pcm"}) is None+++ sys.platform == "darwin",+ reason="macOS deliberately skips the sounddevice OutputStream path (PR #62601)",+)+def test_speaker_output_stream_opens_at_rate_learned_from_first_chunk(monkeypatch):+ """Issue #76466: the PortAudio device is opened after the first chunk arrived, at the rate+ the provider learned from the response, not at the construction-time default."""+ from tools import tts_tool+ from tools.tts_tool_speaker import stream_tts_to_speaker++ class _Learns(ts.StreamingTTSProvider):+ sample_rate = 24000++ @staticmethod+ def available():+ return True++ def stream(self, text):+ self.sample_rate = 44100 # what OpenAIStreamer does on the response headers+ yield b"\x01\x00" * 50++ sd, out = _sd_mock()+ q = _drain_queue(["The first sentence is long enough. ", "The second sentence is long enough too. "])+ stop, done = threading.Event(), threading.Event()+ with patch("tools.tts_streaming.resolve_streaming_provider", return_value=_Learns({}, {})), \+ patch.object(tts_tool, "_import_sounddevice", return_value=sd):+ stream_tts_to_speaker(q, stop, done)+ assert done.is_set()+ assert [c.kwargs["samplerate"] for c in sd.OutputStream.call_args_list] == [44100]+ assert out.write.call_count == 2diff --git a/tools/tts_streaming.py b/tools/tts_streaming.pyindex 71bc4a2cee5..e20f66980be 100644--- a/tools/tts_streaming.py+++ b/tools/tts_streaming.py@@ -97,7 +97,13 @@ class SentenceChunker:class StreamingTTSProvider(ABC):- """Yields raw int16, little-endian, mono PCM chunks at ``sample_rate`` (built-ins: 24 kHz)."""+ """Yields raw int16, little-endian, mono PCM chunks at ``sample_rate`` (built-ins: 24 kHz).++ ``sample_rate`` is provisional until ``stream()`` has yielded its first chunk: a provider may+ update the instance attribute once the endpoint's real format is known (OpenAI-compatible+ servers advertise it in the response headers), so consumers open their output device or WAV+ header after pulling the first chunk, never at construction.+ """sample_rate: int = 24000channels: int = 1@@ -201,9 +207,39 @@ def _openai_config_api_key() -> str:return ""+def _sample_rate_from_headers(headers) -> Optional[int]:+ """Rate an OpenAI-compatible TTS endpoint advertises: ``X-Audio-Sample-Rate`` (the convention+ local servers use) or ``rate=`` in ``Content-Type`` (``audio/pcm; rate=44100``); None if absent."""+ if not headers:+ return None+ raw = headers.get("x-audio-sample-rate")+ if raw is None:+ m = re.search(r"(?:^|[;\s])rate\s*=\s*(\d+)", str(headers.get("content-type") or ""), re.IGNORECASE)+ raw = m.group(1) if m else None+ try:+ rate = int(str(raw).strip())+ except (TypeError, ValueError):+ return None+ return rate if rate > 0 else None++@register("openai")class OpenAIStreamer(StreamingTTSProvider):- """OpenAI speech with ``response_format=pcm`` (24 kHz mono int16)."""+ """OpenAI speech with ``response_format=pcm`` (OpenAI itself: 24 kHz mono int16).++ Compatible servers may emit another rate: ``tts.openai.pcm_sample_rate`` sets the expected+ rate up front and a rate reported by the response (``X-Audio-Sample-Rate`` / Content-Type+ ``rate=``) overrides it before the first chunk is yielded (#76466).+ """++ def __init__(self, tts_config: Dict, section: Dict):+ super().__init__(tts_config, section)+ configured = section.get("pcm_sample_rate", self.sample_rate)+ if isinstance(configured, bool) or not isinstance(configured, (int, float, str)) \+ or not str(configured).strip().isdigit() or int(str(configured).strip()) <= 0:+ logger.warning("Invalid tts.openai.pcm_sample_rate %r; using %d Hz", configured, self.sample_rate)+ else:+ self.sample_rate = int(str(configured).strip())@staticmethoddef available() -> bool:@@ -219,6 +255,12 @@ class OpenAIStreamer(StreamingTTSProvider):model=self.section.get("model", "gpt-4o-mini-tts"), voice=self.section.get("voice", "alloy"),input=text, response_format="pcm",) as response:+ # Runs on the first next(), before any audio is yielded, so consumers reading+ # ``sample_rate`` after the first chunk open their device at the endpoint's rate.+ rate = _sample_rate_from_headers(getattr(response, "headers", None))+ if rate is not None and rate != self.sample_rate:+ logger.info("TTS endpoint reports %d Hz PCM (expected %d Hz); honoring it", rate, self.sample_rate)+ self.sample_rate = rateyield from _capped(response.iter_bytes(), "OpenAI streaming TTS")diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.pyindex 2d05938a7ec..eda39b69596 100644--- a/tools/tts_tool_speaker.py+++ b/tools/tts_tool_speaker.py@@ -11,6 +11,7 @@ playback). Origin seams are resolved through :func:`_origin` at call time.from __future__ import annotationsimport contextlib+import itertoolsimport loggingimport osimport platform@@ -139,7 +140,11 @@ class _StreamerPlayback:def __init__(self, streamer, stop_event: threading.Event):self.streamer, self.stop_event = streamer, stop_event- self.output_stream = self._open_output_stream()+ # The device is opened lazily, once the first sentence's first chunk has arrived: an+ # OpenAI-compatible endpoint reports its real PCM rate in the response headers, so+ # ``streamer.sample_rate`` is only trustworthy after the request answered (#76466).+ self.output_stream = None+ self._use_device = self._device_usable()self._audio_queue: "queue.Queue[Optional[queue.Queue[Optional[bytes]]]]" = queue.Queue()self._prefetch_threads: List[threading.Thread] = []self._prefetch_sem = threading.Semaphore(3)@@ -153,20 +158,35 @@ class _StreamerPlayback:stream.start()return stream- def _open_output_stream(self):+ def _device_usable(self) -> bool:# macOS skips sounddevice entirely: PortAudio/CoreAudio init triggers a# kTCCServiceMediaLibrary prompt though output needs no media-library access.- # None routes every sentence through tempfile -> afplay.- # See PR #62601 / #13291.+ # False routes every sentence through tempfile -> afplay. See PR #62601 / #13291.if platform.system() == "Darwin":- return None+ return Falsetry:- return self._create_output_stream()+ _origin()._import_sounddevice()except (ImportError, OSError) as exc:logger.debug("sounddevice not available, streamer→tempfile: %s", exc)+ return False+ return True++ def _ensure_output_stream(self) -> bool:+ """Open PortAudio at the streamer's *current* rate, reopening it when the rate changed+ (a different endpoint answered); False routes the sentence through a temp WAV."""+ rate = int(self.streamer.sample_rate)+ if self._current_stream is not None and self._current_rate == rate:+ return True+ if self._current_stream is None and self._reinit_count >= self._MAX_REINIT:+ return False+ self.close_output_stream()+ try:+ self.output_stream = self._create_output_stream()except Exception as exc:logger.warning("sounddevice OutputStream failed: %s", exc)- return None+ self.output_stream, self._reinit_count = None, self._MAX_REINIT # don't retry per sentence+ self._current_stream, self._current_rate = self.output_stream, rate+ return self._current_stream is not Nonedef close_output_stream(self) -> None:"""Always release the device so a later stream can open it."""@@ -203,7 +223,8 @@ class _StreamerPlayback:self._prefetch_sem.release()def _play_sentence_via_tempfile(self, chunk_queue) -> None:- _play_via_tempfile(_drain_chunks(chunk_queue), self.stop_event, self.streamer.sample_rate)+ chunks = _drain_chunks(chunk_queue) # drained first: the rate is final once chunks exist+ _play_via_tempfile(chunks, self.stop_event, self.streamer.sample_rate)def _for_each_sentence(self, play: Callable[[queue.Queue], None]) -> None:"""Feed queued sentences to *play* in order until the end sentinel; stopped sentences are skipped."""@@ -236,10 +257,15 @@ class _StreamerPlayback:def _play_sentence_via_stream(self, chunk_queue) -> None:"""Write one sentence's PCM to PortAudio; after an unrecoverable write failure the rest is dropped."""- if self._current_stream is None:- self._play_sentence_via_tempfile(chunk_queue)+ chunks = iter(chunk_queue.get, None)+ first = next(chunks, None) # blocks until the endpoint answered: the rate is final now+ if first is None:+ return+ chunks = itertools.chain([first], chunks)+ if not self._ensure_output_stream():+ _play_via_tempfile(list(chunks), self.stop_event, self.streamer.sample_rate)return- for aligned in _align_int16_chunks(iter(chunk_queue.get, None), self.stop_event, pad_tail=False):+ for aligned in _align_int16_chunks(chunks, self.stop_event, pad_tail=False):try:self._write_pcm(aligned)except Exception as write_exc:@@ -251,7 +277,7 @@ class _StreamerPlayback:def _playback_worker(self) -> None:"""Single consumer: play audio segments from the queue in order."""- if self.output_stream is None:+ if not self._use_device:self._for_each_sentence(self._play_sentence_via_tempfile)returnimport numpy as _np@@ -259,7 +285,7 @@ class _StreamerPlayback:from tools.voice_mode import mark_audio_output_activeexcept Exception:mark_audio_output_active = lambda _active: None # noqa: E731- self._np, self._reinit_count, self._current_stream = _np, 0, self.output_stream+ self._np, self._reinit_count, self._current_stream, self._current_rate = _np, 0, None, Nonemark_audio_output_active(True)try:self._for_each_sentence(self._play_sentence_via_stream)diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 4c8e471466a..828e28f13ec 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -2002,6 +2002,7 @@ tts:voice: "alloy" # alloy, echo, fable, onyx, nova, shimmerspeed: 1.0 # Speed multiplier (clamped to 0.25–4.0 by the API)base_url: "https://api.openai.com/v1" # Override for OpenAI-compatible TTS endpoints+ pcm_sample_rate: 24000 # Streaming PCM rate; overridden by the endpoint's X-Audio-Sample-Rate headerminimax:speed: 1.0 # Speech speed multiplier# base_url: "" # Optional: override for OpenAI-compatible TTS endpointsdiff --git a/website/docs/user-guide/features/tts.md b/website/docs/user-guide/features/tts.mdindex ecff510d470..a7e37623895 100644--- a/website/docs/user-guide/features/tts.md+++ b/website/docs/user-guide/features/tts.md@@ -56,6 +56,7 @@ tts:model: "gpt-4o-mini-tts"voice: "alloy" # alloy, echo, fable, onyx, nova, shimmerbase_url: "https://api.openai.com/v1" # Override for OpenAI-compatible TTS endpoints+ pcm_sample_rate: 24000 # Streaming PCM rate expected from the endpoint (auto-overridden by X-Audio-Sample-Rate)speed: 1.0 # 0.25 - 4.0# language: "es" # Sent as lang_code — only for OpenAI-compatible endpoints that support it (e.g. Kokoro)minimax:@@ -144,6 +145,8 @@ tts:The rewrite uses `auxiliary.tts_audio_tags` and defaults to your main chat model. Override that auxiliary task if you want tag insertion handled by a cheaper or faster model.+**Streaming sample rate (OpenAI-compatible endpoints)**: streaming playback receives headerless raw PCM, so Hermes must know its sample rate. The official OpenAI API emits 24 kHz. A compatible server that reports its rate — the `X-Audio-Sample-Rate` response header, or `rate=` in the `Content-Type` (`audio/pcm; rate=44100`) — is honored automatically: the speaker, the temp-WAV player and the gateway audio stream all open at the reported rate once the response arrives. For servers that report nothing, set `tts.openai.pcm_sample_rate` to the endpoint's output rate (e.g. `22050` for Piper-backed servers); otherwise speech plays at the wrong speed and pitch. Invalid values log a warning and fall back to `24000`.+**Language (OpenAI-compatible endpoints)**: `tts.openai.language` is forwarded to the endpoint as a `lang_code` request parameter. It is intended for OpenAI-compatible TTS servers that support `lang_code` — for example [Kokoro-FastAPI](https://github.com/remsky/Kokoro-FastAPI), where `language: "es"` selects the Spanish phonemizer instead of the English default. Leave it unset when using the official OpenAI API, which does not accept this parameter. When unset, nothing extra is sent.