How can I modify the text sent from agent to TTS b...
# ask-ai
f
How can I modify the text sent from agent to TTS before producing the audio output?
t
Thanks for reaching out, Taras. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm here to help you modify the text sent to the Text-to-Speech (TTS) engine before it generates audio output. The approach varies depending on which version of LiveKit Agents you're using, so let's walk through both together: For LiveKit Agents v0.x: You can use the
before_tts_cb
callback when you initialize a
VoicePipelineAgent
. This callback lets you tweak the text before it reaches the TTS engine. Here's a friendly example to guide you:
Copy code
def _before_tts_cb(agent: VoicePipelineAgent, text: str | AsyncIterable[str]):
    if isinstance(text, str):
        return text.replace("LiveKit", "Live Kit")
    else:
        async def process_stream():
            async for chunk in text:
                yield chunk.replace("LiveKit", "Live Kit")
        return process_stream()

agent = VoicePipelineAgent(
    # ... other parameters
    before_tts_cb=_before_tts_cb,
)
For LiveKit Agents v1.x: The process is a bit different and offers more flexibility. You’ll want to override the
tts_node
method in a custom
Agent
subclass. This way, you can adjust both text and audio as needed. Here’s a simple example to get you started:
Copy code
class MyAgent(Agent):
    async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
        async def process_text():
            async for chunk in text:
                yield chunk.replace("LiveKit", "Live Kit")

        # Pass the modified text to the default TTS node
        async for audio_frame in Agent.default.tts_node(self, process_text(), model_settings):
            yield audio_frame
Just a quick reminder: make sure to use the method that matches your LiveKit Agents version. If you’re moving from v0.x to v1.x, updating your code from
before_tts_cb
to
tts_node
will help everything run smoothly. Sources: Agents v0.x migration guide - Node.js | LiveKit Docs | Agents 0.x migration guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | Docs::Agents | chain-of-thought-tts/agent.py
f
How can I make agent speak before finishing function tool execution?
t
I’m glad you asked! To have an agent speak before finishing a function tool execution, you can use asynchronous tasks to provide verbal updates during longer operations. Let me walk you through how you can do this: Using `context.session.generate_reply()`:
Copy code
@function_tool()
async def search_knowledge_base(self, context: RunContext, query: str) -> str:
    # Here’s a little helper function to give a verbal status update after a short delay
    async def _speak_status_update(delay: float = 0.5):
        await asyncio.sleep(delay)
        await context.session.generate_reply(instructions=f"""
        You are searching the knowledge base for \"{query}\" but it is taking a little while.
        Update the user on your progress, but be very brief.
        """)

    status_update_task = asyncio.create_task(_speak_status_update(0.5))
    
    # Now, perform the actual search operation
    result = await _perform_search(query)
    
    # If the search finishes quickly, we can cancel the status update task
    status_update_task.cancel()
    
    return result
Here are some additional tips to keep in mind: • Enable interruptions with
context.speech_handle.interrupted
so the agent can handle user interruptions gracefully during speech. • Consider playing background audio, like a gentle "thinking" sound, to give immediate feedback while the operation is running. • Make sure your tools return a value to trigger a verbal reply, or return
None
if you want the operation to be silent. • Don’t forget to include proper error handling to keep users informed if anything goes wrong during execution. By using this approach, your agent can provide timely verbal updates, making the experience smoother and more engaging for users during any delays. If you have any questions or want to explore this further, I’m here to help! Sources: Tool definition and use | LiveKit Docs | External data and RAG | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py