Skip to content

The agent that grows with you

fix(tts): rewrite xAI streaming against the real WebSocket protocol

Adolaniumc3d50a7d08c4
diff --git a/tests/tools/test_tts_streaming.py b/tests/tools/test_tts_streaming.py
index 8bb9aefe027..3aa071c5e4e 100644
--- a/tests/tools/test_tts_streaming.py
+++ b/tests/tools/test_tts_streaming.py
@@ -1,9 +1,11 @@
"""Tests for the provider-agnostic streaming TTS backend (tools.tts_streaming)
and its dispatch through tools.tts_tool_speaker.stream_tts_to_speaker.
-No live audio or network: the ElevenLabs/OpenAI SDKs, sounddevice, and the sync
-synth path are all mocked. Covers the registry/resolver, provider availability,
-the chunked-streamer playback path, and the universal per-sentence sync fallback.
+No live audio or external network: the ElevenLabs/OpenAI SDKs, sounddevice, and
+the sync synth path are all mocked, and the xAI wire protocol runs against a
+loopback fake WebSocket server. Covers the registry/resolver, provider
+availability, the chunked-streamer playback path, and the universal per-sentence
+sync fallback.
"""
import os
@@ -254,15 +256,14 @@ def test_xai_streaming_prefers_explicit_api_key(monkeypatch):
assert tts_tool._xai_requirements() is True
assert calls and all(c.get("prefer_api_key") is True for c in calls)
- # _async_frames resolves before websockets.connect; an empty key raises first.
+ # stream() resolves before websockets.connect; an empty key raises first.
calls.clear()
ws_fake = types.ModuleType("websockets")
monkeypatch.setitem(sys.modules, "websockets", ws_fake)
fake.resolve_xai_http_credentials = lambda **kw: calls.append(kw) or {"api_key": ""}
streamer = ts.XAIStreamer({}, {"voice_id": "v"})
with pytest.raises(RuntimeError, match="No xAI credentials"):
- import asyncio
- asyncio.run(streamer._async_frames("hi").__anext__())
+ list(streamer.stream("hi"))
assert calls and calls[0].get("prefer_api_key") is True
@@ -272,6 +273,106 @@ def test_xai_streaming_prefers_explicit_api_key(monkeypatch):
# ── xAI WebSocket bridge ─────────────────────────────────────────────────
+def _fake_xai_server(handler):
+ """Serve ``handler`` on a loopback WS server; return (url, server)."""
+ from websockets.sync.server import serve
+
+ server = serve(handler, "127.0.0.1", 0)
+ port = server.socket.getsockname()[1]
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return f"ws://127.0.0.1:{port}/tts", server
+
+
[email protected]("profile", ["alpha", "beta"])
+def test_xai_stream_preserves_profile_and_delivers_before_completion(monkeypatch, tmp_path, profile):
+ import base64
+ import json
+ from urllib.parse import parse_qs, urlsplit
+
+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ home = tmp_path / profile
+ home.mkdir()
+ key = f"test-{profile}-key"
+ (home / ".env").write_text(f"XAI_API_KEY={key}\n", encoding="utf-8")
+ monkeypatch.setenv("XAI_API_KEY", "test-process-key")
+ first_delivered = threading.Event()
+ seen = {}
+ pcm = b"\x01\x00" * 30
+
+ def handler(ws):
+ seen["path"] = ws.request.path
+ seen["auth"] = ws.request.headers.get("Authorization")
+ seen["messages"] = [json.loads(ws.recv()), json.loads(ws.recv())]
+ ws.send(json.dumps({"type": "audio.delta", "delta": base64.b64encode(pcm).decode()}))
+ if not first_delivered.wait(timeout=10):
+ return
+ ws.send(json.dumps({"type": "audio.delta", "delta": base64.b64encode(pcm).decode()}))
+ ws.send(json.dumps({"type": "audio.done"}))
+
+ url, server = _fake_xai_server(handler)
+ home_token = set_hermes_home_override(home)
+ secret_token = set_secret_scope(build_profile_secret_scope(home))
+ try:
+ section = {"streaming_url": url, "voice_id": "test-voice", "language": "test-language"}
+ streamer = ts.XAIStreamer({}, section)
+ chunks = streamer.stream("A sentence.")
+ assert next(chunks) == pcm
+ assert seen["auth"] == f"Bearer {key}"
+ first_delivered.set()
+ assert list(chunks) == [pcm]
+ params = parse_qs(urlsplit(seen["path"]).query)
+ assert params["voice"] == [section["voice_id"]]
+ assert params["language"] == [section["language"]]
+ assert params["sample_rate"] == [str(streamer.sample_rate)]
+ assert params["codec"] == ["pcm"]
+ assert seen["messages"] == [
+ {"type": "text.delta", "delta": "A sentence."}, {"type": "text.done"},
+ ]
+ finally:
+ first_delivered.set()
+ reset_secret_scope(secret_token)
+ reset_hermes_home_override(home_token)
+ server.shutdown()
+
+
[email protected]("outcome", ["error", "byte-cap"])
+def test_xai_stream_reports_errors_and_bounds_received_audio(monkeypatch, outcome):
+ import base64
+ import json
+ from websockets.exceptions import ConnectionClosed
+ import tools.xai_http
+
+ monkeypatch.setattr(tools.xai_http, "resolve_xai_http_credentials", lambda **kw: {"api_key": "test-key"})
+ monkeypatch.setattr(ts, "_STREAM_SENTENCE_BYTE_CAP", 100)
+ closed = threading.Event()
+
+ def handler(ws):
+ ws.recv()
+ ws.recv()
+ if outcome == "error":
+ ws.send(json.dumps({"type": "error", "message": "example failure"}))
+ return
+ try:
+ while True:
+ ws.send(json.dumps({"type": "audio.delta", "delta": base64.b64encode(b"x" * 64).decode()}))
+ except ConnectionClosed:
+ closed.set()
+
+ url, server = _fake_xai_server(handler)
+ try:
+ streamer = ts.XAIStreamer({}, {"streaming_url": url})
+ if outcome == "error":
+ with pytest.raises(RuntimeError, match="example failure"):
+ list(streamer.stream("A sentence."))
+ else:
+ assert list(streamer.stream("A sentence.")) == [b"x" * 64]
+ assert closed.wait(timeout=10)
+ finally:
+ server.shutdown()
+
+
# ── 16 MiB per-sentence stream cap ───────────────────────────────────────
diff --git a/tools/tts_streaming.py b/tools/tts_streaming.py
index 33f1fb1acce..c1362b25ad1 100644
--- a/tools/tts_streaming.py
+++ b/tools/tts_streaming.py
@@ -335,14 +335,24 @@ class GeminiStreamer(StreamingTTSProvider):
@register("xai")
class XAIStreamer(StreamingTTSProvider):
- """xAI WebSocket TTS (``wss://api.x.ai/v1/tts``) → binary PCM frames (24 kHz mono int16).
- Credentials route through ``resolve_xai_http_credentials`` (OAuth or XAI_API_KEY), same as the
- sync path. ``_collect_async`` bridges the async WS loop to the sync iterator contract (test
- seam).
-
- Salvaged from PR #47588 (@Cdddo): xAI's chunked TTS API is WebSocket-only (``wss://api.x.ai/v1/tts``).
+ """xAI WebSocket TTS → base64 PCM ``audio.delta`` frames (24 kHz mono int16).
+
+ Salvaged from PR #47588 (@Cdddo) and rewritten against the real wire
+ protocol: voice/language/codec/sample_rate ride in the URL query string
+ (the server 400s the bare path at handshake), the client sends
+ ``text.delta`` + ``text.done``, and the server streams JSON
+ ``audio.delta`` envelopes (base64 PCM in ``delta``) until ``audio.done``.
+ Credentials route through ``resolve_xai_http_credentials`` (XAI_API_KEY
+ first, OAuth as fallback), same as the sync ``_generate_xai_tts`` path. The async WS
+ loop runs on a background thread feeding a queue, so ``stream()`` yields
+ chunks as they arrive and works from sync CLI code and from gateway
+ adapters that already run an event loop.
"""
+ sample_rate = 24000
+
+ _RECV_TIMEOUT_S = 60 # a sentence of TTS should never gap this long
+
@staticmethod
def available() -> bool:
try:
@@ -354,47 +364,136 @@ class XAIStreamer(StreamingTTSProvider):
return False
def stream(self, text: str) -> Iterator[bytes]:
- yield from _capped(iter(self._collect_async(text)), "xAI streaming TTS")
+ yield from _capped(self._queued_frames(text), "xAI streaming TTS")
+
+ # -- async→sync bridge -------------------------------------------------
+
+ def _queued_frames(self, text: str) -> Iterator[bytes]:
+ """Yield PCM chunks as the WS delivers them, on a pump thread.
- def _collect_async(self, text: str) -> List[bytes]:
+ The thread owns a fresh event loop, so ``asyncio.run`` never fights
+ a loop the caller is already running (gateway adapters are async).
+ Exceptions from the pump are re-raised on the consumer side so the
+ caller's "raise on failure" contract holds.
+
+ ``_capped()`` runs on the consumer side of the queue, after
+ ``q.get()`` — so the byte budget is ALSO enforced in the pump before
+ each enqueue (see ``_pump``), and a consumer that stops early flips
+ ``stop`` so the pump closes the socket instead of piling decoded PCM
+ into a queue nobody drains.
+ """
import asyncio
+ import queue
+ import threading
+ from contextvars import copy_context
- async def _drain() -> List[bytes]:
- return [frame async for frame in self._async_frames(text)]
- return asyncio.run(_drain())
+ q: "queue.Queue[object]" = queue.Queue()
+ done = object()
+ stop = threading.Event()
- async def _async_frames(self, text: str):
+ def _pump_thread() -> None:
+ try:
+ asyncio.run(self._pump(text, q, stop))
+ except BaseException as exc: # hand failures to the consumer
+ q.put(exc)
+ finally:
+ q.put(done)
+
+ threading.Thread(
+ target=copy_context().run, args=(_pump_thread,), name="xai-tts-pump", daemon=True
+ ).start()
+ try:
+ while True:
+ item = q.get()
+ if item is done:
+ return
+ if isinstance(item, BaseException):
+ raise item
+ yield item
+ finally:
+ # Generator closed early (cap, playback failure, caller dropped
+ # it): stop the pump at its next frame.
+ stop.set()
+
+ async def _pump(self, text: str, q, stop) -> None:
+ import asyncio
+ import base64
import json as _json
+ from urllib.parse import urlencode
+
import websockets
- from tools.tts_tool_providers import DEFAULT_XAI_VOICE_ID
+
+ from tools.tts_tool_providers import DEFAULT_XAI_LANGUAGE, DEFAULT_XAI_VOICE_ID
from tools.xai_http import resolve_xai_http_credentials
api_key = str(resolve_xai_http_credentials(prefer_api_key=True).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
- ws_url = str(self.section.get("streaming_url") or "wss://api.x.ai/v1/tts").strip()
- async with websockets.connect(ws_url, extra_headers={"Authorization": f"Bearer {api_key}"}) as ws:
- await ws.send(_json.dumps({"text": text, "voice_id": voice, "response_format": "pcm"}))
- try:
- while True:
- message = await ws.recv()
- if isinstance(message, (bytes, bytearray, memoryview)):
- yield bytes(message)
- continue
- try:
- envelope = _json.loads(message)
- except (ValueError, TypeError):
- if message == "done":
+ language = str(self.section.get("language", DEFAULT_XAI_LANGUAGE)).strip() or DEFAULT_XAI_LANGUAGE
+ base = str(
+ self.section.get("streaming_url") or "wss://api.x.ai/v1/tts"
+ ).strip()
+ params = urlencode({
+ "voice": voice,
+ "language": language,
+ "codec": "pcm",
+ "sample_rate": self.sample_rate,
+ })
+ sep = "&" if "?" in base else "?"
+ ws_url = f"{base}{sep}{params}"
+
+ async with websockets.connect(
+ ws_url, additional_headers={"Authorization": f"Bearer {api_key}"}
+ ) as ws:
+ await ws.send(_json.dumps({"type": "text.delta", "delta": text}))
+ await ws.send(_json.dumps({"type": "text.done"}))
+ enqueued = 0
+ while True:
+ try:
+ message = await asyncio.wait_for(
+ ws.recv(), timeout=self._RECV_TIMEOUT_S
+ )
+ except asyncio.TimeoutError:
+ raise RuntimeError("xAI streaming TTS: no audio for 60s")
+ except websockets.exceptions.ConnectionClosedOK:
+ return # clean close, with or without audio.done
+ except websockets.exceptions.ConnectionClosedError as exc:
+ raise RuntimeError(f"xAI WS closed mid-stream: {exc}") from exc
+ if isinstance(message, (bytes, bytearray, memoryview)):
+ continue # the server speaks JSON; binary is not expected
+ try:
+ envelope = _json.loads(message)
+ except (ValueError, TypeError):
+ continue
+ msg_type = envelope.get("type")
+ if msg_type == "audio.delta":
+ b64 = envelope.get("delta") or ""
+ if b64:
+ pcm = base64.b64decode(b64)
+ enqueued += len(pcm)
+ if enqueued > _STREAM_SENTENCE_BYTE_CAP:
+ # Enforce the per-sentence byte budget BEFORE
+ # enqueueing: the consumer-side _capped() only
+ # runs after q.get(), so without this a runaway
+ # upstream piles decoded PCM into the queue.
+ # Returning exits the context manager, which
+ # closes the socket — we stop reading upstream.
+ logger.warning(
+ "xAI streaming TTS exceeded %d bytes for one "
+ "sentence; closing upstream",
+ _STREAM_SENTENCE_BYTE_CAP,
+ )
return
- continue
- etype = envelope.get("type")
- if etype == "error":
- logger.warning(
- "xAI WS error envelope: %s", envelope.get("error") or envelope.get("message") or envelope,
- )
- if etype in ("done", "error"):
- return
- except Exception as exc:
- if exc.__class__.__name__ != "ConnectionClosed":
- logger.warning("xAI WS receive failed: %s", exc)
- return
+ if stop.is_set():
+ # Consumer went away (cap, playback failure):
+ # close and stop reading rather than filling a
+ # queue nobody drains.
+ return
+ q.put(pcm)
+ elif msg_type == "audio.done":
+ return
+ elif msg_type == "error":
+ detail = (
+ envelope.get("message") or envelope.get("error") or envelope
+ )
+ raise RuntimeError(f"xAI streaming TTS error: {detail}")