Streamovacie potrubie od LLM k TTS
Na tejto strane
Aktualizované 3. novembra 2026 na základe stránky xAI Text to Speech: každý
text.deltamôže obsahovať až 60 000 znakov. Zdroj: Text to Speech.
Pripojenie LLM k syntéze reči v reálnom čase
Najvýkonnejším využitím TTS WebSocket je jeho prepojenie so streamujúcim LLM. LLM generuje text token po tokene, každý token putuje cez WebSocket do TTS a zvuk sa prehráva hneď, ako dorazí. Používateľ počuje odpoveď ešte počas toho, čo LLM stále „premýšľa“.
Architektúra potrubia
Dáta prechádzajú tromi fázami:
User -> LLM (streaming) -> TTS WebSocket -> Audio (playback)
question text tokens audio.delta speaker
Každá fáza streamuje, čo minimalizuje vnímanú latenciu. Používateľ nemusí čakať, kým LLM dokončí generovanie celej odpovede, aby ju začul počuť.
Implementácia v Pythone
Tu je kompletné potrubie, ktoré spája API Grok Chat Completions s TTS WebSocket:
import asyncio
import websockets
import json
import base64
import aiohttp
async def llm_to_speech(api_key, prompt, voice="rex", language="en"):
# Step 1: TTS WebSocket connection
tts_uri = f"wss://api.x.ai/v1/tts?language={language}&voice={voice}"
tts_headers = {"Authorization": f"Bearer {api_key}"}
audio_chunks = []
async with websockets.connect(tts_uri, additional_headers=tts_headers) as tts_ws:
# Step 2: Streaming LLM call
async with aiohttp.ClientSession() as session:
async with session.post(
"https://api.x.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
json={
"model": "grok-4.5",
"messages": [{"role": "user", "content": prompt}],
"stream": True
}
) as llm_response:
# Step 3: Each LLM token -> TTS delta
buffer = ""
async for line in llm_response.content:
line = line.decode().strip()
if not line.startswith("data: "):
continue
if line == "data: [DONE]":
break
chunk = json.loads(line[6:])
token = chunk["choices"][0].get("delta", {}).get("content", "")
if token:
buffer += token
# Send complete sentences
if any(c in token for c in ".!?\n"):
await tts_ws.send(json.dumps({
"type": "text.delta",
"delta": buffer
}))
buffer = ""
# Send whatever is left in the buffer
if buffer:
await tts_ws.send(json.dumps({
"type": "text.delta",
"delta": buffer
}))
await tts_ws.send(json.dumps({"type": "text.done"}))
# Step 4: Collect the audio
async for msg in tts_ws:
data = json.loads(msg)
if data["type"] == "audio.delta":
audio_chunks.append(base64.b64decode(data["delta"]))
elif data["type"] == "audio.done":
break
return b"".join(audio_chunks)
Stratégia vyrovnávacej pamäte (Buffering)
Odosielať každý token do TTS jednotlivo nie je ideálne: syntetický engine dosahuje lepšie výsledky, keď má k dispozícii kontext. Existujú tri stratégie bufferovania.
Podľa vety
Počkaj na oddeľovač vety (., !, ?, nový riadok) pred odoslaním:
if any(c in token for c in ".!?\n"):
await tts_ws.send(json.dumps({
"type": "text.delta", "delta": buffer
}))
buffer = ""
Toto je najlepšia rovnováha medzi kvalitou a latenciou.
Podľa veľkosti
Odošli, keď buffer dosiahne určitú veľkosť (napríklad 200 znakov):
if len(buffer) >= 200:
await tts_ws.send(json.dumps({
"type": "text.delta", "delta": buffer
}))
buffer = ""
Je to jednoduchšie, ale môže to rozdeliť slovo v polovici.
Podľa časového limitu
Odošli po oneskorení bez nového tokenu (užitočné, keď LLM „premýšľa“):
last_token_time = time.time()
# If more than 500 ms pass without a token, send the buffer
if time.time() - last_token_time > 0.5 and buffer:
await tts_ws.send(...)
buffer = ""
Prehrávanie zvuku v reálnom čase
Ak chceš prehrávať zvuk hneď, ako prichádza (nielen ho zbierať), použi asynchrónny rad (queue):
import asyncio
audio_queue = asyncio.Queue()
async def receive_audio(tts_ws):
"""Receives audio chunks and puts them in the queue."""
async for msg in tts_ws:
data = json.loads(msg)
if data["type"] == "audio.delta":
audio_bytes = base64.b64decode(data["delta"])
await audio_queue.put(audio_bytes)
elif data["type"] == "audio.done":
await audio_queue.put(None) # End sentinel
break
async def play_audio():
"""Plays audio chunks from the queue."""
while True:
chunk = await audio_queue.get()
if chunk is None:
break
# Play the chunk (pyaudio, sounddevice, etc.)
play_chunk(chunk)
Súbežným spustením receive_audio a play_audio sa prehrávanie začne hneď s prvým prijatým chunkom.
Ošetrenie chýb v potrubí
Potrubie môže zlyhať na troch miestach: LLM, TTS alebo sieť. Každú situáciu ošetri:
async def robust_pipeline(api_key, prompt):
try:
audio = await llm_to_speech(api_key, prompt)
return audio
except aiohttp.ClientError:
print("LLM error: check your connection")
except websockets.ConnectionClosed:
print("TTS connection lost: reconnection needed")
except json.JSONDecodeError:
print("Invalid response: unexpected format")
except Exception as e:
print(f"Unexpected error: {e}")
return None
Kľúčové poznatky
- Streamujúci LLM napájajúci TTS WebSocket poskytuje najnižšiu latenciu
- Bufferuj po vetách pre najlepšiu rovnováhu medzi kvalitou a latenciou
- Na prehrávanie zvuku v reálnom čase použi asynchrónny rad
- Ošetruj chyby v každej fáze potrubia
- Celkový text cez WebSocket je neobmedzený (deltá až do 60 000 znakov)
- Limit 50 súbežných relácií platí pre celý tvoj tím