there is always a 3-4 seconds delay between llm re...
# ask-ai
c
there is always a 3-4 seconds delay between llm returned the response and it's passed onto TTS. I've tried adding more logs in the StreamPacer's
_send_task
method to see if there is any lag here, but the logs here are also seeing a lag of almost 3 seconds. why is this happening? where do you think the 3 seconds are being consumed?
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.
Thanks — you're asking why there's a consistent ~3–4s gap between the LLM finishing and the StreamPacer
_send_task
seeing chunks. I’m responding about where that time is most likely spent and what to check next. Quick summary of likely causes • The LLM stream finalization is delayed: the model may buffer/send a final chunk only after finishing, so you see the “LLM returned” event but chunks arrive later. • Upstream post-LLM processing buffers or aggregates chunks before yielding (e.g., a custom
llm_node
that waits for full output). • Agent-level turn/decision logic waits briefly after LLM completion to detect tool calls or other actions before forwarding. • Less likely given your logs, but backpressure from TTS or downstream systems can produce stalls that appear earlier in timing. Concrete, minimal diagnostic steps to pinpoint the 3–4s 1. Add logging at the LLM stream consumer boundary: ◦ Log timestamps for each token/chunk as soon as they arrive from
llm.chat()
(or equivalent stream callback). ◦ Log the timestamp when you yield/pass that chunk into the pipeline (into the pacer). ◦ Compare those timestamps to confirm whether the delay is before the pacer. 1. Instrument Agent boundaries: ◦ Log when
llm_node
starts and finishes, and when the next pipeline node receives the first chunk. ◦ If you have custom nodes, instrument their input and output timings to find buffering points. 1. Inspect final-chunk behavior: ◦ Check whether the stream sends a final “end” chunk only after completion. If so, force incremental yields (yield partial chunks as they arrive). 1. Check metrics: ◦ Review LLMMetrics like
ttft
and overall
duration
. If
duration
includes the 3s gap, it’s LLM/streaming-related; if not, it’s post-LLM processing. 1. Quick test to isolate: ◦ Replace your real LLM with a simple incremental test stream that emits tokens immediately. If delay disappears, the LLM stream is the source. If you’d like, tell me: • Which LLM/provider you’re using and whether you see token-level streaming in your logs. • Whether you have a custom
llm_node
or any intermediate nodes between
llm_node
and
StreamPacer
. I can then suggest exact log points or code snippets to add. Would you like that? Sources: Observability data hooks | LiveKit docs
c
I have a custom llm_node but there isn't any custom logic before the chunks go to StreamPacer. Also, to log the time when TTS has started receiving the yielded chunks, where should I be adding the logs? I'm using cartesia provider
t
Thanks — since your custom
llm_node
doesn't buffer, add logs in the
tts_node
where it consumes the text stream. That will show exactly when TTS starts receiving chunks from the pipeline (and help confirm whether the 3–4s gap is upstream or in the TTS provider). Add one of these minimal options: 1) Simple first-chunk log inside `tts_node`:
Copy code
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
    first = True
    async for chunk in text:
        if first:
            logger.info("TTS received first chunk", extra={"ts": time.time()})
            first = False
        yield chunk
2) Wrapped stream passed to the default node (captures iteration start before default handling):
Copy code
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
    async def logged_stream():
        first = True
        async for chunk in text:
            if first:
                logger.info("TTS stream started", extra={"ts": time.time()})
                first = False
            yield chunk
    return await Agent.default.tts_node(self, logged_stream(), model_settings)
Also add token/chunk timestamps at your
llm.chat()
consumer (the moment tokens are received) so you can compare: • token arrival time (LLM) • time you yield into pipeline (pre-pacer) • first TTS receive time (tts_node) If you share the three timestamps for a sample utterance, I can help identify where the 3–4s is spent. Sources: Pipeline nodes and hooks | LiveKit docs
c
I added logs in the
tts_node
method and I see that chunks are being sent here immediately as received from the llm node. However, the streampacer logs where I log the batches is after 3 seconds.
t
Thanks — since your
tts_node
shows immediate receipt but
StreamPacer
logs batches after ~3s, the delay is happening between when your tts node hands text to the Cartesia client and when audio frames arrive at StreamPacer. Two short, actionable steps to pin it down and reduce it: 1) Add a log at the TTS client handoff (immediately before calling Cartesia) and a log at the first audio frame yield (just before yielding
rtc.AudioFrame
) so you can compare:
Copy code
# before calling Cartesia
logger.info("Handing text to Cartesia", extra={"ts": time.time()})

