using agent 1.x, I need a way to change the eleven...
# ask-ai
f
using agent 1.x, I need a way to change the elevenLabs voice_id mid session (to use a different voice). I've tried "async def change_voice() -> Dict[str, Any]: """Change the ElevenLabs TTS voice to a different character voice""" try: # Hardcoded voice ID for testing target_voice_id = "vGQNBgLaiM3EdZtxIiuY" logger.info(f"🎭 Attempting to change voice to: {target_voice_id}") if not _agent_instance: logger.error("No agent instance available") return {"status": "error", "message": "No agent instance"} # Try multiple approaches to find and update the TTS instance updated = False _# Approach 1: Direct tts attribute if hasattr(_agent_instance, '_tts'): logger.info("Found _tts attribute") _agent_instance._tts.voice_id = target_voice_id updated = True # Approach 2: Check for tts attribute (without underscore) if hasattr(_agent_instance, 'tts'): logger.info("Found tts attribute") _agent_instance.tts.voice_id = target_voice_id updated = True # Approach 3: Try to recreate the TTS instance entirely if not updated: logger.info("Attempting to recreate TTS instance") new_tts = elevenlabs.TTS( voice_id=target_voice_id, model="eleven_turbo_v2_5", ) # Try to replace the TTS instance if hasattr(_agent_instance, '_tts'): _agent_instance._tts = new_tts updated = True elif hasattr(_agent_instance, 'tts'): _agent_instance.tts = new_tts updated = True # Log all attributes of the agent to help debug logger.info(f"Agent attributes: {[attr for attr in dir(_agent_instance) if not attr.startswith('__')][:20]}") if updated: logger.info(f"✅ Voice change operation completed for {target_voice_id}") return { "status": "success", "message": f"Voice changed to {target_voice_id}", "voice_id": target_voice_id } else: logger.error("Could not find TTS instance to update") return { "status": "error", "message": "Could not locate TTS instance" } except Exception as e: logger.error(f"Error in change_voice: {e}", exc_info=True) return { "status": "error", "message": str(e) }" but it's not actually changing the voice (no errors either)
t
Thanks for reaching out, Doug. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
If you want to change the ElevenLabs
voice_id
while you're in the middle of a session with LiveKit Agent 1.x, you can easily do that using the
update_options()
method on your TTS instance. This lets you switch up the
voice_id
and tweak other settings on the fly. Here’s a quick example:
Copy code
# Assuming you have a reference to your agent or its session
agent.tts.update_options(voice_id="new_voice_id_here")
This way, you can update the voice without having to create a whole new TTS instance. If you have any questions or want me to walk you through it, just let me know! Sources: ElevenLabs TTS integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-elevenlabs/README.md | pipeline-tts/tts_comparison.py
f
and how do I update the session's system instructions provided to the LLM in mid-session? (gemini)
t
Hey! If you want to update the system instructions for the LLM (Gemini) while you’re in the middle of a session in LiveKit Agent 1.x, you can simply use the
update_instructions
method on your agent instance. This lets you tweak the instructions on the fly without any hassle. Here’s a quick example for you:
Copy code
await agent.update_instructions("You are now speaking on a phone call.")
The best part? The changes kick in right away—no need to restart the session. If you have any questions or want me to walk you through it, just let me know! Sources: agent/main.py | basics/change_agent_instructions.py | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
f
I'm not using realtime, but rather full pipeline, does this matter?
t
Hey there! Could you help me understand how you're setting up the full pipeline? For instance, are you using a custom session manager or handling the agent's lifecycle yourself? Knowing this will really help me figure out if there are any special things to keep in mind when updating system instructions in the middle of a session. Thanks!
f
All I mean is that I"m not using google live api (for realtime) but instead I'm just using germin-2.5-flash
t
Using
gemini-2.5-flash
instead of a realtime model doesn’t automatically stop you from updating system instructions mid-session. That said, there are a few things to keep in mind: • The
update_instructions
method is available in LiveKit Agent 1.x and lets you tweak instructions on the fly. • With
gemini-2.5-flash
, making updates might cause the session to restart, which could interrupt the flow of your conversation. • Also, the Gemini Live API preview has some known quirks that might affect how smoothly instruction updates work. If you decide to go ahead with
update_instructions
, just be mindful of these possible hiccups. And hey, if you want me to explain anything further or need a hand, I’m here to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/models.py | Gemini Live API integration guide | LiveKit Docs
f
it seems hit or miss on updating the system instructions. Is there a more robust way, or can I reset the session via code to make sure it 'takes'?
t
To make sure your updated system instructions take effect, you can use the
update_instructions
method. It takes care of restarting the session behind the scenes whenever needed, so your new instructions get applied smoothly. Here’s a quick example:
Copy code
await agent.update_instructions("You are a helpful assistant speaking on the phone.")
The framework will handle the session restarts automatically to make sure everything updates correctly. If you have any questions or want me to walk you through it, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_session.py | basics/change_agent_instructions.py
f
does the context get lost upon a session restart?
t
Hey there! Just a heads-up—when you restart a session in LiveKit Agent 1.x, the context can get lost unless you make sure to preserve it. Normally, each new session kicks off with a clean slate, but don’t worry—the full session history is still hanging out in
session.history
. If you want to keep the conversation flowing smoothly across restarts, here are a couple of easy ways to do that: • When you create your
Agent
or
AgentTask
, you can pass along the previous session’s
chat_ctx
using the
chat_ctx
parameter. • Or, you can use the
update_chat_ctx
method to add the initial chat history right when your session starts up. If you’d like, I’m here to help you set this up—just let me know! Sources: Workflows | LiveKit Docs | Workflows | LiveKit Docs | livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime...
f
I have questions --> can we interrogate speechmatic's returned data and swap out it's speaker identifications (e.g Speaker S1) with the name we have for said speaker once it's been mapped? On the fly?
t
Absolutely! You can totally customize Speechmatics' returned data to swap out those speaker IDs (like Speaker S1) with names you prefer, right on the fly in LiveKit Agent 1.x. Here’s how it works: • Turn on speaker diarization in Speechmatics so you get speaker IDs in your transcript. • Set up a mapping (for example, using
SpeechmaticsUserData
) to link those speaker IDs (like S1, S2) to the names you want. • Catch the transcription stream and swap the speaker ID for your mapped name in the
transcript.text
field before it moves along in the process. Plus, you can use a handy function like
set_speaker_name
to create or update these mappings on the fly during a session. If you want, I’m here to help you get this set up! Sources: pipeline-stt/diarization.py
f
can you show me a little python snippet on how to do the swapping bit?
t
Here’s a handy little Python snippet to show you how you can swap out Speechmatics speaker IDs with names you’ve mapped, right as you go:
Copy code
# Example mapping of speaker IDs to names
speaker_mapping = {
    "S1": "Alice",
    "S2": "Bob"
}

