when using Cartesia for TTS with livekit python sd...
# ask-ai
c
when using Cartesia for TTS with livekit python sdk, there is a lot of buffering happening before the text is sent to TTS, how do I reduce this?
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 how to reduce the buffering/latency when using Cartesia TTS with the LiveKit Python SDK — here are focused steps you can try. 1. Use LiveKit Inference descriptor (avoids plugin init overhead) • Instead of creating a full plugin object, pass a descriptor string:
Copy code
session = AgentSession(tts="cartesia/sonic-3:voice-id", ...)
This can reduce initialization buffering. 1. Pick a lower-latency Cartesia model • Use Cartesia models optimized for speed (e.g.,
sonic-
variants like `sonic-3`/`sonic-turbo` where available). 1. Minimize preprocessing before sending text • Remove unnecessary SSML or heavy text transformations and avoid extra tokenization steps prior to TTS calls. 1. Co-locate services to reduce network RTT • Run your agent/server in the same region as Cartesia’s API endpoints to cut round-trip time. 1. Enable TTS-aligned transcripts (improves sync, not generation time) • Set
use_tts_aligned_transcript=True
in your session so transcripts align with actual audio output, improving perceived responsiveness. 1. Test streaming options / check for Cartesia streaming params • Some providers expose streaming or latency params (e.g.,
streaming_latency
or
reduce_latency
). Cartesia-specific streaming knobs are not documented here — if you can try similar streaming flags or a
reduce_latency
-style option in your Cartesia client, test lower values and measure impact. If you’d like, tell me: • the exact Cartesia model/voice name you’re using, • a short code snippet of how you initialize TTS in Python, so I can suggest the most specific change to reduce buffering. Sources: Rime TTS plugin guide | LiveKit Docs | ElevenLabs TTS plugin guide | LiveKit Docs | Cartesia TTS plugin guide | LiveKit docs | Cartesia TTS | LiveKit docs | Introducing LiveKit Inference: A unified model interface for voice AI
c
No, I'm asking how to reduce the amount of text that goes into buffer before it's actually sent to TTS
t
Thanks — I understand you mean the pre-send text aggregation (how much text is collected before being passed to Cartesia). I can help tune that — a couple quick questions so I give a precise fix: 1. Are you using LiveKit Inference/AgentSession or a custom agent implementation? 2. Do you currently send one large string per utterance, or are you streaming smaller text pieces into the agent (paste a short code snippet of your TTS-call path)? 3. Do you want strict per-chunk sending (send every incoming chunk immediately) or sentence-aware chunks (send when punctuation/boundary seen)? If you want an immediate path forward, the most direct option is to override the agent’s
tts_node
to control chunking and yield smaller text units immediately (I can show a minimal Python example once you tell me which of the above matches your setup). Which option would you like me to show? Sources: Agents (Node.js) | livekit/livekit_composite | DeepWiki | Pipeline nodes and hooks | LiveKit docs
c
I'm using Livekit Agentsession. I sent smaller text pieces only. I don't want a per-chunk sending but a sentence-aware chunks with punctuation boundaries
t
You're aiming to send sentence-aware chunks (split on punctuation) from an AgentSession so smaller sentence units are forwarded to Cartesia TTS. Below is a focused solution: override the session's TTS node to buffer incoming small pieces into sentence-aware chunks and yield each sentence as soon as a boundary is detected. Key idea • Collect incoming text pieces into a short buffer. • Use a simple sentence boundary splitter (regex on punctuation like .!? and newline) to emit complete sentences immediately. • Keep any trailing partial sentence in the buffer until more text arrives. Minimal example (override
tts_node
in your AgentSession):
Copy code
import re
from typing import AsyncIterable, List
from livekit_inference import AgentSession, ModelSettings  # adjust imports to your SDK

SENTENCE_RE = re.compile(r'(.+?[\.\!\?]+)(\s+|$)', re.S)

class MyAgentSession(AgentSession):
    async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
        buffer = ""
        async for piece in text:
            buffer += piece
            # find complete sentences
            pos = 0
            for m in SENTENCE_RE.finditer(buffer):
                sentence = m.group(1).strip()
                if sentence:
                    # yield/send the sentence as a single chunk to TTS
                    yield sentence
                pos = m.end()
            # keep remainder (partial sentence)
            buffer = buffer[pos:]
        # flush leftover buffer as final chunk
        if buffer.strip():
            yield buffer.strip()
