polite-dog-12152
10/08/2025, 6:43 AMtall-airline-16756
10/08/2025, 6:44 AMtall-airline-16756
10/08/2025, 6:44 AMpolite-dog-12152
10/08/2025, 6:44 AMtall-airline-16756
10/08/2025, 6:45 AMvoicemail_detected() method.
• Validate Room and Participant Details: It's important to confirm that the room names and participant identities exactly match when you call the move_participant API.
• Enable Detailed Logging: Try setting the logging level to DEBUG so you can capture detailed error messages and stack traces for the merge_calls() method. This can give you more insight into what's happening.
• Check API Permissions: Please ensure that your API key has the necessary permissions (like room:admin or room:write) and that your LiveKit server version supports the move_participant endpoint.
• Test Media Compatibility: Verify that the supervisor and customer can connect and interact in the same room, especially if the supervisor is connecting via SIP.
• Isolate the Issue: It might help to test the move_participant API separately using a standalone script to make sure it works independently of the agent logic.
If you continue to face challenges, consider reviewing the server logs or enabling webhook notifications for real-time event tracking. Please feel free to reach out if you'd like any help walking through these steps—I’m here to support you!
Sources: livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | README.md | SIP troubleshooting guide | LiveKit Docs | Getting Help & Troubleshooting | livekit/livekit_composite | DeepWikipolite-dog-12152
10/13/2025, 3:09 AMtall-airline-16756
10/13/2025, 3:10 AMchat_ctx parameter to smoothly transfer conversation history between agents, which helps keep the conversation flowing naturally during handoffs.
• Truncate History: It’s a good idea to trim the chat history to just the most recent messages. This way, you save on token usage while still keeping the important context.
• Persist History: To maintain memory across sessions, you might want to store session.history externally in a database like PostgreSQL or Redis.
• Enhance Memory: For even richer memory features—like semantic recall or personalized interactions—consider integrating external tools such as Letta or LlamaIndex.
• Load History: Plugins like the OpenAI Realtime API can be really helpful to preload past conversation history into your session prompt.
If you’d like, I can provide a code example for any of these steps—whether it’s setting up database integration or handling context transfer between agents. Just let me know what would be most useful for you!
Sources: examples/voice_agents/restaurant_agent.py | complex-agents/medical_office_triage/triage.py | Workflows | LiveKit Docs | Sending text | LiveKit Docs | External data and RAG | LiveKit Docspolite-dog-12152
10/13/2025, 3:14 AMtall-airline-16756
10/13/2025, 3:15 AMUserData class to keep shared state, like previous agent context and any custom session data you want to hold onto.
• Implement a BaseAgent Class: This base class can manage the context transfer logic. It copies and truncates the previous agent’s chat_ctx so you keep the important parts of the conversation history.
• Truncate Context: It’s helpful to have a method that trims the context to just the most recent messages. This way, you save on token usage but don’t lose the key information.
• Enable Agent Transfers: Using function_tool decorators allows smooth control transfers between agents while keeping the context intact.
Here’s a friendly example showing how you might transfer context:
class BaseAgent(Agent):
async def on_enter(self):
userdata = self.session.userdata
chat_ctx = self.chat_ctx.copy()
if userdata.prev_agent:
truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
exclude_instructions=True,
exclude_function_call=False
).truncate(max_items=6)
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in truncated_chat_ctx.items if item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
await self.update_chat_ctx(chat_ctx)
If you'd like, I can also provide a full example with multiple agent classes or dive deeper into any particular step. Just let me know—I'm here to help!
Sources: pipeline-tts/tts_comparison/README.md | examples/voice_agents/restaurant_agent.py | Workflows | LiveKit Docs | Building Multi-Agent Architectures with LiveKit Agentspolite-dog-12152
10/15/2025, 4:56 AMtall-airline-16756
10/15/2025, 4:56 AMsync_transcription=True in RoomOutputOptions. This ensures words are forwarded exactly as they’re spoken, which is key for real-time display.
• Stream Transcriptions: On the frontend, subscribe to the lk.transcription topic. This way, you’ll receive each word incrementally and can show them right away.
• Use TTS-Aligned Transcription: If you’re working with Cartesia or ElevenLabs, enable use_tts_aligned_transcript=True to get precise word-level timing, making your transcription even more accurate.
• Access Timing Data: In your agent class, implement the transcription_node() method. This allows you to print each word along with its start and end times, giving you detailed insight.
Here’s a quick example to illustrate real-time word-by-word transcription:
async def transcription_node(self, text: str, start_time: float, end_time: float):
print(f"Word: '{text}', starts at {start_time:.2f}s, ends at {end_time:.2f}s")
If you’d like, I’m happy to provide a complete example tailored to your setup—whether that’s frontend integration or a Python backend implementation. Just let me know!
Sources: Text and transcriptions | LiveKit Docs | pipeline-stt/transcriber/README.md | livekit-agents/livekit/agents/voice/agent_activity.pypolite-dog-12152
10/15/2025, 6:27 AMtall-airline-16756
10/15/2025, 6:27 AMsync_transcription=True in RoomOutputOptions. This lets you forward words as they’re being spoken, so nothing gets missed.
• Stream Transcriptions: On your frontend, you can use useTrackTranscription or listen for the RoomEvent.TranscriptionReceived event. This way, you’ll receive transcription segments in real time and keep things flowing smoothly.
• Save Transcriptions: To keep a record, listen for the user_input_transcribed event on your backend or save the session.history once the session ends. This ensures you have the full transcript saved safely.
• Frontend Display: For showing the transcriptions nicely, components like TranscriptionTile can help merge and render both user and agent speech in a friendly chat-like interface.
If you’d like, I’d be happy to provide a detailed code example to guide you through saving transcriptions or integrating them into your frontend. Just let me know!
Sources: docs/index.yaml | Session recording and transcripts | LiveKit Docs | src/transcriptions/TranscriptionTile.tsx | Text and transcriptions | LiveKit Docs | web/src/hooks/use-agent.tsxpolite-dog-12152
10/15/2025, 6:46 AMtall-airline-16756
10/15/2025, 6:46 AMuse_realtime=True. Here’s a simple example:
stt = openai.STT(
model="gpt-4o-mini-transcribe",
use_realtime=True,
turn_detection={
"type": "server_vad",
"threshold": 0.5,
"prefix_padding_ms": 600,
"silence_duration_ms": 350,
}
)
• Enable TTS-Aligned Transcription: For more precise word-level timing, you can use use_tts_aligned_transcript=True with compatible TTS providers like Cartesia or ElevenLabs.
• Implement Transcription Node: Define a transcription_node method to handle the word-by-word transcriptions along with their timing. Here’s how you might do it:
async def transcription_node(self, text_stream: AsyncIterable[str | TimedString]):
async for text in text_stream:
if isinstance(text, TimedString):
print(f"Word: {text.text}, Start: {text.start_time}s, End: {text.end_time}s")
else:
print(f"Text chunk: {text}")
• Frontend Integration: To receive and display transcriptions in real time, subscribe to the lk.transcription topic. If you’re using React, the useTranscriptions hook is a great choice, or you can register a text stream handler like this:
room!.registerTextStreamHandler("lk.transcription", (stream) => {
stream.messages.forEach((msg) => {
console.log(`Transcription: ${msg.message}, Final: ${msg.attributes['lk.transcription_final']}`);
});
});
If you’d like, I’m here to help you with any part of the backend setup or frontend integration. Just let me know how I can assist!
Sources: livekit-plugins/livekit-plugins-fireworksai/livekit/plugins/fireworksai/stt... | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | Text and transcriptions | LiveKit Docspolite-dog-12152
10/15/2025, 8:40 AMtall-airline-16756
10/15/2025, 8:40 AMstart_time and end_time in seconds relative to the start of the agent's current turn. This is super helpful for synchronized transcription forwarding, allowing you to align at the word or sentence level depending on your TTS provider.
Here’s how you can access TimedString:
1. Enable TTS-Aligned Transcription: Simply set use_tts_aligned_transcript=True in your AgentSession configuration. For example:
session = AgentSession(
stt=deepgram.STT(),
llm=openai.LLM(),
tts=cartesia.TTS(),
use_tts_aligned_transcript=True,
)
1. Implement the transcription_node Method: You’ll want to override this method in your agent class to handle TimedString objects. Here’s a simple example:
async def transcription_node(
self, text: AsyncIterable[str | TimedString], model_settings: ModelSettings
) -> AsyncGenerator[str | TimedString, None]:
async for chunk in text:
if isinstance(chunk, TimedString):
print(f"TimedString: '{chunk.text}' ({chunk.start_time} - {chunk.end_time})")
yield chunk
Just a quick note: This feature is currently available only in the Python SDK and works with TTS providers like Cartesia and ElevenLabs. If you have any questions or need a hand with the implementation, please don’t hesitate to ask—I’m here to help!
Sources: Text and transcriptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.pypolite-dog-12152
10/15/2025, 9:09 AMtall-airline-16756
10/15/2025, 9:10 AMtts_node method in LiveKit to better process agent speech text and audio frames. You can tailor both the text before synthesis and the audio frames after synthesis. Here's a friendly guide to get you started:
• Pre-Process Text: You can modify the incoming text stream before it reaches the TTS engine. For instance, you might want to replace certain phrases or add SSML tags to enhance the speech:
`async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
async def process_text():
async for chunk in text:
modified = chunk.replace("lol", "").replace("OMG", "Oh my god!")
yield modified
return Agent.default.tts_node(self, process_text(), model_settings)async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
return self._process_audio_stream(Agent.default.tts_node(self, text, model_settings))
async def _process_audio_stream(self, audio_stream: AsyncIterable[rtc.AudioFrame]):
async for frame in audio_stream:
# Example: Adjust volume or apply effects
yield frame`If you'd like, I can provide a more detailed example tailored to your specific needs, whether that's adding cool effects or integrating external TTS APIs. Just let me know! Sources: Pipeline nodes and hooks | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | docs/index.yaml | plugins/resemble/src/tts.tspolite-dog-12152
10/16/2025, 5:53 AMtall-airline-16756
10/16/2025, 5:54 AMlk.transcription topic. By listening to this stream, you can receive both interim and final transcription segments as they happen.
• React Integration: If you’re working with React, the useTranscriptions hook from @livekit/components-react is a great tool to manage your transcription data smoothly.
• Manual Event Handling: Another option is to listen for the RoomEvent.TranscriptionReceived event via the livekit-client SDK. This event provides transcription segments along with timestamps and speaker identity, giving you rich context.
• Display Logic: To keep everything in order, sort transcriptions by firstReceivedTime. Also, make sure to replace interim text with the finalized versions to avoid any duplicates.
If you’d like, I can share a detailed code example for React or any other frontend framework you’re using. Just let me know!
Sources: complex-agents/turn-taking/README.md | web/src/components/transcript.tsx | Text and transcriptions | LiveKit Docs | client/web/src/components/captions.tsx | components/typewriter.tsxpolite-dog-12152
10/16/2025, 1:10 PMtall-airline-16756
10/16/2025, 1:11 PMRoomEvent.TranscriptionReceived event. This will bring in transcription segments that include the text, timestamps, and some handy metadata.
• Manage Transcription State: It’s a good idea to maintain a state object where you store these transcription segments. When you see segment.isFinal === true, replace any interim results with the final version to keep things accurate.
• Render Transcriptions: To make everything look neat, sort the segments by firstReceivedTime and then display them in your UI. If you want to add a little flair, consider animations like a typewriter effect—it really enhances the user experience!
• Use React Hooks: If you’re working with React, the useTranscriber hook is your friend. It simplifies event handling and managing state. Here’s a quick example:
const { state, transcriptions } = useTranscriber();
const text = Object.values(transcriptions)
.sort((a, b) => a.firstReceivedTime - b.firstReceivedTime)
.map(t => t.text.trim())
.join("\n");
• Optional: If you’d like to receive transcriptions as soon as they’re available without synchronization delays, you can set sync_transcription: false in RoomOutputOptions.
If you’d like, I’d be more than happy to provide a detailed code example tailored to your specific frontend framework or any particular feature you’re interested in. Just let me know!
Sources: Text and transcriptions | LiveKit Docs | hooks/use-transcriber.ts | complex-agents/note-taking-assistant/note-taker-frontend/components/medical...polite-dog-12152
10/16/2025, 1:12 PMtall-airline-16756
10/16/2025, 1:13 PMBuildSIPToken function to create a token with SIP-specific permissions. Here’s an example in Python:
from livekit.protocol.sip import BuildSIPToken
def generate_token(room_name, identity):
token = BuildSIPToken(
api_key="your-api-key",
api_secret="your-api-secret",
room_name=room_name,
participant_identity=identity
)
return token
1. Create a Backend Endpoint: Next, set up an API endpoint (for example, /api/generate-token) that generates and returns the token. Here’s how you might do it using Flask:
@app.route('/api/generate-token', methods=['POST'])
def generate_token_endpoint():
data = request.json
room_name = data.get("room_name")
identity = data.get("identity")
token = generate_token(room_name, identity)
return jsonify({"token": token})
1. Pass the Token to the Frontend: Finally, from your frontend, make an HTTP POST request to get the token and then use it to connect to the LiveKit room. Here’s a JavaScript example:
async function connectToRoom() {
const response = await fetch('/api/generate-token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
room_name: 'my-room',
identity: 'user-123'
})
});
const { token } = await response.json();
const room = new Room();
await room.connect('wss://your-livekit-instance', token);
}
If you’d like, I’m here to help you further with setting up the backend or integrating the frontend. Just let me know how I can assist you!
Sources: rpc/sip.pb.go | ivr-nagivator/flask_livekit/extension.py | Core Platform Architecture & Authentication | livekit/livekit_composite | D... | SIP Integration & Telephony | livekit/livekit_composite | DeepWikipolite-dog-12152
10/16/2025, 1:17 PMtall-airline-16756
10/16/2025, 1:18 PMconst room = new Room();
await room.connect('wss://your-livekit-instance', token);
1. Listen for Transcription Events: After connecting, listen for the RoomEvent.TranscriptionReceived event to catch those transcription segments as they come in. Here's how you can do that:
room.on(RoomEvent.TranscriptionReceived, (segments) => {
// Handle transcription segments
});
1. Render Transcriptions: Once you have the transcription segments, you can display the text in your UI. If you're using React, the useTranscriber hook is a great tool for this:
const { state, transcriptions } = useTranscriber();
const text = Object.values(transcriptions)
.sort((a, b) => a.firstReceivedTime - b.firstReceivedTime)
.map(t => t.text.trim())
.join("\n");
If you'd like, I can provide a detailed example to help you integrate this smoothly into your frontend application. Just let me know!
Sources: app/page.tsx | hooks/use-transcriber.ts | complex-agents/note-taking-assistant/agent.py | client/web/src/components/captions.tsx | Text and transcriptions | LiveKit Docspolite-dog-12152
10/16/2025, 1:37 PMtall-airline-16756
10/16/2025, 1:38 PMon_interim_transcript Event: This event triggers whenever the STT engine provides partial results. Here’s an example:
def on_interim_transcript(self, ev: stt.SpeechEvent, *, speaking: bool | None):
transcript = ev.alternatives[0].text
if transcript:
with open("transcript_interim.txt", "a") as f:
f.write(f"[Interim] {transcript}\n")
1. Listen to user_input_transcribed Events: You can capture partial input by checking is_final=False. Here’s how:
@session.event
async def on_user_input_transcribed(event: UserInputTranscribedEvent):
if not event.is_final:
with open("live_transcription.txt", "a") as f:
f.write(f"Partial: {event.transcript}\n")
1. Override `transcription_node`: This lets you access the transcription stream directly for real-time processing:
async def transcription_node(self, text_stream: AsyncIterable[str]):
async for text in text_stream:
with open("transcript_log.txt", "a") as f:
f.write(f"{text}\n")
These approaches make it easy to save transcription data bit by bit as the user speaks. If you have any questions or need a hand with the implementation, please don’t hesitate to ask—I’m here to help!
Sources: How to capture real-time agent transcriptions during conversations | Session recording and transcripts | LiveKit Docs | livekit-plugins/livekit-plugins-assemblyai/livekit/plugins/assemblyai/stt.p... | Pipeline nodes and hooks | LiveKit Docs | Text and transcriptions | LiveKit Docspolite-dog-12152
10/17/2025, 5:40 AMtall-airline-16756
10/17/2025, 5:42 AMdef generate_token(room_name, identity):
token = api.AccessToken() \
.with_identity(identity) \
.with_grants(api.VideoGrants(room_join=True, room=room_name)) \
.to_jwt()
return token
1. Connect to the Room: Next, on the frontend, you can use this token to connect to the room like so:
const room = new Room();
await room.connect('wss://your-livekit-instance', token);
1. Fetch Transcriptions: To receive transcription segments, listen for the RoomEvent.TranscriptionReceived event. Here’s how you might do that:
room.on(RoomEvent.TranscriptionReceived, (segments) => {
segments.forEach(segment => {
console.log(`Transcription: ${segment.text}`);
});
});
1. Display Transcriptions: Finally, you can display these transcriptions in real time using a React component like TranscriptionView, or feel free to build a custom UI that fits your needs.
If you’d like, I’m happy to provide a more detailed example for either backend token generation or frontend transcription display—just let me know what would be most helpful for you!
Sources: main.py | livekit-rtc/livekit/rtc/room.py | SIP APIs | LiveKit Docs | Voice Assistant Applications | livekit/livekit_composite | DeepWiki | complex-agents/ivr-agent/flask_livekit/extension.pypolite-dog-12152
10/17/2025, 5:54 AMtall-airline-16756
10/17/2025, 5:54 AMfrom flask import Flask, request, jsonify
from livekit import AccessToken, VideoGrant
app = Flask(__name__)
@app.route('/api/generate-token', methods=['POST'])
def generate_token():
data = request.json
room_name = data.get("room_name")
identity = data.get("identity")
if not room_name or not identity:
return jsonify({"error": "Missing room_name or identity"}), 400
token = AccessToken("your-api-key", "your-api-secret")
token.identity = identity
token.add_grant(VideoGrant(room=room_name))
return jsonify({"token": token.to_jwt()})
Frontend: Connect to Room and Fetch Transcriptions
import { Room, RoomEvent } from 'livekit-client';
async function connectToRoom(roomName, identity) {
// First, we fetch the token from your backend
const response = await fetch('/api/generate-token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room_name: roomName, identity: identity })
});
const { token } = await response.json();
// Now, connect to the LiveKit room
const room = new Room();
await room.connect('wss://your-livekit-instance', token);
// Listen for transcription events and handle them here
room.on(RoomEvent.TranscriptionReceived, (segments) => {
segments.forEach(segment => {
console.log(`Transcription: ${segment.text}`);
});
});
console.log('Connected to room:', roomName);
}
Usage
// Just call this function with your room name and participant identity
connectToRoom('sip-room-name', 'sip-participant-identity');
This example walks you through generating a token on the backend, connecting to a SIP room on the frontend, and fetching transcriptions in real time. If you have any questions or need a hand with anything else, feel free to ask—I’m here to help!polite-dog-12152
10/17/2025, 6:48 AMtall-airline-16756
10/17/2025, 6:50 AMconversation_item_added event! Just a little heads-up though, this event gives you the finalized content only, not the real-time streaming updates. It gets triggered whenever a conversation item (like a message from the user or agent) is saved to the chat history. Here’s a quick example to illustrate:
@session.on("conversation_item_added")
def on_conversation_item(event):
if hasattr(event, 'item') and event.item.content:
speaker = "USER" if getattr(event.item, 'role', '') == 'user' else "AGENT"
print(f"{speaker}: {event.item.content}")
If you’re looking for real-time streaming transcription, you might want to explore the user_input_transcribed event or try overriding the transcription_node method. These options give you those interim transcription updates as the user is speaking. I’m happy to share some examples for these if you’d like—just let me know!
Sources: Events and error handling | LiveKit Docs | Text and transcriptions | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | Session recording and transcripts | LiveKit Docs | How to capture real-time agent transcriptions during conversationspolite-dog-12152
10/17/2025, 6:51 AMtall-airline-16756
10/17/2025, 6:51 AMuser_input_transcribed Event
This event gives you real-time transcription updates, including those interim results. Here's a simple example:
@session.on("user_input_transcribed")
def on_user_input_transcribed(event):
if not event.is_final:
print(f"Interim transcription: {event.transcript}")
else:
print(f"Final transcription: {event.transcript}")
2. Overriding the transcription_node Method
This method lets you handle transcription streams directly. Take a look at this example:
async def transcription_node(self, text_stream: AsyncIterable[str]):
async for text in text_stream:
print(f"Streaming transcription: {text}")
3. Using the llm_node for Real-Time Text
If you’re working with an LLM pipeline, you can get real-time text output through the llm_node. Here’s how:
async def llm_node(self, text_stream: AsyncIterable[str]):
async for text in text_stream:
print(f"LLM output: {text}")
These approaches are great for getting immediate transcription updates, perfect for applications that need quick feedback. If you have any questions or want me to walk you through more examples, just let me know—I’m here to help!polite-dog-12152
10/17/2025, 7:03 AMtall-airline-16756
10/17/2025, 7:05 AMredis:
address: localhost:6379
username: redis_username
password: redis_password
db: 0
This setup helps LiveKit use Redis for managing distributed state smoothly.
2. Store Transcriptions in Redis
You can use Redis to save transcription data in real time. Here's a simple example:
import redis
import json
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
def store_transcription(room_name, participant_id, transcript):
key = f"transcriptions:{room_name}"
redis_client.hset(key, participant_id, json.dumps(transcript))
3. Capture Transcription Events
To keep everything up to date, listen for transcription events and save them to Redis like this:
@session.on("user_input_transcribed")
def on_transcription(event):
store_transcription(event.room_name, event.participant_id, event.transcript)
4. Persist Session Data
For session data, including transcriptions, you can store them with an expiry time to manage storage efficiently:
def store_session_data(session_id, data):
redis_client.setex(f"session:{session_id}", 3600, json.dumps(data))
If you'd like, I’m here to help you further with setting up Redis or tailoring this to your specific needs. Just let me know!
Sources: Distributed Setup | LiveKit Docs | README.md | Core Platform Architecture & Authentication | livekit/livekit_composite | D... | Session recording and transcripts | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit Docspolite-dog-12152
10/17/2025, 8:01 AMtall-airline-16756
10/17/2025, 8:03 AMredis:
address: localhost:6379
username: redis_username
password: redis_password
db: 0
This configuration helps LiveKit use Redis for distributed state management smoothly.
2. Store Transcriptions in Redis
import redis
import json
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
def store_transcription(room_name, participant_id, transcript):
key = f"transcriptions:{room_name}"
redis_client.hset(key, participant_id, json.dumps(transcript))
3. Capture Transcription Events
To keep everything in sync, listen for transcription events and save them to Redis like this:
@session.on("user_input_transcribed")
def on_transcription(event):
store_transcription(event.room_name, event.participant_id, event.transcript)
4. Persist Session Data
You can store session data, including transcriptions, with an expiry to manage storage efficiently:
def store_session_data(session_id, data):
redis_client.setex(f"session:{session_id}", 3600, json.dumps(data))
5. Use Redis for Agent Dispatch and Jobs
LiveKit leverages Redis for agent dispatch and job storage. Here's a handy example:
def store_agent_job(room_name, job_id, job_data):
key = f"agent_jobs:{room_name}"
redis_client.hset(key, job_id, json.dumps(job_data))
6. Access Session History
To retrieve the full conversation history and save it to Redis, use session.history like this:
def save_session_history(session_id, history):
redis_client.set(f"session_history:{session_id}", json.dumps(history))
If you'd like, I’m here to help with any specific Redis patterns or LiveKit agent configurations you want to explore further. Just let me know!
Sources: Self-hosting the Ingress Service | LiveKit Docs | Distributed Setup | LiveKit Docs | pkg/service/redisstore_test.go | examples/other/transcription/README.md | Session recording and transcripts | LiveKit Docspolite-dog-12152
10/28/2025, 6:52 AMtall-airline-16756
10/28/2025, 6:53 AMcaching="ephemeral" in your LLM configuration. This helps optimize resource usage by caching the system prompt, tools, and chat history. Here’s a simple example:
llm = AnthropicLLM(api_key="your-api-key", caching="ephemeral")
2. For LiveKit with llama.cpp:
Great news—prompt caching is enabled by default using the cache_prompt parameter. It works by reusing previously computed tokens when prompts share common prefixes. Here’s how you can set it up:
llm = LlamaCppLLM(cache_prompt=True)
3. Advanced Caching Features:
• Cache Reuse: This matches common prefixes to reuse tokens efficiently.
• Slot-based Cache Management: Allows you to save and restore cache states across sessions.
• Chunk Reuse: Helps efficiently reuse attention states for handling larger prompts.
4. For Transcription Workflows:
Although there isn’t detailed caching specifically for transcription, you can use initial prompts with STT models like Azure OpenAI to help guide the transcription process. I’d recommend checking your STT provider’s documentation to see if they support caching.
If you’d like, I’m here to help you with implementing prompt caching tailored to your specific use case—just let me know!
Sources: livekit-plugins/livekit-plugins-anthropic/livekit/plugins/anthropic/llm.py | tools/server/public_simplechat/readme.mdpolite-dog-12152
10/28/2025, 7:10 AMtall-airline-16756
10/28/2025, 7:10 AMstt = deepgram.STT(
model="nova-2",
language="multi" # Enables automatic language detection
)
By setting language="multi", Deepgram will detect the spoken language and include that context in the transcriptions, which is super helpful!
2. Pass Detected Language to Downstream Processes
Once you have the detected language, you can easily update your TTS and STT components dynamically like this:
# Update both STT and TTS with the detected language
tts.update_options(language="es") # Update TTS to Spanish
stt.update_options(language="es") # Update STT to Spanish
3. Implement a Custom SpeechBrain STT Plugin
Even though LiveKit doesn’t directly support SpeechBrain out of the box, you can create a custom STT plugin by:
• Inheriting from stt.STT
• Implementing the _recognize_impl method to handle language detection
• Providing a stream() method for real-time transcription
This approach offers great flexibility if you want to tailor things to your needs.
4. Use Multilingual Turn Detection
LiveKit also supports multilingual turn detection, which is perfect for conversations with mixed languages. Here's a quick setup example:
from livekit.plugins.turn_detector.multilingual import MultilingualModel
session = AgentSession(
stt=deepgram.STT(model="nova-3", language="multi"),
turn_detection=MultilingualModel(),
)
If you'd like, I’m here to help you dive deeper into implementing a custom STT plugin or configuring Deepgram for language detection. Just let me know how I can support you further!
Sources: LiveKit turn detector plugin | LiveKit Docs | pipeline-tts/changing_language/README.md | Building the all-in-one platform for voice AI agents | Building the all-in-one platform for voice AI agents | Building the all-in-one platform for voice AI agentspolite-dog-12152
10/28/2025, 7:53 AMtall-airline-16756
10/28/2025, 7:53 AMupdate_options() method provided by the plugins. Let me walk you through it:
1. Update STT Settings
You can easily change STT parameters like language or model on the fly. Here’s an example:
stt.update_options(languages=["ja", "en"], translation_enabled=True, translation_target_languages=["fr"])
2. Update TTS Settings
Similarly, you can adjust TTS settings such as voice, language, speed, or volume dynamically. For instance:
tts.update_options(voice="Spanish_Narrator", language="es", speed=1.2, vol=1.0)
3. Real-Time Language Switching
If you want to synchronize STT and TTS for multilingual conversations, just update both like this:
# Update both TTS and STT when switching languages
tts.update_options(language="es")
stt.update_options(language="es")
4. Use Cases
• Voice Switching: Easily change TTS voice on the go.
• Language Adaptation: Switch STT and TTS languages based on what the user needs.
• Context-Aware Adjustments: Tweak speed or pitch for better clarity.
These updates happen seamlessly during your sessions without interrupting the conversation. If you’d like, I’m here to help you with any part of the implementation—just let me know!
Sources: livekit-plugins/livekit-plugins-minimax/livekit/plugins/minimax/tts.py | Gladia STT plugin guide | LiveKit Docs | pipeline-tts/tts_comparison/README.md | Models | LiveKit Docs | Introducing LiveKit Inference: A unified model interface for voice AIpolite-dog-12152
10/31/2025, 10:06 AMtall-airline-16756
10/31/2025, 10:07 AMstt.STT or tts.TTS). Let me walk you through how to do this:
1. Custom STT Implementation
Start by creating a class that inherits from stt.STT and implement the necessary methods:
from livekit.agents import stt
class CustomSTT(stt.STT):
def __init__(self, api_key: str, model_url: str):
super().__init__(capabilities=stt.STTCapabilities(streaming=True, interim_results=True))
self._api_key = api_key
self._model_url = model_url
def stream(self, *, language: str = None, conn_options=None):
return CustomSpeechStream(stt=self, opts={}, conn_options=conn_options)
You'll want to define a CustomSpeechStream class that manages real-time audio processing and emits transcription events. This helps keep everything running smoothly.
2. Custom TTS Implementation
Next, create a class that inherits from tts.TTS and implement the synth method like this:
from livekit.agents import tts
class CustomTTS(tts.TTS):
def __init__(self, voice_id: str, api_endpoint: str, api_key: str):
super().__init__(capabilities=tts.TTSCapabilities(sampling_rate=24000, channels=1))
self._voice_id = voice_id
self._endpoint = api_endpoint
self._api_key = api_key
async def synth(self, text: str):
audio_data = await self._call_tts_api(text)
yield SynthesizedAudio(text=text, data=audio_data)
3. Integrate with AgentSession
Once your custom STT and TTS classes are ready, you can easily pass their instances into the AgentSession like this:
session = AgentSession(
stt=CustomSTT(api_key="your-key", model_url="https://your-stt-api"),
tts=CustomTTS(voice_id="custom-voice", api_endpoint="https://your-tts-api"),
llm=OpenAI(),
)
4. Key Notes
• By using custom implementations, you get full control and bypass all built-in plugins, which is great for tailoring the experience exactly how you want.
• Make sure your custom STT and TTS handle real-time audio and text processing properly, and emit the necessary events like SpeechEvent or SynthesizedAudio so everything integrates seamlessly.
If you'd like, I’m here to help you with implementing a specific custom model or integrating a particular API. Just let me know how I can support you!
Sources: livekit-plugins/livekit-plugins-speechmatics/livekit/plugins/speechmatics/s... | Text-to-speech (TTS) models | LiveKit Docspolite-dog-12152
10/31/2025, 10:10 AMtall-airline-16756
10/31/2025, 10:11 AMfrom livekit.agents import stt
from livekit.agents.utils import AudioBuffer
class CustomSTT(stt.STT):
def __init__(self, api_key: str, model_url: str):
super().__init__(capabilities=stt.STTCapabilities(streaming=True, interim_results=True))
self._api_key = api_key
self._model_url = model_url
def stream(self, *, language: str = None, conn_options=None):
return CustomSpeechStream(self._api_key, self._model_url, language)
class CustomSpeechStream(stt.SpeechStream):
def __init__(self, api_key, model_url, language):
self.api_key = api_key
self.model_url = model_url
self.language = language
self.audio_buffer = AudioBuffer()
async def push_audio(self, frame):
self.audio_buffer.add_frame(frame)
# Here, you’d send audio to your custom STT API and get the transcription
transcription = await self._call_stt_api()
if transcription:
yield stt.SpeechEvent(transcript=transcription, is_final=False)
async def _call_stt_api(self):
# Just an example of calling your custom STT API
audio_data = self.audio_buffer.get_audio()
response = await some_http_library.post(self.model_url, data=audio_data, headers={"Authorization": f"Bearer {self.api_key}"})
return response.json().get("transcription")
Custom TTS Implementation
from livekit.agents import tts
class CustomTTS(tts.TTS):
def __init__(self, voice_id: str, api_endpoint: str, api_key: str):
super().__init__(capabilities=tts.TTSCapabilities(sampling_rate=24000, channels=1))
self._voice_id = voice_id
self._endpoint = api_endpoint
self._api_key = api_key
async def synth(self, text: str):
# This is where you call your custom TTS API
response = await some_http_library.post(self._endpoint, json={"text": text, "voice": self._voice_id}, headers={"Authorization": f"Bearer {self._api_key}"})
audio_data = response.content
yield tts.SynthesizedAudio(text=text, data=audio_data)
Integrate with AgentSession
session = AgentSession(
stt=CustomSTT(api_key="your-stt-api-key", model_url="https://your-stt-api"),
tts=CustomTTS(voice_id="custom-voice", api_endpoint="https://your-tts-api", api_key="your-tts-api-key"),
llm=OpenAI(),
)
This example aims to show you how to create your own STT and TTS implementations and seamlessly integrate them into a LiveKit agent session. If you have any questions or would like me to clarify anything or provide more examples, please don’t hesitate to ask—I’m here to help!polite-dog-12152
11/03/2025, 11:40 AMtall-airline-16756
11/03/2025, 11:41 AMstt_node method in LiveKit for postprocessing transcription events! You can do this by overriding the method in a custom Agent subclass. Here’s a friendly example to get you started:
Example: Keyword Detection in Transcription Events
from livekit.agents import Agent
from livekit.plugins import deepgram, openai, silero
import logging
logger = logging.getLogger("keyword-detection")
class KeywordDetectionAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful assistant.",
stt=deepgram.STT(),
llm=openai.LLM(),
tts=openai.TTS(),
vad=silero.VAD.load(),
)
async def stt_node(self, audio, model_settings):
# Get the parent transcription stream
stream = super().stt_node(audio, model_settings)
async def process_stream():
async for event in stream:
if event.type == SpeechEventType.FINAL_TRANSCRIPT and event.alternatives:
transcript = event.alternatives[0].text.lower()
keywords = ["hello", "thanks", "bye"]
for keyword in keywords:
if keyword in transcript:
logger.info(f"Keyword detected: '{keyword}'")
yield event
return process_stream()
Example: Diarization with Speaker Labeling
class DiarizationAgent(Agent):
async def stt_node(self, audio, model_settings):
stream = super().stt_node(audio, model_settings)
self.speaker_names = getattr(self, "speaker_names", {})
async def process_stream():
async for event in stream:
if event.type == SpeechEventType.FINAL_TRANSCRIPT and event.alternatives:
alternative = event.alternatives[0]
speaker_id = getattr(alternative, "speaker_id", None)
if speaker_id:
name = self.speaker_names.get(speaker_id, speaker_id)
alternative.text = f"{name}: {alternative.text}"
yield event
return process_stream()
These examples show you how to add your own special touch, like keyword detection or speaker labeling, all while keeping the original transcription stream intact. If you have any questions or want to explore this further, please don’t hesitate to ask—I’m here to help!
Sources: Pipeline nodes and hooks | LiveKit docs | pipeline-stt/keyword-detection/README.md | Text and transcriptions | LiveKit docspolite-dog-12152
11/15/2025, 5:14 AMtall-airline-16756
11/15/2025, 5:15 AMchat_ctx parameter to transfer or merge conversation history smoothly. Here’s a friendly guide to get you started:
1. Basic Context Transfer
When you create a new agent, simply pass the previous agent’s chat_ctx to keep the conversation history intact:
return TechnicalSupportAgent(chat_ctx=self.session.chat_ctx)
2. Advanced Context Copying and Truncation
To avoid going over token limits, you can copy and truncate the previous context like this:
truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
exclude_instructions=True,
exclude_function_call=False
).truncate(max_items=6)
3. Merging Contexts
When merging contexts, it’s helpful to avoid duplicate messages by checking existing IDs:
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in truncated_chat_ctx.items if item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
4. Use a BaseAgent Pattern
You might find it easier to create a base class that automatically handles context preservation for you:
class BaseAgent(Agent):
async def on_enter(self):
userdata = self.session.userdata
chat_ctx = self.chat_ctx.copy()
if userdata.prev_agent:
truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
exclude_instructions=True,
exclude_function_call=False
).truncate(max_items=6)
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in truncated_chat_ctx.items if item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
await self.update_chat_ctx(chat_ctx)
5. External Context Management
If you’re looking for even more advanced memory retention, integrating external tools like Letta or LlamaIndex can be a great option to maintain context across sessions.
If you’d like, I’m here to help you further with implementing context transfer or exploring those external tools. Just let me know!
Sources: Agent-assisted warm transfer | LiveKit docs | External data and RAG | LiveKit Docs | Workflows | LiveKit docs | examples/voice_agents/README.md | agents/src/llm/chat_context.tspolite-dog-12152
11/15/2025, 9:22 AMtall-airline-16756
11/15/2025, 9:22 AMdocker-compose.yaml file to define your services like this:
services:
redis:
image: redis
volumes:
- redis_data:/data
ports:
- 6379:6379
livekit:
image: livekit/livekit-server
command: --dev --redis-host localhost:6379
network_mode: host
depends_on:
redis:
condition: service_started
sip:
image: livekit/sip
network_mode: host
environment:
SIP_CONFIG_BODY: |
api_key: 'devkey'
api_secret: 'secret'
ws_url: 'ws://localhost:7880'
redis:
address: 'localhost:6379'
sip_port: 5060
rtp_port: 10000-20000
use_external_ip: true
logging:
level: debug
volumes:
redis_data:
2. Configuration Details
• The SIP service connects to the LiveKit server via WebSocket (ws_url), ensuring smooth communication.
• Both services share the same Redis instance to keep everything in sync seamlessly.
• We use host network mode (network_mode: host) for SIP (port 5060) and RTP (ports 10000–20000) so the networking works correctly.
3. Run with Docker Compose
docker-compose up
4. Alternative: Run with docker run
docker run --rm \
-e SIP_CONFIG_BODY="`cat config.yaml`" \
--network host \
livekit/sip
5. Post-Deployment Setup
• Don’t forget to configure your SIP Trunks and Dispatch Rules using the LiveKit CLI or SDKs to tailor everything to your needs.
• Also, make sure UDP traffic is allowed on ports 5060 (SIP) and 10000–20000 (RTP) for smooth operation.
If you'd like, I’m here to help you further with SIP trunk configuration or explore more advanced deployment options. Just let me know!
Sources: README.md | aws-ecs/README.mdpolite-dog-12152
11/15/2025, 9:24 AMtall-airline-16756
11/15/2025, 9:25 AMghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim. Just swap out ${PYTHON_VERSION} for the Python version you want to use (for example, 3.13).
2. Set Environment Variables and Non-Root User
It’s a good idea to set PYTHONUNBUFFERED=1 to keep your logs flowing smoothly without buffering. Also, for security, create a non-privileged user like this:
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/app" \
--shell "/sbin/nologin" \
--uid "${UID}" \
appuser
3. Install Build Dependencies
Next, you’ll want to install the system packages needed to build Python extensions:
RUN apt-get update && apt-get install -y gcc g++ python3-dev \
&& rm -rf /var/lib/apt/lists/*
4. Install Dependencies with UV
For a smooth build process, copy your pyproject.toml and uv.lock files first to take advantage of layer caching, then install your dependencies:
COPY pyproject.toml uv.lock ./
RUN uv sync --locked
5. Pre-download ML Models or Assets
To make sure everything’s ready to go, run a command that pre-fetches any necessary models or assets:
RUN uv run "agent.py" download-files
6. Define Startup Command
Finally, set the container’s entrypoint so your agent starts up automatically:
CMD ["uv", "run", "agent.py", "start"]
Here’s an example Dockerfile putting it all together:
ARG PYTHON_VERSION=3.13
FROM ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim AS base
ENV PYTHONUNBUFFERED=1
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/app" \
--shell "/sbin/nologin" \
--uid "${UID}" \
appuser
RUN apt-get update && apt-get install -y gcc g++ python3-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --locked
COPY . .
RUN chown -R appuser:appuser /app
USER appuser
RUN uv run "agent.py" download-files
CMD ["uv", "run", "agent.py", "start"]
If you’d like, I’m here to help with any part of your Docker deployment or LiveKit configuration. Just let me know how I can support you!
Sources: Builds and Dockerfiles | LiveKit Docs | pkg/agentfs/docker_test.go | complex-agents/exa-deep-researcher/uv.lock | Agent Deployment & Docker | livekit/livekit_composite | DeepWiki | Build Systems & Toolchains | livekit/livekit_composite | DeepWikipolite-dog-12152
11/16/2025, 6:00 AMtall-airline-16756
11/16/2025, 6:01 AMAgent level as a string parameter.
• They provide high-level behavioral guidelines or act as a system prompt for the agent.
• For example: instructions="You are a friendly voice assistant built by LiveKit."
Session Instructions:
• Actually, there isn’t a separate concept called "session instructions."
• The AgentSession simply uses the agent’s instructions to guide real-time execution.
• It manages operational tasks like STT, TTS, and LLM interactions throughout the session.
Dynamic Updates:
Here’s something neat—you can update the agent’s instructions on the fly during a live session using update_instructions(). This means the agent’s behavior adapts instantly without needing to restart the session.
If you’d like, I’d be happy to walk you through an example of how to update instructions dynamically during a session. Just let me know!
Sources: Agent Session Management & Turn Detection | livekit/livekit_composite | Dee... | agent/main.py | livekit-agents/livekit/agents/voice/agent_activity.py | .cursor/rules/agent-core.mdcpolite-dog-12152
11/18/2025, 6:25 AMtall-airline-16756
11/18/2025, 6:25 AMvalues.yaml file, you’ll want to specify the load balancer type like this:
loadBalancer:
type: alb # Options: alb (AWS), gke, do (Digital Ocean), etc.
2. Configure TLS and Hostnames
Next, define your domain(s) and SSL certificates to keep things secure:
loadBalancer:
type: alb
tls:
- hosts:
- livekit.myhost.com
3. Enable TURN with Load Balancer
To improve connectivity, it’s a great idea to enable TURN by adding:
turn:
enabled: true
domain: turn.myhost.com
tls_port: 3478
udp_port: 443
secretName: livekit-tls-secret
serviceType: LoadBalancer
4. Deploy via Helm
Once your values.yaml is all set, you can deploy LiveKit using Helm like this:
helm install livekit livekit/livekit-server -f values.yaml
5. Open Required Ports
Make sure these ports are open so everything runs smoothly:
• WebRTC UDP: 50000-60000
• WebRTC TCP: 7881
• TURN/UDP: 443
• TURN/TLS: 3478
6. Verify Load Balancer Address
To find your load balancer’s address, you can use this command:
kubectl get service <livekit-service-name> --namespace <namespace>
Don’t forget to update your DNS records to point to this address.
7. Multi-Region Routing (Optional)
If you’re aiming for a global reach, consider using a geo-aware DNS service like AWS Route53 to direct users to the closest region.
If you’d like, I’m here to help you with any part of the Helm configuration or DNS setup. Just let me know!
Sources: Deploy to Kubernetes | LiveKit docs | examples/server-eks.yaml | Distributed Setup | LiveKit docs | docs/tutorials/aws-sd.mdpolite-dog-12152
11/18/2025, 6:29 AMtall-airline-16756
11/18/2025, 6:30 AMhelm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm repo update
helm install nginx-ingress ingress-nginx/ingress-nginx --set controller.publishService.enabled=true
2. Configure LiveKit Load Balancer
Next, in your LiveKit Helm values.yaml, make sure to disable the built-in load balancer when using NGINX:
loadBalancer:
type: disable
3. Open Required Ports
To ensure everything runs smoothly, please confirm that the following ports are open:
• WebRTC UDP: 50000-60000
• WebRTC TCP: 7881
• TURN/UDP: 443
• TURN/TLS: 3478
4. Configure SSL Certificates
For automatic SSL certificate management, you'll want to install Cert Manager. Here’s how:
kubectl create namespace cert-manager
helm repo add jetstack https://charts.jetstack.io
helm repo update
helm install cert-manager jetstack/cert-manager --namespace cert-manager --version v1.8.0 --set installCRDs=true
Then, create a ClusterIssuer for Let’s Encrypt with this configuration:
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
email: <your-email-address>
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: letsencrypt-prod-private-key
solvers:
- http01:
ingress:
class: nginx
5. Configure TURN Service
To enable TURN in your LiveKit setup, update your configuration like this:
livekit:
turn:
enabled: true
domain: turn.myhost.com
tls_port: 3478
udp_port: 443
secretName: livekit-tls-secret
6. Deploy LiveKit with Helm
Once everything is set, you can install LiveKit using your configured values:
helm install livekit livekit/livekit-server --namespace <namespace> --values values.yaml
7. Verify Deployment
Finally, check the ingress status and DNS resolution to ensure your setup is working:
kubectl get ingress --namespace <namespace>
If you have any questions or need a hand with the NGINX configuration or troubleshooting, please don’t hesitate to ask. I’m here to support you every step of the way!
Sources: Deploy to Kubernetes | LiveKit docs | docs/tutorials/gke-nginx.md | ingress-sample.yamlpolite-dog-12152
11/18/2025, 6:54 AMtall-airline-16756
11/18/2025, 6:55 AMuse_realtime=True to activate streaming with interim results.
• For Speechmatics, make sure enable_partials=True is set (it’s enabled by default) so you receive those helpful interim transcription events.
2. Backend Processing
Partial transcriptions come through as SpeechEvent with the type SpeechEventType.INTERIM_TRANSCRIPT. You can easily forward these events to the frontend or use them within your agent's logic—whichever works best for you.
3. Frontend Rendering
• Use registerTextStreamHandler to listen to the transcription streams.
• Keep an eye on the lk.transcription_final field to tell interim and final transcriptions apart, and swap out the interim text with the final one when it arrives.
4. Example Flow
1. The user starts speaking → the agent streams audio to the STT engine.
2. The STT engine sends partial transcriptions periodically (like every 0.5 seconds).
3. The agent forwards these interim results to the frontend.
4. Once the speech ends, a final transcription is sent, replacing the interim text.
If you'd like, I’m here to help you dive deeper into either backend or frontend implementation—just let me know!
Sources: Text and transcriptions | LiveKit docs | lib/src/core/room.dart | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/stt.pypolite-dog-12152
11/18/2025, 7:00 AMtall-airline-16756
11/18/2025, 7:01 AMSTT(
enable_partials=True, # Enabled by default
max_delay=0.7, # Controls processing delay (lower = faster but potentially less accurate)
)
2. Use Preemptive Generation
Next, enable preemptive response generation. This means the system begins processing user input before the full utterance is finished, helping to overlap response generation with speech and reduce overall latency.
3. Access Partial Input in Real Time
You can use the onInterimTranscript hook to handle partial input right away, like this:
const recognitionHooks: RecognitionHooks = {
onInterimTranscript: (ev: SpeechEvent) => {
console.log("Partial transcript:", ev.alternatives[0].text);
},
onFinalTranscript: (ev: SpeechEvent) => {
console.log("Final transcript:", ev.alternatives[0].text);
},
onPreemptiveGeneration: (info: PreemptiveGenerationInfo) => {
console.log("Starting preemptive response for:", info.newTranscript);
},
};
These handy features let you respond to partial input immediately while still preparing for the final, confirmed user input. If you have any questions or want some help with the implementation, please don’t hesitate to reach out—I’m here to support you!
Sources: livekit-plugins/livekit-plugins-speechmatics/livekit/plugins/speechmatics/s... | Agent speech and audio | LiveKit docs | agents/src/voice/agent_activity.tspolite-dog-12152
11/18/2025, 7:23 AMtall-airline-16756
11/18/2025, 7:24 AMreduce_latency=True can really help cut down delays. And if you’re working with streaming plugins like ElevenLabs or NeuPhonic, they already have low-latency streaming built in for you.
2. Use Streaming TTS Models
Picking TTS plugins that support native streaming, such as ElevenLabs or NeuPhonic, lets audio come through bit by bit as it’s created, making things feel faster.
3. Optimize Audio Format
Using the audio/pcm format can reduce encoding time, and matching the sample_rate to what your app needs helps keep things smooth.
4. Prewarm TTS Connections
For plugins like NeuPhonic, calling prewarm() gets connections ready ahead of time, so you won’t have to wait for that initial setup.
5. Pre-Synthesize Predictable Responses
If you have fixed phrases like greetings, using session.say() with pre-recorded or pre-generated audio can skip the synthesis step altogether.
6. Adjust Speech Speed
Speeding up speech with parameters like speed_alpha (for Rime) or speaking_rate (for Inworld) can help reduce how long it takes to generate audio.
7. Monitor Latency Metrics
Keep an eye on key numbers like TTFT (Time to First Token) < 300ms, TTFB (Time to First Byte) < 200ms, and End-to-End Latency < 1000ms to make sure things are running smoothly.
If you’d like, I’m here to help you configure a specific TTS plugin or fine-tune your setup—just let me know!
Sources: Operational Best Practices | livekit/livekit_composite | DeepWiki | Live Conversations with AI using ChatGPT and WebRTC | Agent speech and audio | LiveKit docs | Knowledge Base Content | livekit/livekit_composite | DeepWiki | Rime TTS plugin guide | LiveKit Docs