I am intending to parse Livekit agents response, t...
# ask-ai
f
I am intending to parse Livekit agents response, to extract xml tags etc. My requirement is that I dont want agent to speak whatever is under these certain tags. Is there a standard way to control this? FYI, I am using python sdk...
t
Thanks for reaching out, Tushar. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for reaching out! Could you please share a bit more about which specific XML tags or content you'd like to exclude from the agent's response? Also, it would be helpful to know if you're looking for a way to preprocess the response before parsing, or if you'd prefer some guidance on adjusting the agent's behavior directly. I'm here to help you through this!
f
For example, if agent want to provide code, in that case the code is formatted. I want to be able to handle such cases. As for the preprocess before after. I want you to tell both of the ways along with pros and cons
t
I'm here to help you handle cases where the agent provides formatted content, like code. You have a couple of friendly approaches to try out: 1. Preprocessing the Response: • You can use the
before_tts_cb
callback to gently filter the text before it goes through the Text-to-Speech (TTS) engine. Here’s a simple example:
Copy code
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:
Copy code
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.py
f
For my usecase I think I would like to go with overriding tts_node method. Can you give me an sample overriding of async tts_node. I want to modify the llm generated text
t
I'm glad you're exploring how to override the
tts_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:
Copy code
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.py
f
does tts_node receives chunk texts of both agent and user?
t
Thanks for reaching out! The
tts_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::Agents
f
Can you give me a sample example such that, I want to store the full LLM response in one chunk and then process it!
t
To help you store the full LLM response in one chunk and process it smoothly in the
tts_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:
Copy code
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::Agents
f
Is it possible to know the roomid, inside this tts_node function
t
Thanks for reaching out! Could you please share a bit more about how you plan to use the room ID within the
tts_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!
f
I kind of have to make an api call for which i need the roomid
t
I understand that accessing the room ID directly within the
tts_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:
Copy code
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!
f
This is how I am initialising the agent right now - agent=agents.Agent( instructions=instructions, _chat_ctx_=initial_chat_ctx, ), Since now I am using the custom Agent for the tts_node, I want to know the syntax for initialising the custom agent. here is how it looks - class CustomSessionAgent(Agent): def __init__(self, roomid, *_args_, **_kwargs_): super().__init__(*_args_, **_kwargs_) self.room_id = roomid _as you can see I am looking for roomid, also I have to correctly set the instructions and chat_ctx!_
t
I'm happy to help you get your custom agent class set up with those extra parameters like
room_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:
Copy code
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.ts
f
Copy code
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)
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.
t
Thank you for sharing your implementation! It looks like the main hiccup is that your
tts_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:
Copy code
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