Notes and tuning • The regex above detects sentences ending with ., !, or ? followed by space or end-of-text. Tune it for abbreviations or different punctuation rules. • If you need to preserve some small trailing punctuation before sending, adjust the regex capture. • This sends each detected sentence immediately rather than waiting for a full utterance. • If Cartesia supports streaming, this approach helps reduce perceived buffering while keeping sentence-level cohesion. Would you like a version that: • respects max sentence length (force-send very long runs), or • handles common abbreviations (e.g., "Dr.", "e.g.") to avoid premature splits?
c
The base AgentSession class isn't having tts_node method, how does this help in any way?
t
You're right —
tts_node
isn't on
AgentSession
. Thank you for calling that out. Short answer: implement the sentence-aware buffering in a custom Agent (override
tts_node
there), then pass that Agent instance into your AgentSession. The AgentSession will use your Agent's node implementations in the pipeline. Concise example (override in an Agent subclass and use with AgentSession):
Copy code
import re
from typing import AsyncIterable
from livekit.agents import Agent, AgentSession
from livekit.plugins import cartesia
from livekit.agents.types import ModelSettings

SENTENCE_RE = re.compile(r'(.+?[\.\!\?]+)(\s+|$)', re.S)

class MyAgent(Agent):
    async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
        buffer = ""
        async for piece in text:
            buffer += piece
            pos = 0
            for m in SENTENCE_RE.finditer(buffer):
                sentence = m.group(1).strip()
                if sentence:
                    # forward sentence to default TTS node which returns audio frames
                    async for frame in Agent.default.tts_node(self, [sentence], model_settings):
                        yield frame
                pos = m.end()
            buffer = buffer[pos:]
        if buffer.strip():
            async for frame in Agent.default.tts_node(self, [buffer.strip()], model_settings):
                yield frame

# use your agent with AgentSession
session = AgentSession(
    stt="assemblyai/universal-streaming:en",
    llm="openai/gpt-4.1-mini",
    tts="cartesia/sonic-3:voice-id",
)

await session.start(room=room, agent=MyAgent())
If you prefer, I can: • provide a version that avoids splitting on common abbreviations (e.g., "Dr.", "e.g."), • add a max-sentence-length cutoff to force-send very long runs, • or adapt this to your exact SDK imports if yours differ. Which would you like? Sources: Pipeline nodes and hooks | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs | Agent speech and audio | LiveKit docs
c
provide a version that avoids splitting on common abbreviations and add a max-setence-length cutoff
t
Below is a focused Agent
tts_node
implementation that: • Buffers incoming text pieces, • Splits into sentence-aware chunks using punctuation boundaries, • Avoids splitting on a configurable list of common abbreviations, • Forces-send when a max sentence length (characters) is exceeded. Adjust
ABBREVIATIONS
and
MAX_SENTENCE_LEN
to fit your needs.
Copy code
import re
from typing import AsyncIterable
from livekit.agents import Agent, AgentSession
from livekit.agents.types import ModelSettings

# Tune these
ABBREVIATIONS = {
    "mr.", "mrs.", "ms.", "dr.", "prof.", "sr.", "jr.",
    "e.g.", "i.e.", "vs.", "etc.", "st.", "rd.", "ave.", "inc.", "corp."
}
MAX_SENTENCE_LEN = 300  # force-send if buffer exceeds this many characters

# Regex captures sentence-like fragments ending with . ! ? or newline
_FRAG_RE = re.compile(r'(.+?[\.\!\?\n]+)(\s+|$)', re.S)

def _ends_with_abbrev(fragment: str) -> bool:
    # lower and trim trailing whitespace for match
    frag = fragment.rstrip().lower()
    # check last token(s) against abbreviations
    # examine last 1-3 tokens joined with dots (to catch "e.g." etc.)
    tokens = frag.split()
    if not tokens:
        return False
    last = tokens[-1]
    # direct match
    if last in ABBREVIATIONS:
        return True
    # also check if last token ends with an abbreviation (e.g., "Smith, Dr.")
    # check punctuation-trimmed token
    last_clean = re.sub(r'^[^\w]+|[^\w]+$', '', last).lower()
    if last_clean in ABBREVIATIONS:
        return True
    return False