# inside audio-generation loop, before yielding frames
logger.info("Yielding first audio frame", extra={"ts": time.time()})
2) Inspect/adjust Cartesia/StreamPacer settings: • Check Cartesia TTS streaming options for low-latency mode or smaller internal buffers (enable incremental streaming if available). • Check StreamPacer config (batch size / max_batch_duration / pace interval) and reduce time-based thresholds so it forwards smaller batches sooner. If you share the three timestamps (text-to-Cartesia handoff, first audio-frame yield, and StreamPacer batch log) for one sample run, I’ll point to exactly which component is adding the ~3s and suggest the concrete config change or code patch. Sources: Agent speech and audio | LiveKit docs | Observability data hooks | LiveKit docs | Live Conversations with AI using ChatGPT and WebRTC | Text-to-speech (TTS) models | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs
c
If there is delay before the chunks are received in streampacer itself, how does adding logs before cartesia calls are happening? all the streampacer logic runs before chunks are sent to cartesia right?
t
You're right to question the order — to be clear: StreamPacer runs after audio is returned from the TTS provider, not before the Cartesia call. So logging before you call Cartesia is useful because it marks the moment you hand text off to the TTS service; comparing that timestamp to when StreamPacer first receives audio isolates whether the delay is in the TTS/network/synthesis or later in pacing. What to log (minimal): • Timestamp just before calling Cartesia (handoff). • Timestamp when you receive the first
rtc.AudioFrame
from Cartesia (inside your
tts_node
, before yielding). • Timestamp from your existing StreamPacer first-batch log. Small example:
Copy code
logger.info("handing to Cartesia", extra={"ts": time.time()})
# call Cartesia / default tts_node...
logger.info("first audio frame received", extra={"ts": time.time()})
# StreamPacer already logs its batch ts
How to interpret: • If handoff → first-audio ≈ 3s => Cartesia (synthesis or network) is adding the latency. • If first-audio → StreamPacer batch ≈ 3s => StreamPacer batching/pacing is introducing the delay (check its batch duration/size). • If handoff → first-audio small and first-audio → StreamPacer small, but you still observe 3s elsewhere, share the three timestamps and I’ll help pinpoint it. If you want, paste one sample set of those timestamps and I’ll analyze which component adds the ~3s and suggest the concrete config/code change. Sources: Text-to-speech (TTS) models | LiveKit Docs | ElevenLabs TTS plugin guide | LiveKit Docs | Models | LiveKit Docs | Observability data hooks | LiveKit docs
c
I put the logs like you said: but what I observed is that streampacer's log is before request going to tts. And both are nearly at the same time: not even 0.1 second. So there is some lag between the llm returned chunks are sent to batching in streampacer.
t
Thanks — good detective work. You’ve confirmed that: • LLM chunks reach your
tts_node
immediately, • StreamPacer logs occur almost simultaneously with the TTS handoff, • Yet StreamPacer’s batching shows a ~3s gap before it actually processes/sends the batch. That means the delay is happening between when LLM chunks are produced and when they are enqueued into StreamPacer’s batching window (i.e., upstream of StreamPacer’s batch send). Likely causes and next steps: 1) Where the buffering can occur (quick checklist) • The code that converts LLM text chunks into the stream items StreamPacer consumes may be buffering or coalescing. Search for a buffer/queue, debounce, or time-window logic where text → audio-synthesis inputs are collected. • Any async handoff (putting chunks onto an asyncio.Queue or awaiting a consumer) can introduce batching if a consumer waits for more items or sleeps between pulls. • StreamPacer config may expect audio frames and not text; if you’re converting text→audio frames in a middle layer, that conversion could be delayed by time-based batching. 2) Immediate diagnostics to pinpoint the enqueue delay • Add a log the instant you create/enqueue the item that StreamPacer will batch (not just when StreamPacer logs batches). Example points: ◦ Right when you wrap/yield a text chunk into the stream object that ultimately feeds StreamPacer. ◦ Right when you push into any internal queue:
queue.put_nowait(...)
timestamp. • Log the timestamp when StreamPacer reads from that queue (consumer-side read). If you see the item enqueued timestamp much earlier than the consumer read, the gap is in the queue/wrapper. 3) Code/config items to inspect or change • If you use an intermediate queue: ensure producers use
put_nowait
and consumers do not do
await asyncio.sleep(...)
or wait for N items before processing. • If there’s a debounce/timer in your wrapper, reduce the timer (e.g., from 3s to 200–500ms). • If StreamPacer expects
AudioFrame
objects but you buffer until you have enough text to synthesize, switch to incremental synthesis: send partial text chunks to TTS immediately so audio frames arrive sooner. 4) Quick experiment to isolate: • Replace your enqueue path with a direct passthrough that yields each LLM chunk immediately into the StreamPacer input (or a mock stream that forwards instantly). If the 3s gap disappears, the buffering lives in your enqueue/wrapper logic. 5) Helpful data to share if you want me to pinpoint further • A short snippet of the code that hands LLM chunks into the stream/queue that StreamPacer reads. • Any StreamPacer-related config values (batch size, max_batch_duration, pace interval) and whether you altered defaults. • The three timestamps for a sample request: LLM chunk arrival, enqueue timestamp (your new log), and StreamPacer read/send timestamp. If you share the enqueue/queue code or those timestamps, I’ll point to the exact line or config to change to remove the ~3s.