TTS Chunking Strategy - Custom tts_node Processing...
# ask-ai
j
TTS Chunking Strategy - Custom tts_node Processing vs SentenceTokenizer Configuration** --- Hi LiveKit team, Following up on the TTS chunking guidance, we have a specific question about the interaction between custom text processing and Deepgram's tokenizer configuration. ## Current Implementation ### Our Custom Sentence Chunking We override tts_node with sentence-based processing:
Copy code
python
_# In agent.py and agent-ptt.py_
async def tts_node(_self_, _text_: AsyncIterable[str], _model_settings_: ModelSettings):
    async def process_with_sentence_chunking():
        buffer = ""

        _async_ _for_ chunk _in_ text:
            _# Minimal stage direction filtering_
            filtered_chunk = filter_stage_directions(chunk)
            buffer += filtered_chunk

            _# Only break at natural sentence boundaries_
            sentence_pattern = r'([.!?][""]?\s+)'
            sentence_match = re.search(sentence_pattern, buffer)

            _if_ sentence_match:
                _# Yield complete sentences only_
                end_pos = sentence_match.end()
                to_yield = buffer[:end_pos].strip()
                buffer = buffer[end_pos:]

                _if_ to_yield:
                    _yield_ to_yield

        _# Yield remaining text_
        _if_ buffer.strip():
            _yield_ buffer.strip()

    _return_ super().tts_node(process_with_sentence_chunking(), model_settings)