class MyAgent(Agent):
    async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
        buffer = ""
        async for piece in text:
            buffer += piece

            # If buffer is too long, force-send chunks from its start
            if len(buffer) > MAX_SENTENCE_LEN:
                # take up to MAX_SENTENCE_LEN and try to cut at last punctuation inside that slice
                slice_ = buffer[:MAX_SENTENCE_LEN]
                m = list(_FRAG_RE.finditer(slice_))
                if m:
                    # choose last complete fragment inside slice
                    last = m[-1].group(1).strip()
                    if last and not _ends_with_abbrev(last):
                        async for frame in Agent.default.tts_node(self, [last], model_settings):
                            yield frame
                        buffer = buffer[len(m[-1].group(0)):]
                        continue
                # fallback: force-send the slice as-is
                to_send = slice_.strip()
                if to_send:
                    async for frame in Agent.default.tts_node(self, [to_send], model_settings):
                        yield frame
                buffer = buffer[len(slice_):]
                continue

            pos = 0
            for m in _FRAG_RE.finditer(buffer):
                frag = m.group(1).strip()
                if not frag:
                    pos = m.end()
                    continue

                # If fragment ends with an abbreviation, keep it in buffer (don't send yet)
                if _ends_with_abbrev(frag):
                    pos = m.end()
                    continue

                # Otherwise emit this sentence fragment
                async for frame in Agent.default.tts_node(self, [frag], model_settings):
                    yield frame
                pos = m.end()

            buffer = buffer[pos:]

        # flush any remaining buffer
        if buffer.strip():
            remaining = buffer.strip()
            # If remaining is longer than max and still contains abbrev at end:
            if len(remaining) > MAX_SENTENCE_LEN:
                # split by safe chunks of MAX_SENTENCE_LEN without breaking words
                start = 0
                while start < len(remaining):
                    end = min(start + MAX_SENTENCE_LEN, len(remaining))
                    # try to cut at last whitespace before end
                    if end < len(remaining):
                        cut = remaining.rfind(" ", start, end)
                        if cut > start:
                            chunk = remaining[start:cut].strip()
                            start = cut + 1
                        else:
                            chunk = remaining[start:end].strip()
                            start = end
                    else:
                        chunk = remaining[start:end].strip()
                        start = end
                    if chunk:
                        async for frame in Agent.default.tts_node(self, [chunk], model_settings):
                            yield frame
            else:
                async for frame in Agent.default.tts_node(self, [remaining], model_settings):
                    yield frame
If you want, I can: • Expand the
ABBREVIATIONS
list or provide a pattern-based abbreviation matcher (e.g., initials like "U.S.A."), • Lower MAX_SENTENCE_LEN or add a minimum chunk size to avoid too-short TTS calls. Which tweak would you like?
c
this code isn't working. my agents doesn't speak at all
t
Sorry that happened — let’s diagnose and get audio working quickly. Quick checks • Do you see any errors or exceptions in your agent/server logs when the session starts or when TTS should play? Copy any stack trace lines you see. • Confirm you passed your Agent instance into AgentSession.start (not into AgentSession constructor). Example used earlier:
await session.start(room=room, agent=MyAgent())
. • Confirm your AgentSession
tts
value is valid (e.g.,
"cartesia/sonic-3:voice-id"
). • Confirm the session actually reached the point of sending audio (LLM produced text). Do transcripts or debug logs show text being sent into your custom
tts_node
? Minimal isolation test 1. Replace your custom
tts_node
with a trivial pass-through that sends everything immediately to the default TTS node to confirm audio works:
Copy code
class TestAgent(Agent):
    async def tts_node(self, text, model_settings):
        async for piece in text:
            async for frame in Agent.default.tts_node(self, [piece], model_settings):
                yield frame
• If audio plays with this, the issue is in the buffering/splitting logic. If audio still doesn't play, the problem is upstream (session wiring, tts config, or SDK version). If pass-through works, try a simpler buffered version that emits on newline only:
Copy code
class TestAgent(Agent):
    async def tts_node(self, text, model_settings):
        buf = ""
        async for piece in text:
            buf += piece
            if "\n" in buf:
                line, _, buf = buf.partition("\n")
                async for frame in Agent.default.tts_node(self, [line.strip()], model_settings):
                    yield frame
        if buf.strip():
            async for frame in Agent.default.tts_node(self, [buf.strip()], model_settings):
                yield frame
