there is always a 5 seconds delay between my livek...
# ask-ai
c
there is always a 5 seconds delay between my livekit python sdk server receives the first chunk and it sends the request to tts. I assume it's because of the buffer which is waiting for some significant time before sending the text to TTS. is there a way to override this delay/buffer so that as soon as one sentence completes, TTS step start and the user can hear the audio?
t
Thanks for reaching out, Bharath. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're right to suspect the delay comes from endpointing (turn-end) detection rather than audio buffering. That wait is controlled by VAD/turn settings. To start TTS as soon as a sentence completes, try one or more of the following: • Reduce endpointing delays in your `AgentSession`:
Copy code
session = AgentSession(
    # ...other config
    min_endpointing_delay=0.1,
    max_endpointing_delay=0.5,
)
Lower values make the agent respond faster (at the risk of cutting off faint trailing speech). • Enable
preemptive_generation=True
so LLM/TTS can start generating before turn end is fully confirmed (reduces perceived latency but may waste compute if interrupted). • Use the Turn Detector plugin (transformer-based) instead of conservative VAD rules to more accurately detect semantic turn ends:
Copy code
from livekit.plugins.turn_detector.multilingual import MultilingualModel

session = AgentSession(
    turn_detection=MultilingualModel(),
    min_endpointing_delay=0.1,
    # ...
)
• Tweak VAD parameters (e.g., lower
min_silence_duration
in Silero VAD) if you rely on VAD for silence detection. Which approach would you like to try first, and can you share the relevant parts of your current
AgentSession
config (VAD, endpointing values, and whether
preemptive_generation
is enabled)? I’ll give precise code adjustments based on that. Sources: Agents (Python) | livekit/livekit_composite | DeepWiki | Agent session | LiveKit docs | Agents Framework | livekit/livekit_composite | DeepWiki | LiveKit turn detector plugin | LiveKit docs | Agent speech and audio | LiveKit docs
c
I see that my case is more of a TTS buffer problem. I would want the text that LLM has given to be sent to TTS as soon as a sentence is complete instead of waiting longer times
t
Thanks — understood: you want LLM-generated sentences sent to TTS immediately when a sentence completes. I can help tune that. A few quick options that accomplish this; tell me which fits your setup or share your `AgentSession`/TTS config and I’ll give exact changes. • Send sentences to TTS as they’re produced: ◦ If your LLM outputs sentence-level chunks, stream each completed sentence directly to TTS immediately (flush buffer on sentence-end). ◦ If your LLM streams tokens, implement sentence-boundary detection (e.g., look for punctuation + whitespace or an explicit sentence-complete event) and push that text chunk to TTS as soon as detected. • Reduce turn/endpoint waiting so TTS can start earlier: ◦ Set
min_endpointing_delay
and
max_endpointing_delay
to low sub-second values (e.g., 0.1 / 0.5s) so the pipeline stops waiting for extra silence before sending text to TTS. • Use preemptive generation to overlap processing: ◦ Enable
preemptive_generation=True
so LLM/TTS start producing before final turn confirmation (reduces perceived latency; may increase wasted work if interrupted). • Stream TTS output instead of waiting for full audio: ◦ Configure your TTS integration to accept incremental text and stream audio back as it’s generated so the user hears audio earlier. Questions so I can give precise code/config: 1. Which LLM and streaming mode are you using (sentence-chunked, token-streaming, or non-streaming)? 2. Which TTS service/library are you calling and does it support incremental text-to-speech streaming? 3. Share the relevant parts of your
AgentSession
(VAD/endpointing values,
preemptive_generation
), or paste the TTS-call code path where text is buffered. Tell me those and I’ll provide exact code snippets and config edits to send each completed sentence to TTS immediately.
c
my llm is doing token-streaming. TTS library is Cartesia. I don't want to change anything on VAD/endpointing for now
t
Good — since you’re receiving token-streams and won’t change VAD, here’s a focused plan to send completed sentences to Cartesia TTS immediately, plus a minimal example and a question for your code. What to do (high level) • Buffer incoming tokens from the LLM until you detect a sentence boundary. • On sentence boundary: flush that sentence string to Cartesia’s TTS call (use Cartesia’s incremental/streaming TTS endpoint if available). Start TTS immediately while continuing to collect tokens for the next sentence. • Keep a small lookback buffer to handle punctuation followed by short tokens (e.g., “Mr.”). Use heuristics to avoid premature flushes. • Optionally set your LiveKit TTS buffer to minimal (e.g.,
tts_buffer_seconds=0
) if your integration exposes it. Sentence-boundary detection (recommended heuristics) • Primary rule: flush when you see a token that ends with sentence punctuation followed by whitespace or newline (., ?, !). • Secondary checks to avoid false positives: ◦ If token ends with common abbreviations (e.g., “Mr.”, “Dr.”, “e.g.”), do not flush. ◦ If next token starts with lowercase and the punctuation was a period, consider waiting briefly for more tokens (or require punctuation + whitespace + capitalized next token). ◦ If you want more aggressive behavior, flush immediately on punctuation regardless of next token. Minimal Python pseudocode (token-stream consumer -> Cartesia)
Copy code
abbreviations = {"mr.", "mrs.", "dr.", "e.g.", "i.e.", "etc."}
buffer = ""
def is_sentence_end(token, next_token):
    t = token.strip()
    if not t: return False
    if any(t.lower().endswith(a) for a in abbreviations): return False
    if t[-1] in ".?!" :
        if t[-1] == "." and next_token and next_token[0].islower():
            return False
        return True
    return False

