cool-lizard-26153
12/10/2025, 10:16 AMtall-airline-16756
12/10/2025, 10:17 AMtall-airline-16756
12/10/2025, 10:17 AMsession = 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 AIcool-lizard-26153
12/10/2025, 10:18 AMtall-airline-16756
12/10/2025, 10:19 AMtts_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 docscool-lizard-26153
12/10/2025, 10:20 AMtall-airline-16756
12/10/2025, 10:20 AMtts_node in your AgentSession):
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?cool-lizard-26153
12/10/2025, 10:22 AMtall-airline-16756
12/10/2025, 10:22 AMtts_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):
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 docscool-lizard-26153
12/10/2025, 10:26 AMtall-airline-16756
12/10/2025, 10:26 AMtts_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.
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?cool-lizard-26153
12/10/2025, 10:31 AMtall-airline-16756
12/10/2025, 10:32 AMawait 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:
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:
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.cool-lizard-26153
12/10/2025, 10:35 AMtall-airline-16756
12/10/2025, 10:35 AMtts_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 docscool-lizard-26153
12/10/2025, 10:40 AMtall-airline-16756
12/10/2025, 10:40 AMtts_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.
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):
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:
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 Docscool-lizard-26153
12/10/2025, 10:43 AMtall-airline-16756
12/10/2025, 10:43 AMAgentSession(...) 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:
# 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.