### Current TTS Configuration
Copy code
python
_# Default Deepgram TTS configuration_
tts=deepgram.TTS(
    _model_=voice_model,
    _encoding_="linear16",
    _sample_rate_=24000,
)
_# No word_tokenizer specified = uses default WordTokenizer_
## The Issue ### Abrupt Audio Changes We're experiencing: - Speed/tonality changes at chunk boundaries - Choppy transitions between speech segments - Unnatural audio flow despite sentence-based chunking ### Your Recent Guidance You recommended using SentenceTokenizer:
Copy code
python
sentence_tokenizer = tokenize.basic.SentenceTokenizer(_min_sentence_len_=50)
tts = deepgram.TTS(_word_tokenizer_=sentence_tokenizer)
## Key Questions ### 1. Processing Pipeline Interaction How do these two approaches interact: - Our custom tts_node processes text into sentences - Deepgram's word_tokenizer then processes our output - Question: Does our sentence chunking get re-tokenized by Deepgram's WordTokenizer? ### 2. Redundancy vs Complementary Should we: - Use both custom sentence processing AND SentenceTokenizer? - Replace our custom processing with SentenceTokenizer only? - Keep custom processing and add SentenceTokenizer for Deepgram? - Different approach entirely? ### 3. Audio Quality Impact Which configuration provides smoothest TTS: Option A: Custom + SentenceTokenizer
Copy code
python
_# Custom sentence chunking + Sentence tokenizer_
async def process_with_sentence_chunking(): _# Our custom processing_
tts=deepgram.TTS(_word_tokenizer_=sentence_tokenizer)  _# Deepgram sentence tokenizer_
Option B: SentenceTokenizer Only
Copy code
python
_# Remove custom processing, use default tts_node_
_# Let SentenceTokenizer handle everything_
tts=deepgram.TTS(_word_tokenizer_=sentence_tokenizer)
Option C: Custom Only
Copy code
python
_# Keep custom processing, use default WordTokenizer_
_# Current approach_
### 4. Source Code Analysis From Deepgram TTS plugin implementation: - How does word_tokenizer affect the text we yield from tts_node? - Does SentenceTokenizer eliminate the need for custom sentence chunking? - Performance implications of each approach? ### 5. Tokenizer Configuration For SentenceTokenizer implementation: - Optimal min_sentence_len for therapeutic conversations? - Other configuration options to improve speech flow? - How to balance chunk size with responsiveness? ## Use Case Context Mental health therapy app where: - Audio quality critical for therapeutic rapport - Natural speech flow essential for comfort - Smooth transitions important for professional experience - Real-time conversations require responsive TTS ## Current Problem Analysis ### Suspected Issue Processing mismatch: 1. Our tts_node yields sentence-sized chunks (10-50 words) 2. Default WordTokenizer re-chunks into individual words 3. Deepgram processes many small word chunks 4. Result: Audio artifacts at word boundaries within sentences ### Expected Solution Aligned processing: 1. Our tts_node yields sentence chunks 2. SentenceTokenizer respects our sentence boundaries 3. Deepgram processes complete sentences 4. Result: Smooth audio without internal chunk artifacts ## Request Could you provide guidance on: 1. Best practice for combining custom text processing with Deepgram tokenizers 2. Redundancy elimination - which processing layer to use 3. Optimal configuration for smooth therapeutic conversation TTS 4. Performance considerations for different tokenizer approaches This will help us eliminate the TTS choppiness while maintaining our text filtering requirements! Thank you for your excellent support! ---
t
Thanks for reaching out, Albert. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! I wanted to help clarify your questions about TTS chunking strategies and how your custom processing interacts with Deepgram's SentenceTokenizer. 1. Processing Pipeline Interaction: Your custom
tts_node
handles the text before it gets to Deepgram's TTS engine. But keep in mind, Deepgram's
word_tokenizer
will still break the text down into word-level chunks for streaming synthesis. Because of this, your sentence-based chunking might not line up perfectly with Deepgram’s internal process, which could be why you're noticing some audio glitches. 2. Redundancy vs Complementary: Using both your custom sentence processing and Deepgram's SentenceTokenizer can actually work well together if set up right. That said, if both are chunking text in similar ways, it might feel a bit redundant. Here are a couple of ways to handle that: • Swap out your custom processing for SentenceTokenizer to keep things simple. • Or keep your custom processing but tweak SentenceTokenizer so it respects the sentence boundaries you’ve set. 3. Audio Quality Impact: For smoother TTS, here are some options to consider: • Option A: Use both custom processing and SentenceTokenizer together for more precise control over chunking, which can help the audio flow better. • Option B: Rely on SentenceTokenizer alone to simplify your pipeline and take advantage of Deepgram’s built-in strengths. • Option C: Using only custom processing might cause mismatches with Deepgram’s tokenization, which could lead to those audio artifacts. 4. Tokenizer Configuration: For conversations that are more therapeutic in nature, starting with a
min_sentence_len
of about 50 words works well. Feel free to adjust this based on how natural the text sounds and how responsive you want the system to be. You might also want to experiment with pacing tools like
SentenceStreamPacer
to find the right balance between chunk size and real-time performance. 5. Recommendations: To help smooth out the audio and get rid of any choppiness: • Make sure your custom
tts_node
outputs complete sentences. • Use Deepgram’s SentenceTokenizer so the chunking matches up with its internal processing. • Try out different setups to see what feels best for your specific needs. If you want, I’m here to help you with implementation or testing—just let me know! Sources: Agent speech and audio | LiveKit Docs | examples/voice_agents/speedup_output_audio.py | Agents 0.x migration guide | LiveKit Docs | pipeline-tts/short_replies_only.py | An open source stack for real-time multimodal AI
j
does deepgram have sentencetokenizer -- or is this not exist?
t
Hey there! Just a heads-up—Deepgram TTS doesn’t have a built-in
SentenceTokenizer
. It actually uses a
word_tokenizer
to handle things word by word. But don’t worry! The LiveKit framework has your back by letting you add sentence-level tokenization. You can do this by wrapping your Deepgram TTS instance with a
StreamAdapter
and popping in a
SentenceTokenizer
. This way, you can still break things down sentence by sentence, even though Deepgram doesn’t do it out of the box. If you want, I’d be happy to walk you through how to set it up—just let me know! Sources: livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/__init__.... | StreamAdapter | LiveKit Agents | StreamAdapterWrapper | LiveKit Agents | agents/src/pipeline/pipeline_agent.ts
j
show me how
t
Here’s a friendly guide on how you can set up a
StreamAdapter
with a
SentenceTokenizer
for Deepgram TTS in LiveKit:
Copy code
from livekit.agents.tts import StreamAdapter
from livekit.plugins import deepgram
from livekit.agents.tokenize import blingfire