# token_stream yields (token, maybe_next_token)
for token, peek in token_stream():
    buffer += token
    if is_sentence_end(token, peek):
        sentence = buffer.strip()
        buffer = ""
        # send sentence to Cartesia immediately (use streaming if available)
        cartesia.speak(sentence)  # replace with your async/stream call
Integration tips with Cartesia • If Cartesia supports incremental/streaming TTS, call that endpoint so audio begins before full utterance audio is generated. • If only batch TTS is available, send each sentence as its own TTS request so audio plays as soon as that sentence audio is ready. • Make the TTS call async so it doesn’t block consuming more tokens; play audio as chunks arrive. Edge cases and tuning • Short fragments: consider a minimum length (e.g., >= 3–4 characters) before sending. • Long sentences: you can optionally force-flush after a max token/char count to avoid long waits. • Latency vs correctness: more aggressive flushing reduces latency but risks splitting sentences incorrectly; tune abbreviation list and capitalization checks. One quick question so I can give exact code: do you call Cartesia synchronously (blocking) or does your integration already support async/streaming audio callbacks? Share the Cartesia call snippet and I’ll adapt the example into an async streaming implementation you can drop into your pipeline.
c
My integration already has streaming audio and I have not modified anything on cartesia as such
t
Great — since you have token-streaming LLM output and Cartesia streaming TTS, here’s a concise, practical implementation to detect sentence boundaries in the token stream and push each completed sentence to Cartesia immediately (async, non-blocking). Key steps • Buffer tokens as they arrive. • Detect sentence end via punctuation + simple heuristics (avoid common abbreviations, optional capitalization check). • On boundary: asynchronously push the sentence to Cartesia’s streaming TTS and continue consuming tokens. • Keep a small leftover buffer for partial sentences. Async Python example (drop into your token consumer)
Copy code
import asyncio

ABBREVS = {"mr.", "mrs.", "dr.", "e.g.", "i.e.", "etc."}
MIN_SENT_LEN = 3  # avoid flushing tiny fragments

async def is_sentence_end(token, peek):
    t = token.strip()
    if not t or len(t) < MIN_SENT_LEN:
        return False
    low = t.lower()
    if any(low.endswith(a) for a in ABBREVS):
        return False
    if t[-1] in ".?!\n":
        if t[-1] == "." and peek and peek[0].islower():
            return False
        return True
    return False

