I'm setting SentenceTokenizer and setting min sent...
# ask-ai
c
I'm setting SentenceTokenizer and setting min sentence length from 20 - default to 5. I want to send even 1-2 word sentences immediately to Cartesia TTS provider without waiting for longer streams. what is the suggested configuration changes?
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.
Acknowledging you want 1–2 word segments sent immediately to Cartesia TTS instead of waiting for longer sentences. Here are concise, practical changes you can make. 1) Lower tokenizer threshold • Set
min_sentence_length
to 1–2 (e.g.,
min_sentence_length=2
) so the tokenizer considers very short segments eligible for flush. 2) Flush short chunks immediately • Use Cartesia’s incremental API: call
flush_text()
for each short segment as soon as it’s available so it’s sent without buffering. 3) Bypass or override SentenceTokenizer when needed • If the pipeline still buffers, override your
tts_node
to skip the default tokenizer and forward incoming text chunks directly to Cartesia’s stream (calling
flush_text()
per chunk). 4) Use word-based chunking as a fallback • If sentence boundaries aren’t detected reliably, split incoming text by words and group into 1–2 word chunks, sending each chunk with
flush_text()
. 5) Verify streaming mode is enabled • Ensure Cartesia TTS is used in streaming/incremental mode (not batch) so immediate flushes produce audio frames. Trade-off note: very short immediate chunks can reduce natural prosody; test with target phrases to tune chunk size or occasional aggregation. Would you like a short code example for overriding
tts_node
and calling
flush_text()
? Sources: Cartesia TTS plugin guide | LiveKit docs | Pipeline nodes and hooks | LiveKit docs
c
yes please?
t
Below is a concise Python example that: • sets
min_sentence_length=2
, • overrides
tts_node
to bypass default tokenization, • splits incoming text into 1–2 word chunks, • calls Cartesia TTS stream's
flush_text()
for immediate synthesis. Adjust imports/names to match your project.
Copy code
from typing import AsyncIterable
from livekit.agents import Agent
from livekit.agents.models import cartesia  # adjust import to your Cartesia plugin
from livekit import rtc

class LowLatencyTTSAgent(Agent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # If your agent/framework exposes tokenizer settings globally, set it here:
        self.sentence_tokenizer_settings = {"min_sentence_length": 2}

    async def tts_node(self, text: AsyncIterable[str], model_settings) -> AsyncIterable[rtc.AudioFrame]:
        """
        Receives an async stream of text segments (from ASR or upstream).
        This node splits into 1-2 word chunks and immediately flushes each chunk
        to Cartesia's streaming TTS using flush_text().
        """
        tts = cartesia.TTS()             # construct Cartesia TTS client/plugin
        stream = tts.stream()            # open streaming session

        async for segment in text:
            segment = (segment or "").strip()
            if not segment:
                continue

            # Simple word-based chunking: 1-2 words per flush
            words = segment.split()
            i = 0
            while i < len(words):
                chunk = " ".join(words[i : i + 2])
                i += 2

                # Send chunk immediately to Cartesia and yield generated audio frames
                # Use flush_text to force immediate incremental synthesis
                async for audio_frame in stream.flush_text(chunk):
                    yield audio_frame

        # Optionally finalize/end the stream if the plugin requires it
        try:
            async for audio_frame in stream.flush_text(""):  # flush any remaining buffer
                yield audio_frame
        except Exception:
            pass
Notes: • Keep
min_sentence_length=2
so any tokenizer that still runs will allow short sentences. • Splitting by words guarantees 1–2 word chunks even when punctuation isn't present. • Test output for prosody; you can increase chunk size to 3–4 words if synth quality suffers. • If your agent framework requires different Cartesia client usage, swap
cartesia.TTS()
and
stream.flush_text()
calls for your SDK equivalents. Want this adapted to a specific framework file or an async runner you’re using?
c
how do I ensure cartesia is configured in stream mode and not batch mode?
t
You’re already on the right track. To ensure Cartesia runs in streaming (low-latency) mode and not batch mode, do the following: 1. Use the Cartesia plugin and its streaming interface • Construct the plugin and call
tts.stream()
(the streaming session) — streaming is used when you create and consume a stream. 1. Push text incrementally and flush immediately • Send each short segment as soon as it’s available with
push_text()
or
flush_text()
(depending on your Cartesia client) rather than accumulating a large buffer. 1. Avoid waiting for tokenizer boundaries • Override your
tts_node
or bypass the default SentenceTokenizer so incoming 1–2 word segments are forwarded immediately to the
tts_stream
. 1. No extra “enable streaming” flag required • Cartesia in LiveKit is streaming-capable by default — you just need to use the streaming API and feed small chunks incrementally. Minimal example pattern (adjust to your SDK):
Copy code
tts = cartesia.TTS(model="sonic-3", voice="your-voice-id")
stream = tts.stream()

# push short chunks right away
await stream.push_text("Yes")
await stream.push_text("Go")
# consume audio frames as they arrive
async for audio_frame in stream:
    await audio_source.capture_frame(audio_frame)
If you want, I can adapt that snippet to the exact Cartesia client methods your project uses (e.g.,
flush_text()
vs
push_text()
), or show a full
tts_node
override. Which method name does your Cartesia client expose? Sources: Cartesia TTS plugin guide | LiveKit docs | Text-to-speech (TTS) models | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Text and transcriptions | LiveKit docs
c
i'm not overriding the tts_node as of now, how to make sure that streaming is happening
t
You're not overriding
tts_node
— here are quick checks and actions to confirm streaming is happening and minimize buffering. 1) Confirm you use the streaming API • Verify your code (or the agent pipeline) calls
tts.stream()
and then sends text with
push_text()
or
flush_text()
rather than a single batch call like
synthesize(text)
. 2) Observe real-time audio frames • While running, consume the stream and check you receive audio frames incrementally (first audio should arrive after each short chunk). Example behavior: after
push_text("Yes")
you get audio frames before sending the next chunk. 3) Check logs/DEBUG output • Enable debug logging for the Cartesia plugin or LiveKit Agents. Look for entries showing incremental requests/packets or streaming session creation (e.g., "started stream", "pushed text", "received audio frame"). Incremental push/flush calls should appear per short segment. 4) Verify no upstream buffering • Ensure upstream components (ASR, SentenceTokenizer) are not aggregating text. If you can’t/aren’t overriding
tts_node
, set the tokenizer config to a low value (e.g.,
min_sentence_length=1
or
2
) so it forwards short segments quickly. 5) Measure latency end-to-end • Send a 1–2 word input and measure time from push to first audio frame. Low-latency streaming returns audio within a few hundred milliseconds for short chunks. If you want, paste the snippet that forwards text into the agent (or the tokenizer settings) and I’ll point out exactly where to check or change it.