Common pitfalls • Your regex or abbreviation check might swallow text (e.g., pos logic sets buffer to full string). Add logging inside the
async for piece in text
loop to confirm
piece
values and buffer contents. • If
Agent.default.tts_node
yields nothing because
model_settings
is wrong or
tts
config is missing, nothing will be spoken. Log
model_settings
and the
tts
descriptor. • Ensure you’re using a compatible SDK version where node overrides are supported. Please run the pass-through test and share: • Any logs/errors you see, • A short snippet showing how you call
session.start(...)
, • The exact
tts
string you configured. I’ll use that to pinpoint whether the problem is integration, config, or the sentence-splitting code and provide a corrected snippet.
c
instead of extending the tts_node, can I just not play with the tokenize methods?
t
Short answer: no — you should not poke at internal tokenize methods. They aren’t a supported public extension point and changing them can break the pipeline. The supported ways to control what gets sent to TTS are: • Use Cartesia’s streaming-capable plugin so text can be sent as it’s produced (reduces need for chunking). • Override the Agent’s tts_node (not AgentSession) to implement sentence-aware buffering and max-length logic — this is the supported extension point. • Or preprocess/split text before feeding it into the Agent (i.e., push sentence-aware pieces into the session upstream). Since your tts_node attempt resulted in no audio, I can help debug the exact issue quickly. To proceed, please paste: 1. The Agent subclass code you used for
tts_node
. 2. How you call
session.start(...)
(the snippet showing passing your Agent). 3. Any logs/errors around when TTS should play. I’ll point out the minimal fix (common issues: missing async yields, not passing Agent instance to session.start, wrong
tts
string, or
Agent.default.tts_node
not being iterated). Sources: Pipeline nodes and hooks | LiveKit docs | Cartesia TTS plugin guide | LiveKit docs
c
can you give a working example for this: • Override the Agent’s tts_node (not AgentSession) to implement sentence-aware buffering and max-length logic — this is the supported extension point.
t
Acknowledged — below is a concise, working example you can drop into your project. It overrides the Agent’s
tts_node
(not AgentSession), implements sentence-aware buffering that avoids common abbreviations, and enforces a max sentence length cutoff. It yields audio frames from
Agent.default.tts_node
so LiveKit will play the audio. Adjust
ABBREVIATIONS
,
MAX_SENTENCE_LEN
, and Cartesia voice/model values as needed.
Copy code
import re
from typing import AsyncIterable
from livekit import rtc
from livekit.agents import Agent, AgentSession
from livekit.agents.types import ModelSettings
from livekit.plugins import cartesia

# Configs
ABBREVIATIONS = {
    "mr.", "mrs.", "ms.", "dr.", "prof.", "sr.", "jr.",
    "e.g.", "i.e.", "vs.", "etc.", "st.", "rd.", "ave.", "inc.", "corp."
}
MAX_SENTENCE_LEN = 300  # chars before forcing a flush

# Regex: fragment ending with punctuation (., !, ?, or newline) and trailing whitespace
_FRAG_RE = re.compile(r'(.+?[\.\!\?\n]+)(\s+|$)', re.S)

def _ends_with_abbrev(fragment: str) -> bool:
    frag = fragment.rstrip().lower()
    if not frag:
        return False
    # Check last token and clean punctuation
    tokens = frag.split()
    last = tokens[-1]
    last_clean = re.sub(r'^[^\w]+|[^\w]+$', '', last).lower()
    return last in ABBREVIATIONS or last_clean in ABBREVIATIONS

