when my custom LLM is streaming text, when and how...
# ask-ai
c
when my custom LLM is streaming text, when and how does livekit consider end of a significant amount of chunk to pass it to TTS?
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 asking when and how LiveKit treats a streamed LLM text chunk as "finished" and ready to send to TTS. Here's how it works and what you can change. • LiveKit uses sentence-based chunking: it accumulates streamed text and looks for sentence boundaries (periods, question marks, exclamation marks) to mark a significant chunk as complete and pass that sentence to TTS. This produces more natural, non-choppy speech. • If your TTS doesn't stream natively, LiveKit still uses the sentence tokenizer to split text for incremental synthesis so it can send completed sentences one-by-one. • You can customize this behavior by overriding the
tts_node
in your agent and implementing your own chunking logic (for example, chunk by phrase length, punctuation, pauses, or custom markers). Example pattern:
Copy code
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings) -> AsyncIterable[rtc.AudioFrame]:
      # implement custom chunk detection here
      async for frame in Agent.default.tts_node(self, text, model_settings):
          yield frame
Would you like suggestions for a specific custom chunking rule (e.g., time-based pauses, token-count thresholds, or punctuation+pause hybrid)? Sources: Pipeline nodes and hooks | LiveKit docs | Live Conversations with AI using ChatGPT and WebRTC
c
Currently, my llm is streaming but mutliple sentences are being merged and sent to TTS. Strict sentence based chunking is not happening before text is sent to TTS
t
Thanks—I hear you: you expect strict sentence-based chunking, but multiple sentences are being merged and sent to TTS. To help diagnose and fix this, a few quick questions and targeted suggestions: Questions • Are you using LiveKit’s built-in agent
tts_node
or a custom
tts_node
override? • Is your LLM sending text as short incremental fragments (e.g., token-level) or as larger multiline strings? • Do you see punctuation in the streamed text as it arrives (periods, question marks, etc.) or are those added later/omitted? • Which TTS provider/plugin are you using (native streaming TTS vs a provider that requires full input)? Immediate checks and fixes you can try • Verify streamed tokens include sentence-ending punctuation as they arrive. If punctuation is delayed, LiveKit can’t detect sentence boundaries. • If you use a custom
tts_node
, ensure you’re not aggregating multiple sentences before yielding to TTS. Insert logging to show when punctuation-triggered yields occur. • If your LLM streams token-by-token, implement buffering that emits to TTS only when you detect a sentence boundary (e.g., regex for [.?!] followed by whitespace or end-of-stream). • If the TTS provider buffers internally, switch to incremental calls per detected sentence instead of sending a long combined string. If you want, share: • a short snippet of how your LLM stream is consumed and how/where you call
tts_node
, and • a sample of the raw streamed text fragments (sanitized) that are being merged. I can then give a specific code pattern to enforce strict sentence chunking (time-based fallbacks, punctuation detection, or token-count safeguards). Would you like that?
c
1. I'm using Livekit's built-in tts_node 2. My LLM is sending short incremental tokens 3. Yes, there are puntucations in the tokens. 4. I'm using cartesia TTS provider
t
Thanks — I understand you're using LiveKit's built-in
tts_node
, your LLM streams short tokens that include punctuation, and Cartesia TTS is receiving multiple sentences merged instead of one sentence at a time. Below are targeted, practical steps to enforce strict sentence-based chunking before sending text to Cartesia. 1) Quick diagnosis to confirm • Verify punctuation arrives in the same token as the sentence end (e.g.,
"word."
), not as a following separate token. If the punctuation is a separate token, simple boundary detection may miss it until later. • Confirm LiveKit’s stream is passing tokens through unchanged before TTS; add short logs that print each incoming token and timestamps to see accumulation behavior. 2) Enforce strict sentence chunking (recommended approach) • Buffer incoming tokens into a short accumulator string. • Run a sentence-boundary check on the accumulator after each token append. Use a regex that looks for sentence terminators followed by whitespace or end-of-stream, e.g.: ◦ Pattern concept:
[.!?]+(?=\s|$)
• When you detect one or more complete sentences at the start of the buffer, extract exactly those sentences and send each sentence separately to Cartesia TTS (do not send the remaining buffer). • Keep any trailing partial sentence in the buffer until more tokens arrive or the stream ends. • Implement a short fallback flush (e.g., 500–1000 ms) to handle cases where punctuation is delayed or missing: if no new tokens arrive within that window and buffer length > 0, treat the buffer as a chunk and send it. 3) Handling Cartesia specifics • If Cartesia accepts incremental per-sentence calls, call the TTS API per extracted sentence so audio streams back while you continue buffering the next sentence. • If Cartesia buffers and only returns audio for full inputs, still send one sentence per request to avoid merged-sentence outputs. 4) Example logic (pseudocode)
Copy code
buffer = ""
last_token_time = now()

