future-umbrella-45124
09/09/2025, 11:22 AMtall-airline-16756
09/09/2025, 11:22 AMtall-airline-16756
09/09/2025, 11:23 AMfuture-umbrella-45124
09/09/2025, 11:28 AMtall-airline-16756
09/09/2025, 11:29 AMbefore_tts_cb callback to gently filter the text before it goes through the Text-to-Speech (TTS) engine. Here’s a simple example:
async def _before_tts_cb(agent: VoicePipelineAgent, text: str | AsyncIterable[str]):
if isinstance(text, str):
# Handle non-streaming text
result = text.replace("<think>", "").replace("</think>", "")
return result
else:
# Handle streaming text
async def process_stream():
async for chunk in text:
processed = chunk.replace("<think>", "").replace("</think>", "Okay, I'm ready to respond.")
yield processed
return process_stream()
2. Modifying the Agent's Behavior:
• If you're comfortable with a bit more customization, you can override the llm_node method in your custom Agent class to directly process the output. Here’s how it might look:
async def llm_node(self, chat_ctx, tools, model_settings=None):
async def process_stream():
async with self.llm.chat(chat_ctx=chat_ctx, tools=tools) as stream:
async for chunk in stream:
if chunk is None:
continue
content = getattr(chunk.delta, 'content', None) if hasattr(chunk, 'delta') else str(chunk)
if content:
processed_content = content.replace("<think>", "").replace("</think>", "")
if hasattr(chunk, 'delta') and hasattr(chunk.delta, 'content'):
chunk.delta.content = processed_content
else:
chunk = processed_content
yield chunk
return process_stream()
Pros and Cons to keep in mind:
• Preprocessing: This is usually easier to implement and maintain, perfect if you want a straightforward filter for specific patterns.
• Agent Modification: Gives you more control and flexibility, though it might need a bit more integration effort and testing.
Also, don’t forget about the handy built-in filter_markdown utility! It can help you manage a variety of text formatting styles like headers, lists, block quotes, images, links, bold/italic text, and code blocks.
If you’d like, I’m here to walk you through any of these steps or answer any questions you have. Just let me know!
Sources: chain-of-thought-tts/README.mdoc | Modifying LLM output before TTS | LiveKit Docs | livekit-agents/livekit/agents/llm/utils.pyfuture-umbrella-45124
09/10/2025, 10:43 AMtall-airline-16756
09/10/2025, 10:44 AMtts_node method to customize LLM-generated text before it gets synthesized into speech. Here's a friendly example of how you can create a custom Agent class to achieve this:
from livekit import rtc
from livekit.agents import Agent, ModelSettings
from typing import AsyncIterable
import logging
logger = logging.getLogger("tts_node_override")
logger.setLevel(logging.INFO)
class MyAgent(Agent):
async def tts_node(
self,
text: AsyncIterable[str],
model_settings: ModelSettings
) -> AsyncIterable[rtc.AudioFrame]:
"""Modify LLM-generated text before TTS synthesis."""
async def process_text():
async for chunk in text:
original_chunk = chunk
# Example modification: replace "lol" with "[laughs]"
modified_chunk = chunk.replace("lol", "[laughs]").replace("LOL", "[laughs]")
if original_chunk != modified_chunk:
logger.info(f"TTS original: '{original_chunk}'")
logger.info(f"TTS modified: '{modified_chunk}'")
yield modified_chunk
# Use default TTS behavior with modified text
async for frame in Agent.default.tts_node(self, process_text(), model_settings):
yield frame
Here's a quick explanation to help you along:
• The process_text function lets you work with the incoming text stream, so you can tweak or filter the text as you like—for example, swapping out "lol" for "[laughs]".
• After modifying the text, it’s passed along to the default TTS implementation using Agent.default.tts_node.
This method gives you wonderful flexibility to customize the text right before it reaches the TTS engine, making sure the output sounds just the way you want. If you have any questions or would like more examples, please don’t hesitate to ask—I’m here to help!
Sources: Pipeline nodes and hooks | LiveKit Docs | Docs::Agents | Pipeline nodes and hooks | LiveKit Docs | Tool definition and use | LiveKit Docs | pipeline-tts/tts_node.pyfuture-umbrella-45124
09/10/2025, 10:46 AMtall-airline-16756
09/10/2025, 10:47 AMtts_node method is designed to process text that’s generated solely by the agent’s LLM as part of its response. It doesn’t handle text chunks that come directly from the user.
Here’s how the data flows: user audio → stt_node → chat context → llm_node → tts_node → agent audio output. So, while the user’s input does influence the agent’s response indirectly through the llm_node, the tts_node itself focuses on synthesizing text created by the agent.
If you’re looking to adjust how the user’s input impacts the agent’s response, you’d want to make those changes upstream in the llm_node or through other hooks like on_user_turn_completed. Please feel free to ask if you’d like me to walk you through this with more details or examples—I’m here to help!
Sources: Pipeline nodes and hooks | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | pipeline-tts/short_replies_only.py | Docs::Agentsfuture-umbrella-45124
09/10/2025, 10:50 AMtall-airline-16756
09/10/2025, 10:51 AMtts_node, you can override the method to gather all incoming text chunks before sending them to the TTS engine. Here’s a friendly example to guide you through it:
from livekit import rtc
from livekit.agents import Agent, ModelSettings
from typing import AsyncIterable
class MyAgent(Agent):
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
full_text = ""
async for chunk in text:
full_text += chunk
# Now full_text contains the entire LLM response
print(f"Full LLM response: {full_text}")
# Optional: Preprocess full_text (e.g., remove tags, modify content)
processed_text = full_text.replace("", "")
# Pass the processed text as a single chunk to the TTS engine
return Agent.default.tts_node(self, iter([processed_text]), model_settings)
Here’s a quick explanation to make things clearer:
• The tts_node method collects all the text chunks into one complete string (full_text).
• You have the flexibility to preprocess full_text however you like, such as removing tags or applying any transformations.
• Finally, the processed text gets passed to the TTS engine as a single-element iterator, making the process seamless.
This way, you ensure the entire LLM response is ready for processing before synthesis, giving you the chance to apply any full-context changes you need. If you’d like, I’m here to help with more examples or any other questions you might have!
Sources: livekit-agents/livekit/agents/voice/generation.py | Tool definition and use | LiveKit Docs | Modifying LLM output before TTS | LiveKit Docs | Docs::Agentsfuture-umbrella-45124
09/10/2025, 10:58 AMtall-airline-16756
09/10/2025, 10:59 AMtts_node function? For instance, are you hoping to log it, adjust the behavior based on the room, or something else? I’m here to help you figure it out!future-umbrella-45124
09/10/2025, 10:59 AMtall-airline-16756
09/10/2025, 11:00 AMtts_node function might feel a bit unclear since it's not explicitly documented. A helpful way to handle this is by passing the room ID as part of the agent's context or configuration when you initialize the agent. This makes it easily accessible inside the tts_node function.
For example, you could store the room ID in the agent's instance variables during initialization like this:
class MyAgent(Agent):
def __init__(self, room_id, *args, **kwargs):
super().__init__(*args, **kwargs)
self.room_id = room_id
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
# Access the room ID
print(f"Room ID: {self.room_id}")
# Use the room ID in your API call
response = await make_api_call(self.room_id, text)
return response
Please feel free to reach out if you'd like any more help with implementing this approach or with making the API call—I’m here to support you!future-umbrella-45124
09/10/2025, 11:13 AMtall-airline-16756
09/10/2025, 11:14 AMroom_id, instructions, and chat_ctx. You can simply adjust the constructor of your custom agent to accept these values when you create an instance. Here's a friendly example to guide you:
from livekit.agents import Agent
class CustomSessionAgent(Agent):
def __init__(self, room_id, instructions, chat_ctx, *args, **kwargs):
super().__init__(instructions=instructions, chat_ctx=chat_ctx, *args, **kwargs)
self.room_id = room_id
# Example initialization
agent = CustomSessionAgent(
room_id="room12345",
instructions="You are a helpful assistant.",
chat_ctx=initial_chat_ctx
)
Here's a quick rundown:
• The room_id is saved as an instance variable (self.room_id) so you can use it inside your agent whenever you need.
• The instructions and chat_ctx get passed up to the parent Agent class with super().__init__, making sure everything is set up properly.
If you'd like, I’m here to walk you through more examples or answer any other questions you might have!
Sources: main.py | Job lifecycle | LiveKit Docs | Workflows | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py | agents/src/voice/generation.tsfuture-umbrella-45124
09/10/2025, 1:13 PMfrom livekit import rtc
from livekit.agents import Agent, ModelSettings
from typing import AsyncIterable
class MyAgent(Agent):
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
full_text = ""
async for chunk in text:
full_text += chunk
# Now full_text contains the entire LLM response
print(f"Full LLM response: {full_text}")
# Optional: Preprocess full_text (e.g., remove tags, modify content)
processed_text = full_text.replace("", "")
# Pass the processed text as a single chunk to the TTS engine
return Agent.default.tts_node(self, iter([processed_text]), model_settings)
I am using this structur as suggested by you, but it's not working, essentially I am noticing that the agent isn't speaking at all. Can you see if there is a mistake. since in the repo's sample example, they are passing a function which yields.tall-airline-16756
09/10/2025, 1:14 PMtts_node function isn’t yielding text chunks in the way the default TTS node expects. The default TTS node works best with an asynchronous stream of text chunks to synthesize speech smoothly. If this stream isn’t forwarded correctly, the agent might stop speaking unexpectedly.
To help you out, here’s a revised version that should work better:
from livekit import rtc
from livekit.agents import Agent, ModelSettings
from typing import AsyncIterable
class MyAgent(Agent):
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
async def process_text():
full_text = ""
async for chunk in text:
full_text += chunk
# Optional: Preprocess full_text (e.g., remove tags, modify content)
processed_text = full_text.replace("", "")
# Yield the processed text as a single chunk
yield processed_text
# Forward the processed stream to the default TTS node
return Agent.default.tts_node(self, process_text(), model_settings)
Here are the key updates to keep in mind:
• The process_text function collects the entire response first and then yields it as one chunk.
• We call Agent.default.tts_node with this processed stream, making sure the TTS engine gets the input it needs.
Please feel free to reach out if you want me to walk you through this further or if you’d like some extra debugging tips. I’m here to help!
Sources: Docs::Agents | pipeline-tts/tts_node.py | livekit-plugins/livekit-plugins-lmnt/livekit/plugins/lmnt/tts.py