# Function to process and replace speaker IDs
def process_transcript(transcript):
    speaker_id = transcript.get("speaker_id")
    if speaker_id in speaker_mapping:
        # Replace speaker ID with the mapped name
        transcript["text"] = f"{speaker_mapping[speaker_id]}: {transcript['text']}"
    return transcript

# Example usage
transcript_event = {
    "speaker_id": "S1",
    "text": "Hello, how are you?"
}

# Process the transcript
updated_transcript = process_transcript(transcript_event)
print(updated_transcript)
This will give you:
Copy code
{
  "speaker_id": "S1",
  "text": "Alice: Hello, how are you?"
}
Feel free to plug this into your LiveKit transcription stream processing. And if you want a hand with anything else, just give me a shout!
f
why are we not exploiting the llm_node to modify the chat context before sending it to LLM?
t
You're totally right! The
llm_node
is a great tool to tweak the chat context before it gets sent to the LLM in LiveKit Agent 1.x. It gives you the flexibility to customize how the LLM is used, like adding or changing context on the fly. For instance, you can override the
llm_node
method in your own
Agent
subclass to preprocess the
chat_ctx
before it reaches the LLM. People often do this for things like retrieval-augmented generation (RAG) or to dynamically add speaker mappings into the context. If you'd like, I’d be happy to share a code example or help you get started with this—just let me know! Sources: Agents v0.x migration guide | LiveKit Docs | Agents 0.x migration guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | Voice pipeline nodes | LiveKit Docs
f
I'm not 'married' to using llm_node , I just want a solution that will works, is supported and the simplest to implement.
t
If you're looking for a simple, supported, and effective solution, the
llm_node
is definitely a great pick. It lets you preprocess the chat context on the fly before sending it to the LLM, which keeps things flexible and plays nicely with LiveKit's setup. I'd be happy to share an easy example of how to override the
llm_node
method to add speaker mappings or tweak the context in other ways. Just let me know if you'd like me to walk you through it!
f
yes please
t
Here’s a friendly example to show you how you can override the
llm_node
method to tweak the chat context on the fly before sending it off to the LLM:
Copy code
from livekit.agent import Agent

class CustomAgent(Agent):
    async def llm_node(self, chat_ctx, tools, model_settings):
        # Just a quick example: adding speaker mappings into the chat context
        speaker_mapping = {
            "S1": "Alice",
            "S2": "Bob"
        }

        # Let’s update the chat context dynamically
        for message in chat_ctx.messages:
            if "speaker_id" in message:
                speaker_id = message["speaker_id"]
                if speaker_id in speaker_mapping:
                    message["text"] = f"{speaker_mapping[speaker_id]}: {message['text']}"

        # Now, we call the original method with our updated context
        return await super().llm_node(chat_ctx, tools, model_settings)

# Here’s how you create and use your custom agent
agent = CustomAgent()
This snippet shows you how to add speaker names into
chat_ctx.messages
before it goes to the LLM. Feel free to tweak it to fit what you need! And hey, if anything’s unclear or you want to dive deeper, just ask—I’m here to help!