async for token in llm_stream:
    buffer += token
    last_token_time = now()
    while has_complete_sentence(buffer):            # uses regex check
        sentence, buffer = pop_first_sentence(buffer)
        await send_sentence_to_cartesia_tts(sentence)

# on stream end or timeout:
if buffer.strip():
    await send_sentence_to_cartesia_tts(buffer.strip())
5) Tuning suggestions • Regex for boundary detection: use
[.!?]+(?=\s|$)
but expand for ellipses, abbreviations, or language-specific punctuation if needed. • Fallback timeout: 300–1000 ms depending on typical token pace. • Max sentence length guard: if a sentence grows beyond N characters/tokens without punctuation, you may force-split to avoid indefinite buffering. If you want, I can: • Provide an actual Python snippet that integrates into LiveKit’s built-in
tts_node
flow, or • Suggest exact timeout and max-length defaults based on your token rate if you share typical tokens/sec. Which would you prefer?
c
give me python snipet that integrates into livekit's built-in tts_node flow.
t
Below is a concise Python snippet that wraps LiveKit’s built-in
tts_node
to enforce strict sentence-based chunking (regex boundary + timeout fallback) and sends one sentence at a time to your TTS call function
send_to_cartesia_tts(sentence)
. Replace
send_to_cartesia_tts
with your Cartesia integration that returns/streams audio frames.
Copy code
import re
import asyncio
from datetime import datetime, timedelta
from typing import AsyncIterable

SENTENCE_RE = re.compile(r'([^\r\n.!?]*[.!?]+)(\s+|$)', re.MULTILINE)

# Example placeholder — replace with your Cartesia call that yields AudioFrame objects
async def send_to_cartesia_tts(sentence: str) -> AsyncIterable['rtc.AudioFrame']:
    # call Cartesia TTS API per sentence and stream or yield audio frames
    # e.g., await cartesia.synthesize(sentence) -> yield audio frames
    yield from []  # replace

class CustomAgent:
    # timeout in seconds to flush incomplete buffer when tokens stop arriving
    FLUSH_TIMEOUT = 0.5
    MAX_BUFFER_CHARS = 5000  # safety guard to force-split if no punctuation

    async def tts_node(self, text: AsyncIterable[str], model_settings) -> AsyncIterable['rtc.AudioFrame']:
        buffer = ""
        last_recv = datetime.utcnow()

        async def flush_buffer(force=False):
            nonlocal buffer
            # extract all full sentences at start of buffer
            while True:
                m = SENTENCE_RE.match(buffer)
                if not m:
                    break
                sentence = m.group(1).strip()
                buffer = buffer[m.end():]
                # send sentence to Cartesia and yield its audio frames
                async for frame in send_to_cartesia_tts(sentence):
                    yield frame

            # if forced flush and remaining buffer exists, send as final chunk
            if force and buffer.strip():
                sentence = buffer.strip()
                buffer = ""
                async for frame in send_to_cartesia_tts(sentence):
                    yield frame

        # main consumption loop
        async for token in text:
            buffer += token
            last_recv = datetime.utcnow()

            # emit any complete sentences found
            async for frame in flush_buffer():
                yield frame

            # safety: if buffer too large without punctuation, force-split at whitespace boundary
            if len(buffer) > self.MAX_BUFFER_CHARS:
                # naive split: send up to MAX_BUFFER_CHARS
                part, buffer = buffer[: self.MAX_BUFFER_CHARS], buffer[self.MAX_BUFFER_CHARS :]
                async for frame in send_to_cartesia_tts(part.strip()):
                    yield frame

            # allow event loop to schedule timeout checks
            await asyncio.sleep(0)

            # check timeout: if no new tokens within FLUSH_TIMEOUT, flush partial buffer
            if (datetime.utcnow() - last_recv) > timedelta(seconds=self.FLUSH_TIMEOUT):
                async for frame in flush_buffer(force=True):
                    yield frame
                last_recv = datetime.utcnow()

        # stream ended — flush remaining buffer
        async for frame in flush_buffer(force=True):
            yield frame