# Initialize Deepgram TTS
tts = deepgram.TTS(model="aura-asteria-en")

# Create a sentence tokenizer
tokenizer = blingfire.SentenceTokenizer()

# Wrap TTS with StreamAdapter
tts_wrapped = StreamAdapter(tts=tts, sentence_tokenizer=tokenizer)
stream = tts_wrapped.stream()

# Push text in chunks
stream.push_text("Hello! This is a streaming demo.")
stream.flush()
stream.end_input()

# Handle audio output
async for audio in stream:
    await source.capture_frame(audio.frame)
Here’s what to do step-by-step: 1. Start by initializing the Deepgram TTS instance with the model you want. 2. Create a
SentenceTokenizer
to break your text into neat sentences. 3. Wrap your TTS instance with
StreamAdapter
, and pass in the tokenizer. 4. Use the
stream()
method to send text in and handle the audio output asynchronously. This setup helps split your text into meaningful chunks, making the audio sound smoother and more natural. If you have any questions or want to dive deeper, just let me know—I’m here to help! Sources: tests/test_tts.py | SentenceTokenizer | LiveKit Agents | agents/src/pipeline/pipeline_agent.ts
j
how. change dthis to make tts speak in one long chunk? tts=deepgram.TTS( model=voice_model, encoding="linear16", # Crisp, clear audio per LiveKit recommendation _sample_rate_=24000, # Higher sample rate for quality _word_tokenizer_=tokenize.basic.SentenceTokenizer(_min_sentence_len_=1000), # Much larger chunks for even smoother audio ),
t
If you want Deepgram TTS to process your text as one long chunk, here’s a simple way to do it: 1. Use the
synthesize()
method instead of
stream()
. The
synthesize()
method sends all your text at once to the Deepgram API, so it treats it as a single piece. 2. Make sure to pass the full text string directly to
synthesize()
, rather than sending it bit by bit, which can cause it to split up. 3. Double-check that your
tts_node
isn’t chopping the text into smaller parts before it reaches the TTS engine. Here’s a quick example to illustrate:
Copy code
from livekit.plugins import deepgram

# Initialize Deepgram TTS
tts = deepgram.TTS(model="aura-asteria-en")

# Process text as one long chunk
output_audio = await tts.synthesize("This is a very long text that should be processed as a single chunk.")

# Handle the audio output
with open("output.wav", "wb") as f:
    f.write(output_audio)
This way, your text gets processed all at once, so you won’t have to worry about it being split up internally. If you have any questions or want me to walk you through it, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/tts/tts.py | Pipeline nodes and hooks | LiveKit Docs | pipeline-tts/tts_node.py
j
LiveKit Slack/DiscordTopic: TTS Configuration & Audio Quality --- Question: Hi LiveKit team! I'm working with LiveKit Agents 1.2.2 and trying to optimize Deepgram TTS for smoother audio output. Current Issue: I want to reduce TTS choppiness by using larger text chunks (sentence/paragraph level) instead of word-by-word streaming, but I'm running into a limitation. What I Tried: tts=deepgram.TTS( model=voice_model, encoding="linear16", sample_rate=24000, word_tokenizer=tokenize.basic.SentenceTokenizer(min_sentence_len=1000) # ❌ This doesn't work ) Problem: Deepgram TTS only accepts WordTokenizer, not SentenceTokenizer. Looking at the source code, it falls back to default word-level chunking, resulting in choppy audio. Questions: 1. Is there a way to configure Deepgram TTS for sentence/paragraph-level chunking instead of word-level? 2. Are there other TTS providers in LiveKit that support SentenceTokenizer for smoother audio? 3. Would using a different encoding (like "mp3") affect chunking behavior? 4. Any recommended approaches for reducing TTS choppiness in voice agents? Goal: Deliver complete sentences/thoughts as single audio segments rather than word-by-word streaming for more natural conversation flow. Context: Using both continuous voice and push-to-talk modes. Thanks for any guidance on achieving smoother TTS output!
t
Hey there! Let me walk you through some tips on optimizing Deepgram TTS for smoother audio output: 1. Configuring Deepgram TTS for Sentence/Paragraph-Level Chunking: Deepgram TTS doesn’t natively support chunking by sentence or paragraph, but no worries! You can get around this by customizing the
tts_node
in your agent to handle text sentence by sentence before sending it off to the TTS engine. Using a
SentenceTokenizer
helps break the text into bigger, more natural chunks. 2. Other TTS Providers Supporting SentenceTokenizer: If sentence-level chunking is a must-have for you, providers like Cartesia and ElevenLabs in LiveKit have built-in support for sentence tokenization. They might be a great fit depending on what you need. 3. Encoding Impact on Chunking: Just a heads-up: changing the encoding format (like switching to "mp3") won’t change how chunking works. That’s all about the tokenizer and streaming setup, not the audio format itself. 4. Reducing TTS Choppiness: Here are a few friendly tips to smooth things out: If you want, I’m happy to help you dive deeper into setting up a custom
tts_node
or exploring other providers—just let me know! Sources: livekit-plugins/livekit-plugins-elevenlabs/livekit/plugins/elevenlabs/tts.p... | Pipeline nodes and hooks | LiveKit Docs
j
should we use batch vs stream?
t
When deciding between batch and stream processing for TTS, it really depends on what you’re aiming to do: Batch Processing: This is great if you have the full text ready from the start and want to generate speech for everything all at once. It works best for static content where you don’t need things to happen in real-time. Stream Processing: Go for stream processing if you want to generate speech bit by bit as the text comes in. This is perfect for real-time chats or conversations because it lets the audio play while the text is still coming, making everything feel more natural and responsive. Here’s a little tip: For things like voice agents or therapeutic chats, stream processing usually wins out. It helps start the speech sooner, even before the full response is ready, which means a smoother, quicker experience for users. Plus, tools like
SentenceStreamPacer
can help keep the flow steady and avoid any awkward pauses during streaming. If you want a hand setting up either one, just give me a shout—I’m here to help! Sources: Live Conversations with AI using ChatGPT and WebRTC | Live Conversations with AI using ChatGPT and WebRTC | livekit-plugins/livekit-plugins-cartesia/livekit/plugins/cartesia/tts.py | Live Conversations with AI using ChatGPT and WebRTC
j
available in deepgram? SentenceStreamPacer
t
The
SentenceStreamPacer
isn’t something you can access directly in Deepgram TTS, but no worries—you can still use it indirectly by wrapping Deepgram TTS with the
StreamAdapter
in LiveKit. The
StreamAdapter
comes with text pacing turned on by default, which actually uses
SentenceStreamPacer
behind the scenes to buffer sentences and send them in batches based on audio length and text size. Here’s a quick example to get you started:
Copy code
from livekit.agents.tts import StreamAdapter
from livekit.plugins import deepgram

# Wrap Deepgram TTS with StreamAdapter
tts_wrapped = StreamAdapter(
    tts=deepgram.TTS(model="aura-asteria-en"),
    text_pacing=True,  # Enables SentenceStreamPacer
)
This setup is great for making the speech sound smoother and cutting down on any interruptions while streaming. If you have any questions or want to chat more about it, just let me know—I’m here to help! Sources: livekit-plugins/livekit-plugins-cartesia/livekit/plugins/cartesia/tts.py