class SentenceAgent(Agent):
    def __init__(self, *args, **kwargs):
        # configure TTS plugin here or pass via AgentSession
        super().__init__(*args, **kwargs)

    async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings) -> AsyncIterable[rtc.AudioFrame]:
        buffer = ""
        async for piece in text:
            buffer += piece

            # If buffer is too long, try to emit a safe fragment inside the limit
            if len(buffer) >= MAX_SENTENCE_LEN:
                slice_ = buffer[:MAX_SENTENCE_LEN]
                matches = list(_FRAG_RE.finditer(slice_))
                if matches:
                    last_frag = matches[-1].group(1).strip()
                    # only send if not ending with abbreviation
                    if last_frag and not _ends_with_abbrev(last_frag):
                        async for frame in Agent.default.tts_node(self, [last_frag], model_settings):
                            yield frame
                        buffer = buffer[matches[-1].end():]
                        continue
                # fallback: force-send up to MAX_SENTENCE_LEN (try not to cut in middle of word)
                cut = slice_.rfind(" ")
                if cut > 0:
                    to_send = slice_[:cut].strip()
                    rest_start = cut + 1
                else:
                    to_send = slice_.strip()
                    rest_start = len(to_send)
                if to_send:
                    async for frame in Agent.default.tts_node(self, [to_send], model_settings):
                        yield frame
                buffer = buffer[rest_start:]
                continue

            # Emit complete fragments found in buffer
            pos = 0
            for m in _FRAG_RE.finditer(buffer):
                frag = m.group(1).strip()
                pos = m.end()
                if not frag:
                    continue
                if _ends_with_abbrev(frag):
                    # keep in buffer until more text arrives
                    continue
                async for frame in Agent.default.tts_node(self, [frag], model_settings):
                    yield frame
            buffer = buffer[pos:]

        # flush remaining
        if buffer.strip():
            remaining = buffer.strip()
            # if remaining is longer than max, break into safe chunks
            if len(remaining) > MAX_SENTENCE_LEN:
                start = 0
                while start < len(remaining):
                    end = min(start + MAX_SENTENCE_LEN, len(remaining))
                    if end < len(remaining):
                        cut = remaining.rfind(" ", start, end)
                        if cut > start:
                            chunk = remaining[start:cut].strip()
                            start = cut + 1
                        else:
                            chunk = remaining[start:end].strip()
                            start = end
                    else:
                        chunk = remaining[start:end].strip()
                        start = end
                    if chunk:
                        async for frame in Agent.default.tts_node(self, [chunk], model_settings):
                            yield frame
            else:
                async for frame in Agent.default.tts_node(self, [remaining], model_settings):
                    yield frame
Usage (pass agent into start; set TTS on AgentSession or via Agent constructor):
Copy code
session = AgentSession(
    stt="assemblyai/universal-streaming:en",
    llm="openai/gpt-4.1-mini",
    tts="cartesia/sonic-3:voice-id",  # or configure cartesia.TTS in Agent constructor
)

agent = SentenceAgent()
await session.start(room=room, agent=agent)
If this doesn't produce audio: • Run a quick pass-through test to confirm audio plumbing:
Copy code
class PassthroughAgent(Agent):
    async def tts_node(self, text, model_settings):
        async for piece in text:
            async for frame in Agent.default.tts_node(self, [piece], model_settings):
                yield frame
Share any logs/errors if passthrough works but SentenceAgent doesn't — I’ll pinpoint the fix. Sources: Cartesia TTS plugin guide | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | Agent speech and audio | LiveKit docs | Text-to-speech (TTS) models | LiveKit Docs
c
The passthrough also isn't sending any audio
t
Thanks — since passthrough also produces no audio, the problem is likely integration/config rather than the chunking logic. I can debug this quickly — please provide these items: 1. The Agent subclass code you used (the passthrough one). 2. The exact snippet you use to start the session (how you call
AgentSession(...)
and
await session.start(...)
). 3. The
tts
value you configured (e.g., "cartesia/sonic-3:voice-id"). 4. SDK/package versions (output of
pip show livekit-agents livekit-plugins-cartesia
or your requirements). 5. Any logs or console output when you start the agent and when LLM produces text (include errors/tracebacks). 6. Confirm you have a participant in the room and whether the agent is joining the same room (briefly: are you running locally or via livekit-agent CLI). Meanwhile, quick checks you can run now: • Verify Cartesia API key is set in env (CARTESIA_API_KEY) and valid. • Run a minimal pass-through test outside the session to confirm default TTS works:
Copy code
# minimal check: directly call default.tts_node with a static sentence
agent = PassthroughAgent()
async for frame in Agent.default.tts_node(agent, ["hello world"], some_model_settings):
    print("got frame", type(frame))
(If frames print, audio generation works; issue is session wiring.) Send the items above and I’ll pinpoint the fix.