Notes: • SENTENCE_RE matches sentence endings using [.?!] (adjust for abbreviations or other punctuation as needed). • FLUSH_TIMEOUT controls how long to wait before forcing a partial buffer flush; tune between 0.3–1.0s. • Replace
send_to_cartesia_tts
with your Cartesia integration that yields audio frames compatible with LiveKit. • You can add logging around token arrival and sentence sends for debugging. Would you like this adapted to a specific Cartesia request/response shape (sync vs streaming) so I can show the exact integration?
c
I implemented this but is has some error.
Copy code
async def tts_node(
            self,
            text: AsyncIterable[str],
            model_settings: ModelSettings,
    ) -> AsyncIterable[rtc.AudioFrame]:
        # 1) punctuation-boundary sentence stream
        async def sentence_stream() -> AsyncGenerator[str, None]:
            stream = self.sent_tok.stream()  # SentenceStream[web:61][web:62]
            async for chunk in text:
                # push the raw tokens/words into the stream
                for sentence in stream.push_text(chunk):
                    # only returned when tokenizer sees a completed sentence
                    yield sentence
            # flush tail at the end
            for sentence in stream.end_input():
                yield sentence

        # 2) per-sentence Cartesia streaming
        async for sentence in sentence_stream():
            # Cartesia TTS is configured with text_pacing=False so it won't re-batch[web:43]
            tts_stream = self._cartesia_tts.stream()  # see plugin TTS.stream doc[web:43][web:47]
            tts_stream.push_text(sentence)
            tts_stream.end_input()

            async for synthesized in tts_stream:  # SynthesizedAudio[web:47]
                yield synthesized.frame
fix this
t
Thanks — I see the
tts_node
you wrote that pushes tokens into
sent_tok
, then calls Cartesia per sentence. To fix it I need the exact error message or behavior you're seeing (traceback, hanging, duplicated frames, or missing audio). Could you paste the error or describe what happens when you run it? While you share that, two likely issues and fixes based on the code: 1) Async generator types:
sentence_stream()
is declared to return
AsyncGenerator[str, None]
but typed as
-> AsyncGenerator[str, None]
vs your signature using
AsyncIterable[str]
elsewhere isn’t an actual runtime problem — just ensure imports:
from typing import AsyncGenerator, AsyncIterable
. 2) Blocking/pull semantics on the Cartesia stream: If
self._cartesia_tts.stream()
is an async iterable that only starts producing after
push_text()
+
end_input()
, you must await iteration correctly. Also ensure
tts_stream.push_text()
and
end_input()
are awaited if they are async. If
push_text
returns sentences (sync) vs coroutine, calling without
await
will fail. To help immediately, here is a corrected, safe variant that: • Uses consistent typing/imports • Awaits
push_text
/
end_input
if they are coroutines (handles both sync and async by checking
inspect.isawaitable
) • Ensures Cartesia stream is iterated asynchronously and yields
synthesized.frame
Copy code
import inspect
import asyncio
from typing import AsyncIterable, AsyncGenerator
from datetime import datetime, timedelta

async def maybe_await(fn_or_coro, *args, **kwargs):
    res = fn_or_coro(*args, **kwargs) if callable(fn_or_coro) else fn_or_coro
    if inspect.isawaitable(res):
        return await res
    return res

async def tts_node(
    self,
    text: AsyncIterable[str],
    model_settings: ModelSettings,
) -> AsyncIterable[rtc.AudioFrame]:
    # sentence_stream: pushes tokens into sentence tokenizer that yields completed sentences
    async def sentence_stream() -> AsyncGenerator[str, None]:
        stream = self.sent_tok.stream()
        async for chunk in text:
            for sentence in stream.push_text(chunk):
                yield sentence
        for sentence in stream.end_input():
            yield sentence

    # iterate sentences and send to Cartesia per sentence
    async for sentence in sentence_stream():
        # obtain tts_stream (async iterable) from plugin
        tts_stream = self._cartesia_tts.stream()

        # call push_text and end_input — handle sync or async implementations
        await maybe_await(tts_stream.push_text, sentence)
        await maybe_await(tts_stream.end_input)

        # iterate the resulting async iterable and yield audio frames
        async for synthesized in tts_stream:
            # synthesized likely has .frame — forward it
            yield synthesized.frame
