How do I allow a user to switch the TTS voice opti...
# ask-ai
n
How do I allow a user to switch the TTS voice option after a room has been created?
đź‘€ 1
t
Thanks for reaching out, William. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I’m happy to help you enable users to switch the TTS voice option even after a room has been created! You can easily update the voice settings on the fly by using the
update_options
method available on TTS instances. This method works smoothly across different TTS plugins and LiveKit’s unified inference gateway. Here’s a friendly step-by-step guide to get you started: 1. Set up a listener for
participant_attributes_changed
so you can detect when a user picks a new voice. 2. Make sure to validate the selected voice ID to confirm it’s valid and supported. 3. Call
tts.update_options(voice="new_voice_id")
to update the voice. The change will take effect the next time the system speaks. 4. It’s a nice touch to provide user feedback, like confirming the voice switch, especially when the agent isn’t speaking. This method works well with all supported TTS providers, including Cartesia, ElevenLabs, and Google Cloud. If you’d like, I’m here to help with any part of the implementation or answer any questions you might have! Sources: agent/main.py | livekit-plugins/livekit-plugins-neuphonic/livekit/plugins/neuphonic/tts.py | Hume TTS plugin guide | LiveKit Docs | Introducing LiveKit Inference: A unified model interface for voice AI
n
but what if i need to also change the provider? I'm trying to use Hume and Elevenlabs
t
It’s great that you’re looking to switch between TTS providers like Hume and ElevenLabs dynamically! A helpful approach here is using the agent transfer pattern. This means creating separate agent classes for each provider and using function tools to smoothly switch between them. Here’s a simple way to get started: 1. Create separate agent classes for Hume and ElevenLabs, each set up with their specific TTS instance. 2. Define function tools such as
switch_to_hume()
and
switch_to_elevenlabs()
that return the new agent instance. 3. When the user says something like "Switch to ElevenLabs," the function tool will handle the agent transfer, keeping your session state and context intact. Another option is to use LiveKit Inference, which offers a simpler API. With this, switching providers just means reinitializing the agent with a new TTS string. If you’d like, I’m more than happy to provide detailed code examples or walk you through the process—just let me know! Sources: docs/index.yaml | examples/src/comprehensive_test.ts | livekit-plugins/livekit-plugins-hume/livekit/plugins/hume/tts.py | Introducing LiveKit Inference: A unified model interface for voice AI | Hume TTS plugin guide | LiveKit Docs
n
No this will be updated using the participant attributes changed event handler.
t
I'd love to help you dynamically switch TTS providers like Hume and ElevenLabs using the
participant_attributes_changed
event handler! Here's a friendly approach you can try: 1. First, listen for changes in participant attributes with the
participant_attributes_changed
event. 2. Then, check if there’s a specific attribute (like
tts_provider
) that tells you which TTS provider to use. 3. Finally, based on that attribute’s value, you can reinitialize the TTS instance or switch to a new agent set up with the chosen provider. Here’s a simple example to illustrate:
Copy code
@ctx.room.on("participant_attributes_changed")
def on_participant_attributes_changed(changed_attributes, participant):
    if "tts_provider" in changed_attributes:
        provider = participant.attributes.get("tts_provider")
        if provider == "hume":
            tts = hume.TTS(...)
        elif provider == "elevenlabs":
            tts = elevenlabs.TTS(...)
        # Update the agent or session with the new TTS instance
This way, you can update TTS providers in real-time based on what the user chooses. If you’d like, I’m here to walk you through more detailed steps or clarify anything—just let me know! Sources: Participant attributes and metadata | LiveKit docs | agent/main.py | pipeline-tts/changing_language/README.md | Introducing LiveKit Inference: A unified model interface for voice AI | Job lifecycle | LiveKit Docs
n
Yes i get that part. This is the part that I need help with: # Update the agent or session with the new TTS instance Please continue with the code example, because I'm unclear after the part you shared. I actually have that much already just confused because I can't change the tts from the AgentSession it seems.
t
To dynamically update the TTS instance in an
AgentSession
, you can use the
update_options
method on the TTS instance. However, if you need to switch the TTS provider entirely, you will need to reinitialize the agent with the new TTS configuration. Here’s how you can proceed: For updating the TTS instance dynamically:
Copy code
@ctx.room.on("participant_attributes_changed")
def on_participant_attributes_changed(changed_attributes, participant):
    if "tts_provider" in changed_attributes:
        provider = participant.attributes.get("tts_provider")
        if provider == "hume":
            session.tts.update_options(voice="HumeVoiceID", model="hume_model")
        elif provider == "elevenlabs":
            session.tts.update_options(voice="ElevenLabsVoiceID", model="elevenlabs_model")
        # Provide feedback
        asyncio.create_task(session.say("TTS provider updated successfully."))
If you need to switch providers entirely (e.g., from Hume to ElevenLabs), you will need to reinitialize the agent:
Copy code
class HumeAgent(Agent):
    def __init__(self):
        super().__init__(
            tts=hume.TTS(voice="HumeVoiceID"),
            # other configurations
        )

