steep-balloon-41261
11/06/2025, 8:26 AMtall-airline-16756
11/06/2025, 8:26 AMtall-airline-16756
11/06/2025, 8:27 AMSpeechCreatedEvent! This event is triggered whenever new agent speech is created, which can happen for a few reasons:
• The user has provided input
• session.say is used to create agent speech
• session.generate_reply is called to create a reply
To help you get started, here’s a simple example of how you can use this event:
Python:
@session.on("speech_created")
def on_speech_created(event: SpeechCreatedEvent):
print(f"Speech created via {event.source}. User initiated: {event.user_initiated}")
# Use speech_handle to control playback
handle = event.speech_handle
if not event.user_initiated:
# Allow interruptions only for non-user-initiated speech
handle.allow_interruptions = True
TypeScript:
session.on('speech_created', (event: SpeechCreatedEvent) => {
console.log(`Speech created from source: ${event.source}, initiated by user: ${event.userInitiated}`);
const handle = event.speechHandle;
// Example: Wait for speech to finish playing
handle.waitForPlayout();
});
If you’d like to dive deeper, feel free to check out the LiveKit documentation on events and the Agent speech and audio guide. I’m here if you have any questions or need further assistance!
Sources: livekit-agents/livekit/agents/inference/stt.py | Events and error handling | LiveKit docs | Agent speech and audio | LiveKit docs | agents/src/voice/events.tsbetter-sandwich-65834
11/06/2025, 8:27 AMtall-airline-16756
11/06/2025, 8:28 AMSpeechCreatedEvent can be a bit tricky. It doesn’t directly change what the agent will say because it happens after the speech content is already generated. However, it does give you a SpeechHandle that lets you control how the speech plays back—like whether to allow interruptions or wait until the speech finishes.
If you’re looking to actually change the text the agent says, you’ll want to jump in a little earlier in the process. Here are some friendly options you can try:
• Modify LLM Output: You can use the llm_node() hook to tweak the text the language model creates before it goes to TTS. This is great if you want to rewrite or replace the agent’s response.
• Customize Text Before TTS: The tts_node() hook lets you fine-tune the text right before it’s turned into speech—perfect for adding SSML tags or adjusting how things are phrased.
• Direct Speech: If you want the agent to say something specific right away, session.say() lets you bypass the LLM and speak directly.
• Update Instructions: You can also dynamically change how your agent behaves and responds by updating its instructions using agent.update_instructions().
Please feel free to reach out if you’d like me to share some examples or walk you through any of these methods—I’m here to help!
Sources: Agents v0.x migration guide - Node.js | LiveKit Docs | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | agents/src/voice/events.ts | Events and error handling | LiveKit docs | livekit-agents/livekit/agents/voice/agent_activity.pybetter-sandwich-65834
11/06/2025, 8:29 AMtall-airline-16756
11/06/2025, 8:30 AMllm_node() hook to catch and tweak the text generated by the language model before it goes to TTS. This gives you the flexibility to rewrite or replace the agent's response on the fly.
• Customize Text Before TTS: The tts_node() hook lets you adjust the text right before it’s turned into speech. This is perfect for fine-tuning how things sound or adding SSML tags to improve pronunciation.
• Direct Speech: If you want the agent to say something very specific, you can use session.say() to bypass the language model altogether. This works well for scripted or predefined lines.
• Update Instructions: You can also dynamically update the agent’s behavior and style by changing its instructions with agent.update_instructions(). This shapes how the agent responds in future conversations.
These options give you full control over the agent’s speech content. If you’d like, I’d be more than happy to provide detailed examples or guide you through implementing any of these approaches. Just let me know!better-sandwich-65834
11/06/2025, 8:41 AMtall-airline-16756
11/06/2025, 8:41 AMtts_node plays a key role in the STT-LLM-TTS pipeline of a voice agent in LiveKit, helping to transform the text generated by the LLM into clear, audible speech. It’s quite flexible and can be tailored to fit different needs, such as:
• Default TTS Synthesis: This converts text to speech using the TTS model you’ve set up in your agent configuration.
• Custom Pronunciation: You can tweak the text before synthesis, like swapping out acronyms or informal phrases to make the speech sound more natural.
• Audio Processing: It allows for enhancements like adjusting the volume or speeding up the audio output to suit your preferences.
• Short Reply Filtering: You can keep responses concise by limiting replies based on text length.
• Dynamic TTS Switching: This lets you switch between different TTS providers on the fly during runtime.
• Standalone Usage: You can even use it outside the usual pipeline to directly publish synthesized audio to participants.
It’s a great upgrade from the older before_tts_cb callback, offering much more flexibility to customize both the text input and the audio output. If you’d like, I’m here to help you implement any specific use case you have in mind!
Sources: livekit-agents/livekit/agents/telemetry/trace_types.py | Pipeline nodes and hooks | LiveKit docs | docs/index.yaml | Camera & microphone | LiveKit Docs | Text-to-speech (TTS) models | LiveKit Docsbetter-sandwich-65834
11/06/2025, 8:44 AMfrom livekit import rtc
from livekit.agents import ModelSettings, Agent
from typing import AsyncIterable
async def tts_node(
self, text: AsyncIterable[str], model_settings: ModelSettings
) -> AsyncIterable[rtc.AudioFrame]:
# Insert custom text processing here
async for frame in Agent.default.tts_node(self, text, model_settings):
# Insert custom audio processing here
yield frame
i want to modify text that will be saidtall-airline-16756
11/06/2025, 8:45 AMtts_node, you can gently process the text stream before it gets converted into audio frames. Here’s a simple example to guide you through this:
from livekit import rtc
from livekit.agents import ModelSettings, Agent
from typing import AsyncIterable
async def tts_node(
self, text: AsyncIterable[str], model_settings: ModelSettings
) -> AsyncIterable[rtc.AudioFrame]:
# Modify the text before synthesis
async for chunk in text:
modified_chunk = chunk.replace("original text", "modified text")
# Pass the modified text to the default TTS node
async for frame in Agent.default.tts_node(self, iter([modified_chunk]), model_settings):
yield frame
In this example, we’re capturing and tweaking the text chunks (like swapping out specific words or phrases) before sending them along to the default TTS node for synthesis. Feel free to adjust the modified_chunk part to fit exactly what you need.
If you have any questions or would like me to walk you through more examples, just let me know—I’m here to help!better-sandwich-65834
11/06/2025, 8:48 AMasync def tts_node(
self, text: AsyncIterable[str], model_settings: ModelSettings
) -> AsyncIterable[rtc.AudioFrame]:
# Insert custom text processing here
async for frame in Agent.default.tts_node(self, text, model_settings):
# Insert custom audio processing here
yield frame
i want to dynamically translate text here to target languagetall-airline-16756
11/06/2025, 8:48 AMtts_node, you can add a translation step right before passing the text to the default TTS node. Here’s a simple example to guide you:
from livekit import rtc
from livekit.agents import ModelSettings, Agent
from typing import AsyncIterable
import some_translation_library # Replace with your preferred translation library
async def tts_node(
self, text: AsyncIterable[str], model_settings: ModelSettings
) -> AsyncIterable[rtc.AudioFrame]:
async for chunk in text:
# Translate the text chunk to the target language
translated_chunk = some_translation_library.translate(chunk, target_language="es") # Example: Translate to Spanish
# Pass the translated text to the default TTS node
async for frame in Agent.default.tts_node(self, iter([translated_chunk]), model_settings):
yield frame
In this example, just swap out some_translation_library with the translation library or API you prefer, like Google Translate API or DeepL API. The translate function will take care of converting the text chunk into the language you want before it’s turned into audio.
If you’d like, I’m here to help you set up a specific translation library or API—just let me know!better-sandwich-65834
11/06/2025, 8:49 AMtranslator = LLM.with_azure(
azure_deployment=judge_llm_settings.model,
temperature=0.0,
)
translate_ctx = llm.ChatContext()
translate_ctx.add_message(
role="system",
content=(
f"You are a professional translator. Your task is to translate the ENTIRE document below into {language_name}. "
f"CRITICAL RULES:\n"
f"1. Translate EVERY SINGLE LINE and EVERY SINGLE WORD\n"
f"2. Maintain ALL formatting, line breaks, bullet points, and structure\n"
f"3. Do NOT summarize, shorten, or skip any content\n"
f"4. Do NOT add explanations or commentary\n"
f"5. Return ONLY the complete translated text\n"
f"6. The document is very long - translate it ALL from beginning to end"
),
)
translate_ctx.add_message(
role="user",
content=f"Translate this complete document into {language_name}:\n\n{original_instructions}"
)
logger.info("Starting translation of %d characters...", len(original_instructions))
translation_stream = translator.chat(chat_ctx=translate_ctx)
translated_chunks: list[str] = []
chunk_count = 0
async for chunk in translation_stream:
if chunk.delta and chunk.delta.content:
translated_chunks.append(chunk.delta.content)
chunk_count += 1
await translation_stream.aclose()
logger.info("Received %d chunks from translator", chunk_count)
translated_instructions = "".join(translated_chunks).strip()
i'll use this translate mechanismtall-airline-16756
11/06/2025, 8:50 AMtts_node! You can use it to translate the text chunks dynamically before passing them to the default TTS node. Here's a way you can adapt your code:
from livekit import rtc
from livekit.agents import ModelSettings, Agent
from typing import AsyncIterable
async def tts_node(
self, text: AsyncIterable[str], model_settings: ModelSettings
) -> AsyncIterable[rtc.AudioFrame]:
async for chunk in text:
# Set up the translation context
translate_ctx = llm.ChatContext()
translate_ctx.add_message(
role="system",
content=(
f"You are a professional translator. Your task is to translate the ENTIRE document below into {language_name}. "
f"CRITICAL RULES:\n"
f"1. Translate EVERY SINGLE LINE and EVERY SINGLE WORD\n"
f"2. Maintain ALL formatting, line breaks, bullet points, and structure\n"
f"3. Do NOT summarize, shorten, or skip any content\n"
f"4. Do NOT add explanations or commentary\n"
f"5. Return ONLY the complete translated text\n"
f"6. The document is very long - translate it ALL from beginning to end"
),
)
translate_ctx.add_message(
role="user",
content=f"Translate this complete document into {language_name}:\n\n{chunk}"
)
# Perform the translation
translation_stream = translator.chat(chat_ctx=translate_ctx)
translated_chunks = []
async for translation_chunk in translation_stream:
if translation_chunk.delta and translation_chunk.delta.content:
translated_chunks.append(translation_chunk.delta.content)
await translation_stream.aclose()
# Combine translated chunks
translated_text = "".join(translated_chunks).strip()
# Pass the translated text to the default TTS node
async for frame in Agent.default.tts_node(self, iter([translated_text]), model_settings):
yield frame
This method lets you dynamically translate each text chunk with your translation mechanism, then synthesize the translated text into audio. If you have any questions or want to explore this further, please don’t hesitate to ask—I’m here to support you every step of the way!better-sandwich-65834
11/06/2025, 8:52 AMtall-airline-16756
11/06/2025, 8:52 AMtranslator object hasn't been defined in your code snippet yet. No worries! To fix this, you just need to initialize the translator using your preferred LLM or translation API. Here’s a simple example to get you started:
from livekit.agents import llm
# Initialize the translator with Azure LLM settings
translator = llm.LLM.with_azure(
azure_deployment=judge_llm_settings.model, # Replace with your Azure deployment settings
temperature=0.0, # Adjust temperature as needed
)
Just be sure to swap out judge_llm_settings.model with the correct model settings for your Azure deployment. Once you’ve got translator set up, the rest of your code should run smoothly.
If you have any questions or need a hand with anything else, feel free to ask—I’m here to help!