Send the exact traceback or describe the runtime symptom (e.g., TypeError: object not awaitable, nothing yielded, or hangs) and I’ll tailor the fix (for example, adjusting to sync vs async push_text, or ensuring
self._cartesia_tts.stream()
returns an async iterator). Would you like that?
c
I see
Copy code
Expected type 'collections.Iterable', got 'None' instead
at the stream.end_input() and stream.push_text(chunk) methods
t
Thanks — the error means you were treating
push_text()
/
end_input()
as if they returned an iterable. They return None (and must be awaited), and the audio is produced by iterating the
tts_stream
async iterable. Below is a corrected, minimal snippet that fixes that and integrates with LiveKit’s built-in flow. It: • Buffers incoming token chunks into sentences (regex), • Awaits
push_text
/
end_input
, • Iterates
tts_stream
to yield
synthesized.frame
. Replace
self._cartesia_tts.stream()
and
send
handling as needed for your Cartesia plugin.
Copy code
import re
import asyncio
from typing import AsyncIterable
from datetime import datetime, timedelta

SENTENCE_SPLIT_RE = re.compile(r'(?<=[.!?])\s+')

async def tts_node(
    self,
    text: AsyncIterable[str],
    model_settings,
) -> AsyncIterable['rtc.AudioFrame']:
    buffer = ""
    last_recv = datetime.utcnow()
    FLUSH_TIMEOUT = 0.5
    MAX_BUFFER_CHARS = 5000

    async def flush_buffer_to_tts(tts_stream, force=False):
        nonlocal buffer
        # split into sentences; keep trailing partial sentence in buffer
        parts = SENTENCE_SPLIT_RE.split(buffer.strip()) if buffer.strip() else []
        if len(parts) > 1:
            for sent in parts[:-1]:
                if sent:
                    await tts_stream.push_text(sent)
            buffer = parts[-1]
        elif force and buffer.strip():
            await tts_stream.push_text(buffer.strip())
            buffer = ""

    # iterate incoming token stream, build sentences, send per-sentence to Cartesia
    async for token in text:
        if token is None:
            continue
        buffer += token
        last_recv = datetime.utcnow()

        # if we have at least one complete sentence, start a TTS session for it
        # create a fresh tts_stream per sentence-grouping to ensure proper lifecycle
        # (Cartesia plugin typically expects push_text/end_input per session)
        # find and send any complete sentences now:
        # We'll create a session only when there's at least one full sentence to send.
        m = SENTENCE_SPLIT_RE.search(buffer)
        if m:
            tts_stream = self._cartesia_tts.stream()
            await flush_buffer_to_tts(tts_stream, force=False)
            await tts_stream.end_input()
            async for synthesized in tts_stream:
                yield synthesized.frame
            # ensure stream closed if plugin exposes aclose
            aclose = getattr(tts_stream, "aclose", None)
            if aclose:
                await aclose()

        # safety: huge buffer guard
        if len(buffer) > MAX_BUFFER_CHARS:
            # force-send chunk
            tts_stream = self._cartesia_tts.stream()
            part, buffer = buffer[:MAX_BUFFER_CHARS], buffer[MAX_BUFFER_CHARS:]
            await tts_stream.push_text(part.strip())
            await tts_stream.end_input()
            async for synthesized in tts_stream:
                yield synthesized.frame
            aclose = getattr(tts_stream, "aclose", None)
            if aclose:
                await aclose()

        # timeout-based flush if no tokens arrive
        await asyncio.sleep(0)
        if (datetime.utcnow() - last_recv).total_seconds() > FLUSH_TIMEOUT and buffer.strip():
            tts_stream = self._cartesia_tts.stream()
            await flush_buffer_to_tts(tts_stream, force=True)
            await tts_stream.end_input()
            async for synthesized in tts_stream:
                yield synthesized.frame
            aclose = getattr(tts_stream, "aclose", None)
            if aclose:
                await aclose()
            last_recv = datetime.utcnow()

    # stream ended: flush remaining buffer
    if buffer.strip():
        tts_stream = self._cartesia_tts.stream()
        await tts_stream.push_text(buffer.strip())
        await tts_stream.end_input()
        async for synthesized in tts_stream:
            yield synthesized.frame
        aclose = getattr(tts_stream, "aclose", None)
        if aclose:
            await aclose()
Key points: • Always
await tts_stream.push_text(...)
and `await tts_stream.end_input()`; they return None. • Consume audio by
async for synthesized in tts_stream:
and yield
synthesized.frame
. • Create/close a TTS session per group of sentences sent; adjust if your Cartesia plugin expects long-lived sessions. • Tune
SENTENCE_SPLIT_RE
,
FLUSH_TIMEOUT
, and
MAX_BUFFER_CHARS
for your LLM token pace. If you paste the exact Cartesia stream API (whether
push_text
is sync/async and whether sessions should be reused), I’ll adapt this to match it exactly. Sources: Pipeline nodes and hooks | LiveKit docs | Cartesia TTS plugin guide | LiveKit docs | Text-to-speech (TTS) models | LiveKit Docs