class ElevenLabsAgent(Agent):
    def __init__(self):
        super().__init__(
            tts=elevenlabs.TTS(voice="ElevenLabsVoiceID"),
            # other configurations
        )

@ctx.room.on("participant_attributes_changed")
def on_participant_attributes_changed(changed_attributes, participant):
    if "tts_provider" in changed_attributes:
        provider = participant.attributes.get("tts_provider")
        if provider == "hume":
            session = AgentSession(agent=HumeAgent())
        elif provider == "elevenlabs":
            session = AgentSession(agent=ElevenLabsAgent())
        asyncio.create_task(session.say("Switched to the new TTS provider."))
I hope this helps you smoothly update or switch your TTS provider! If anything feels unclear or you’d like a hand with the implementation, please don’t hesitate to ask—I’m here to support you every step of the way. Sources: OpenAI Realtime API plugin guide | LiveKit docs | Hume TTS plugin guide | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | pipeline-tts/tts_comparison/README.md | Text-to-speech (TTS) models | LiveKit Docs
n
async def switch_agent(): _try_: # Create new session with the new agent new_session = AgentSession( vad=ctx.proc.userdata["vad"], _preemptive_generation_=True ) # Start the new session with the new agent await new_session.start(agent=new_agent, room=ctx.room) logger.info(f"✅ Successfully switched to voice '{voice_name}' (provider: {provider})") print(f"✅ Agent switched to voice '{voice_name}' (provider: {provider})") # Announce the switch using the new session await new_session.say(f"Voice changed to {voice_name}.") except Exception as e: logger.error(f"Failed in switch_agent task: {e}") logger.exception(e) print(f"❌ Error in switch_agent: {e}") Like this?
t
Your implementation is definitely on the right track! Using a new
AgentSession
to switch agents dynamically is a great approach. I’d like to share a few friendly tips to help make sure everything runs smoothly: 1. Make sure the
new_agent
is fully initialized with the TTS provider and configuration you want before starting the session. 2. Keep any important state or context from the previous session if needed—like user-specific data or room attributes—so nothing gets lost during the switch. 3. Try to handle any ongoing tasks or speech in the current session gently before switching over, to avoid any sudden interruptions. Here’s a slightly polished version of your code that incorporates these ideas:
Copy code
async def switch_agent(new_agent, voice_name, provider):
    try:
        # Create new session with the new agent
        new_session = AgentSession(
            vad=ctx.proc.userdata["vad"],
            preemptive_generation=True
        )

        # Start the new session with the new agent
        await new_session.start(agent=new_agent, room=ctx.room)

        logger.info(f"âś… Successfully switched to voice '{voice_name}' (provider: {provider})")
        print(f"âś… Agent switched to voice '{voice_name}' (provider: {provider})")

        # Announce the switch using the new session
        await new_session.say(f"Voice changed to {voice_name}.")
    except Exception as e:
        logger.error(f"Failed in switch_agent task: {e}")
        logger.exception(e)
        print(f"❌ Error in switch_agent: {e}")
This way, the new session gets set up properly and the voice change is kindly announced to everyone involved. If you have any questions or want to explore this further, just let me know—I’m here to help!
n
Now I have two agents talking how do i end the other agent session
t
To smoothly end the existing agent session when switching to a new agent, you can use the
aclose()
method on the current
AgentSession
. This helps tidy things up nicely and prevents multiple agents from speaking at the same time. Here’s a friendly way to adjust your code:
Copy code
async def switch_agent(new_agent, voice_name, provider):
    try:
        # Close the current session
        if current_session:
            await current_session.aclose()

        # Create a new session with the new agent
        new_session = AgentSession(
            vad=ctx.proc.userdata["vad"],
            preemptive_generation=True
        )

        # Start the new session with the new agent
        await new_session.start(agent=new_agent, room=ctx.room)

        logger.info(f"âś… Successfully switched to voice '{voice_name}' (provider: {provider})")
        print(f"âś… Agent switched to voice '{voice_name}' (provider: {provider})")

        # Announce the switch using the new session
        await new_session.say(f"Voice changed to {voice_name}.")
    except Exception as e:
        logger.error(f"Failed in switch_agent task: {e}")
        logger.exception(e)
        print(f"❌ Error in switch_agent: {e}")
Just be sure to replace
current_session
with the actual reference to the active session you want to close. If anything feels unclear or you want to dive deeper, please don’t hesitate to ask—I’m here to help! Sources: examples/warm-transfer/README.md | Job lifecycle | LiveKit Docs
n
When I run, it doesn't seem to be available to the agent. It's telling me it doesn't have history at least not on the initial turn. await self.update_chat_ctx(new_ctx)
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
n
When I run, it doesn't seem to be available to the agent. It's telling me it doesn't have history at least not on the initial turn. await self.update_chat_ctx(new_ctx)