jolly-eve-3916
08/25/2025, 4:42 PMpython
_# Both agent.py and agent-ptt.py_
session = AgentSession(
_stt_=deepgram.STT(_model_="nova-3"),
_tts_=deepgram.TTS(_model_="aura-2-cora-en"), _# Default config_
_# ... other settings_
)
### Custom Text Processing (Potential Issue)
We override tts_node with custom text chunking:
python
async def tts_node(_self_, _text_: AsyncIterable[str], _model_settings_: ModelSettings):
async def process_with_word_boundary_preservation():
buffer = ""
_async_ _for_ chunk _in_ text:
_# Filter stage directions from the chunk_
filtered_chunk = filter_stage_directions(chunk)
buffer += filtered_chunk
_# Check for sentence endings first (highest priority)_
sentence_pattern = r'([.!?。!?][""]?\s+)'
sentence_match = re.search(sentence_pattern, buffer)
_if_ sentence_match:
_# Found sentence boundary - yield everything up to and including it_
end_pos = sentence_match.end()
to_yield = buffer[:end_pos].strip()
buffer = buffer[end_pos:]
_if_ to_yield:
_yield_ to_yield + " "
_# If no sentence boundary and buffer is getting long, look for clause breaks_
_elif_ len(buffer) > 80:
_# Look for clause boundaries (commas, semicolons)_
clause_pattern = r'([,;]\s+)'
clause_match = re.search(clause_pattern, buffer)
_if_ clause_match:
end_pos = clause_match.end()
to_yield = buffer[:end_pos].strip()
buffer = buffer[end_pos:]
_if_ to_yield:
_yield_ to_yield + " "
_# If still too long, break at word boundaries only_
_elif_ len(buffer) > 150:
_# Find the last complete word before position 150_
words = buffer[:150].split()
_if_ len(words) > 1:
_# Take all but the last word (which might be incomplete)_
complete_words = words[:-1]
to_yield = " ".join(complete_words)
_# Keep the partial word and everything after in buffer_
remaining_start = len(to_yield) + (1 _if_ to_yield _else_ 0)
buffer = buffer[remaining_start:]
_if_ to_yield:
_yield_ to_yield + " "
_# Yield any remaining text in buffer_
_if_ buffer.strip():
_yield_ buffer.strip()
_return_ super().tts_node(process_with_word_boundary_preservation(), model_settings)
### Stage Direction Filtering (Potential Issue)
python
def filter_stage_directions(_text_: str) -> str:
_# First, handle double asterisks for emphasis: **word** -> ...word..._
text = re.sub(r'\*\*([^*]+)\*\*', r'...\1...', text)
_# Replace content within single asterisks with a space: *action*_
text = re.sub(r'(?<!\*)\*[^*]+\*(?!\*)', ' ', text)
_# Convert single periods at sentence ends to ellipses for slower pacing_
text = re.sub(r'\.(\s|$)', r'...\1', text)
_# Clean up extra whitespace_
text = re.sub(r'\s+', ' ', text)
_return_ text
## The Problem
### Choppy Audio Symptoms
- Stuttering speech in both Live Voice and PTT modes
- Audio artifacts at text chunk boundaries
- Unnatural pauses or breaks mid-sentence
- Inconsistent audio quality across different responses
### Suspected Causes
1. Text chunking boundaries creating audio artifacts
2. Stage direction filtering affecting speech flow
3. Ellipses conversion (periods to ...) disrupting TTS rhythm
4. Mobile audio handling with React Native WebRTC
5. Default Deepgram TTS configuration not optimized
## Questions
### 1. Text Chunking Best Practices
Our current approach chunks text at:
- Sentence boundaries (80+ chars)
- Clause boundaries (150+ chars)
- Word boundaries (as fallback)
Questions:
- Does chunking at these boundaries cause audio artifacts in Deepgram TTS?
- What's the recommended chunk size and boundary detection for smooth TTS?
- Should we avoid mid-sentence chunking entirely?
### 2. Deepgram TTS Configuration
Current configuration uses defaults:
python
tts=deepgram.TTS(_model_="aura-2-cora-en") _# Default settings_
Questions:
- Are there Deepgram TTS parameters to optimize for smooth audio?
- Audio encoding, sample rate, or buffer settings for better quality?
- Best practices for streaming TTS in real-time conversations?
### 3. Text Processing Impact
Our filtering and modifications:
- Stage direction removal: *sighs* → (spaces)
- Emphasis conversion: **word** → ...word...
- Period conversion: Hello. → Hello...
Questions:
- Do these text modifications affect TTS audio quality?
- Does excessive ellipses (...) cause choppy or unnatural speech?
- Should text preprocessing be minimized for smoother TTS?
### 4. Mobile Audio Considerations
Platform: React Native with @livekit/react-native
Audio path: Agent TTS → LiveKit → Mobile WebRTC → Device speakers
Questions:
- Are there mobile-specific audio configurations for smoother playback?
- WebRTC audio settings that could reduce choppiness?
- Buffer management or audio processing recommendations for React Native?
### 5. Agent Session Audio Configuration
Questions:
- Should we configure specific audio settings in AgentSession?
- Audio processing options to prevent artifacts?
- TTS streaming optimization for real-time conversations?
## Use Case Context
Mental health conversation app where:
- Audio quality critical for therapeutic experience
- Natural speech flow essential for user comfort
- Real-time conversations require smooth TTS
- Professional audio quality expected
## Environment Details
- TTS Provider: Deepgram aura-2 models
- Agent Platform: Python livekit-agents
- Client: React Native with @icy-policeman-64898/react-native
- Use Cases: Live Voice + PTT conversations
- Text Processing: Custom chunking and stage direction filtering
## Request
Could you provide guidance on:
1. Optimal text chunking strategies for Deepgram TTS
2. Deepgram TTS configuration parameters for smooth audio
3. Text preprocessing best practices (minimal vs extensive filtering)
4. Mobile audio optimization for React Native WebRTC
5. Agent session configuration for optimal TTS quality
Any specific recommendations for eliminating choppy audio artifacts would be greatly appreciated!tall-airline-16756
08/25/2025, 4:42 PMtall-airline-16756
08/25/2025, 4:47 PMmin_remaining_audio (around 3.0 seconds) and max_text_length (about 300 characters) to gently control how text flows into the TTS engine.
- Avoid chopping sentences in the middle to prevent those awkward pauses.
2. Deepgram TTS Configuration:
- Set your sample_rate to 24000 Hz and pick linear16 encoding for crisp, clear audio.
- Turn on text pacing to make the speech sound smoother by sending text in well-sized batches.
- You might want to try a model tailored for your needs, like aura-2-andromeda-en, for even better results.
3. Text Preprocessing Impact:
- Be careful with things like lots of ellipses ("...") or filtering out stage directions—they can mess with the TTS rhythm. Keep preprocessing to just the essentials.
- Using a TTS node override to handle preprocessing can help make sure these tweaks don’t cause any hiccups.
4. Mobile Audio Optimization:
- Before joining a room in React Native, configure your audio session with AudioSession.configureAudio().
- Use communication presets designed for voice calls, and on Android, enable hardware-based audio processing for the best experience.
- On iOS, the useIOSAudioManagement hook is your friend for smooth, dynamic audio handling.
5. Agent Session Configuration:
- Turn on use_tts_aligned_transcript to keep your transcripts nicely in sync.
- Use text pacing in your TTS config to cut down on interruptions and boost speech quality.
- Make sure your connection options can gracefully handle any TTS errors to keep things running reliably.
Give these a try, and you should see those choppy audio glitches fade away, making your TTS sound much better overall. If you want, I’m here to help with any specific examples or questions you have!
Sources: Live Conversations with AI using ChatGPT and WebRTC | examples/other/text-to-speech/sync_tts_transcription.py | Pipeline nodes and hooks | LiveKit Docs | Deepgram TTS integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt.pyjolly-eve-3916
08/26/2025, 6:48 AMtypescript
_// In livekit-token-generator.ts_
const dispatch = await dispatchClient.createDispatch(
roomName,
agentName,
{ metadata: JSON.stringify({ mode, threadId, patientId }) } _// Current working dispatch_
);
### Proposed Extension for Voice Identity
typescript
const dispatch_metadata = {
mode, threadId, patientId, _// Existing_
voice_name: "Gabriel", _// New: voice identity_
custom_instructions: "You are Gabriel, a supportive AI reflection guide..." _// New: dynamic instructions_
};
const dispatch = await dispatchClient.createDispatch(
roomName,
agentName,
{ metadata: JSON.stringify(dispatch_metadata) }
);
## Agent Access Question
### Current Agent Code
python
_# In agent entrypoint - we already access ctx.job successfully_
async def entrypoint(_ctx_: JobContext):
logger.info(f"Job ID: {ctx.job.id}") _# ← This works_
_# Proposed: Access dispatch metadata_
dispatch_config = json.loads(ctx.job.metadata) _if_ ctx.job.metadata _else_ {} _# ← Will this work?_
voice_name = dispatch_config.get('voice_name', 'Cora')
## Specific Questions
### 1. ctx.job.metadata Availability
Is ctx.job.metadata the correct way to access dispatch metadata?
- Does ctx.job.metadata contain the metadata passed to createDispatch()?
- Is this metadata available immediately when the agent entrypoint starts?
- Any difference between ctx.job.metadata and the dispatch metadata we send?
### 2. Metadata Structure
How is the dispatch metadata structured in ctx.job.metadata?
- Is it already JSON parsed or still a string requiring json.loads()?
- Does the metadata structure match what we send in createDispatch()?
- Any additional fields or wrapper objects to be aware of?
### 3. Error Handling
Best practices for accessing dispatch metadata safely:
python
_# Is this the right error handling pattern?_
_try_:
dispatch_config = json.loads(ctx.job.metadata) _if_ ctx.job.metadata _else_ {}
voice_name = dispatch_config.get('voice_name', 'Cora')
_except_ (json.JSONDecodeError, AttributeError) _as_ e:
logger.error(f"Error parsing dispatch metadata: {e}")
voice_name = 'Cora' _# Fallback_
### 4. Alternative Access Methods
Are there other ways to access dispatch configuration?
- Alternative APIs for dispatch metadata access?
- Different timing or access patterns we should consider?
- Any performance considerations for metadata access?
## Use Case Context
Mental health therapy app where:
- Voice identity must be consistent (Gabriel voice says "I'm Gabriel")
- 7 different voice personalities need dynamic configuration
- Dispatch metadata will contain voice_name and custom_instructions
- Reliable access to dispatch configuration essential
## Current Status
Working elements:
- ✅ Agent dispatch system working perfectly
- ✅ ctx.job.id access confirmed working
- ✅ Dispatch metadata creation in token generator
Need clarification:
- ❓ ctx.job.metadata structure and access pattern
- ❓ Metadata parsing and error handling best practices
## Request
Could you confirm:
1. Correct API for accessing dispatch metadata in agents
2. Metadata structure and parsing requirements
3. Best practices for safe metadata access and error handling
4. Any gotchas or considerations for dispatch metadata usage
This will help us complete our dynamic voice identity implementation using the proper LiveKit APIs!
Thank you for your excellent guidance so far!tall-airline-16756
08/26/2025, 6:49 AMcreateDispatch() and is ready to use as soon as your agent starts.
- Since it’s a freeform string, it’ll match exactly what you send during dispatch, as long as nothing else changes it.
2. Metadata Structure:
- The metadata comes as a string, so you’ll want to parse it (like with json.loads()) to get the structured data out.
- The structure you get matches what you send in createDispatch(), so just make sure you serialize it properly (JSON usually works great).
- LiveKit doesn’t add any extra wrappers or fields—what you send is what you get.
3. Error Handling Best Practices:
- It’s a good idea to safely parse your metadata to handle cases where it might be missing or not quite right:
try:
dispatch_config = json.loads(ctx.job.metadata) if ctx.job.metadata else {}
voice_name = dispatch_config.get('voice_name', 'Cora')
except (json.JSONDecodeError, AttributeError) as e:
logger.error(f"Error parsing dispatch metadata: {e}")
voice_name = 'Cora' # Fallback
- Using .get() with defaults helps avoid any key errors and keeps things smooth.
4. Alternative Access Methods:
- ctx.job.metadata is definitely your go-to for accessing dispatch metadata.
- Just make sure you include the metadata when you call createDispatch() via the metadata field.
- To keep things running fast, consider preloading all the data you need into the metadata—this way, your agent won’t have to make extra API calls right when it starts.
Hopefully, these tips make it easier for you to set up dynamic voice identities using dispatch metadata. If you want to chat more or need any clarification, just let me know—I’m here to help!
Sources: Dispatching agents | LiveKit Docs | Job lifecycle | LiveKit Docs | External data and RAG | LiveKit Docs | Job lifecycle | LiveKit Docs | livekit/livekit_agent.pb.go