async def stream_tokens_to_cartesia(token_stream, cartesia_tts):
    buffer = ""
    pending_tasks = set()

    async for token, peek in token_stream:  # token_stream yields (token, next_token_peekable)
        buffer += token
        if await is_sentence_end(token, peek):
            sentence = buffer.strip()
            buffer = ""

            # async push to Cartesia TTS (non-blocking)
            task = asyncio.create_task(cartesia_tts.push_and_play(sentence))
            pending_tasks.add(task)
            task.add_done_callback(pending_tasks.discard)

    # flush remainder
    if buffer.strip():
        task = asyncio.create_task(cartesia_tts.push_and_play(buffer.strip()))
        pending_tasks.add(task)

    if pending_tasks:
        await asyncio.wait(pending_tasks)
Minimal Cartesia adapter pattern (example)
Copy code
class CartesiaTTSAdapter:
    def __init__(self, tts_stream):
        self.stream = tts_stream  # your Cartesia streaming client

    async def push_and_play(self, text):
        # non-blocking: push text and let the stream produce audio while returning
        self.stream.push_text(text)
        self.stream.flush()           # if your client needs explicit flush
        # optionally await small handshake/ack if required, otherwise return
Tuning suggestions • Expand
ABBREVS
for domain-specific abbreviations. • Use a capitalization check (require next token to be capitalized) if you see false positives. • Set a max sentence length to force-flush very long outputs. • Keep TTS calls async so token consumption remains uninterrupted. If you share your Cartesia call snippet (how you currently push text/flush/play), I’ll adapt the adapter and token consumer exactly to your API. Sources: Agent speech and audio | LiveKit docs | examples/frontdesk | livekit/livekit_composite | DeepWiki
c
where do I integrate this in my livekit sdk?
t
You should integrate the sentence-buffer + flush-to-Cartesia logic into the part of your LiveKit pipeline that receives the LLM token stream — i.e., the LLM output handler inside your AgentSession (or the token callback you already consume). Concretely, put the logic in the async token consumer that you pass to AgentSession (or override the session’s token/event handler). That ensures sentences are detected and pushed to Cartesia immediately while LiveKit keeps running. Where to add it • If you use AgentSession with an LLM instance that yields tokens: add the buffer & sentence-detection inside the async loop that consumes that token stream (the same coroutine that currently builds the LLM response). • If you handle LLM tokens via a callback/event (e.g., on_token, on_update): perform buffering and flush inside that callback. • Ensure the Cartesia TTS call is async/non-blocking so token consumption continues while audio is generated. Minimal integration example with AgentSession token consumer 1) Create a Cartesia adapter with async push/flush (non-blocking). 2) In your AgentSession token handler, buffer tokens, detect sentence boundaries, and call the adapter to stream each completed sentence. Example (integration sketch — drop into your LiveKit AgentSession token handler):
Copy code
# cartesia adapter you create once
class CartesiaTTSAdapter:
    def __init__(self, tts_stream):
        self.stream = tts_stream

    async def push_and_play(self, text):
        self.stream.push_text(text)
        self.stream.flush()   # if client requires
        # return immediately; stream produces audio concurrently

# token consumer registered with your LLM/AgentSession
async def handle_llm_tokens(token_stream, cartesia_adapter):
    buffer = ""
    async for token, peek in token_stream:  # how you get tokens from your LLM
        buffer += token
        if is_sentence_end(token, peek):     # use the heuristics we discussed
            sentence = buffer.strip()
            buffer = ""
            # fire-and-forget TTS push so token loop isn't blocked
            asyncio.create_task(cartesia_adapter.push_and_play(sentence))

    # flush any remainder
    if buffer.strip():
        asyncio.create_task(cartesia_adapter.push_and_play(buffer.strip()))
How this connects to LiveKit • If you pass an LLM instance into AgentSession, intercept its token stream (the LLM client usually exposes an async generator or token callback). Use that generator/callback for
handle_llm_tokens
. • If AgentSession exposes a token event or
on_llm_token
hook, register this handler there. • Make sure the Cartesia audio output is published to the LiveKit room (rtc AudioSource) as your existing flow does; streaming TTS will then play immediately in the room. Next step I can do for you • If you paste the snippet where your code currently consumes LLM tokens (or show how you instantiate AgentSession / on_token handler), I’ll adapt the exact code to your setup and provide the precise lines to insert.