Best Practice for Dynamic Agent Identity Based on ...
# ask-ai
j
Best Practice for Dynamic Agent Identity Based on User Preferences - Constructor vs Conversation Context** --- Hi LiveKit team, We're implementing dynamic voice selection where users can choose different AI personalities (Cora, Gabriel, Leo, etc.) that should match their selected voice model. We have two potential approaches and would love your guidance on the best practice. ## Current Architecture ### Agent Creation Flow
Copy code
python
_# Current agent creation in entrypoint_
async def entrypoint(_ctx_: JobContext):
    _# 1. Create agent with hardcoded identity_
    assistant = CoraAssistant(_chat_ctx_=initial_ctx)  _# ← Agent created here_

    _# 2. Later: Get participant metadata_
    participant = _await_ ctx.wait_for_participant()
    voice_model = participant_metadata.get('voiceModel', 'aura-2-cora-en')

    _# 3. Create session with dynamic voice_
    session = AgentSession(
        _tts_=deepgram.TTS(_model_=voice_model),  _# ← Dynamic TTS works_
    )
### Current Agent Constructor
Copy code
python
class CoraAssistant(Agent):
    def __init__(_self_, _chat_ctx_: llm.ChatContext = None):
        super().__init__(
            _chat_ctx_=chat_ctx _or_ llm.ChatContext(),
            _llm_=anthropic.LLM(_model_="claude-sonnet-4-20250514"),
            _instructions_="""You are Cora, a supportive AI reflection guide..."""  _# ← Hardcoded_
        )
## The Challenge ### User Voice Selection Scenario - User selects "Gabriel" voice (male, warm voice) - Agent should identify as Gabriel (not Cora) - Voice model works (gets male voice sound) - But instructions still say "You are Cora" (gender mismatch) ## Two Potential Approaches ### Approach 1: Agent Restructuring (Constructor Timing) Restructure agent creation to happen after metadata:
Copy code
python
async def entrypoint(_ctx_: JobContext):
    _# 1. Get participant metadata first_
    participant = _await_ ctx.wait_for_participant()
    voice_model = participant_metadata.get('voiceModel', 'aura-2-cora-en')
    voice_name = get_voice_name_from_model(voice_model)  _# Gabriel, Leo, etc._

    _# 2. Create agent with dynamic identity_
    assistant = CoraAssistant(_chat_ctx_=initial_ctx, _voice_name_=voice_name)

    _# 3. Create session_
    session = AgentSession(_tts_=deepgram.TTS(_model_=voice_model))
Modified agent constructor:
Copy code
python
class CoraAssistant(Agent):
    def __init__(_self_, _chat_ctx_: llm.ChatContext = None, _voice_name_: str = "Cora"):
        super().__init__(
            _instructions_=f"""You are {voice_name}, a supportive AI reflection guide..."""  _# ← Dynamic_
        )
### Approach 2: Conversation Context (Current Pattern) Use conversation context for identity (same pattern as other instructions):
Copy code
python
_# After metadata is available, add identity to conversation context_
voice_name = get_voice_name_from_model(voice_model)

initial_ctx.add_message(
    _role_="user",
    _content_=f"Your name is {voice_name}. Please introduce yourself as {voice_name}."
)
initial_ctx.add_message(
    _role_="assistant",
    _content_=f"Hello! I'm {voice_name}, and I'm here to support you."
)

_# Agent created with context containing identity_
assistant = CoraAssistant(_chat_ctx_=initial_ctx)  _# ← Existing timing, enhanced context_
## Questions for LiveKit ### 1. Agent Construction Timing Best Practices Is it advisable to: - Defer agent creation until after participant metadata is available? - Create agents before
ctx.wait_for_participant()
for performance reasons? - Restructure entrypoint flow to get metadata before agent creation? ### 2. Dynamic Agent Identity Patterns What's the recommended approach for dynamic agent identity: - Constructor-level identity setting (Approach 1)? - Conversation context identity setting (Approach 2)? - Alternative patterns we haven't considered? ### 3. Performance and Architecture Considerations For Approach 1 (agent restructuring): - Performance impact of deferring agent creation? - Best practices for agent initialization timing? - Any architectural concerns with metadata-dependent agent creation? For Approach 2 (conversation context): - Impact of additional context messages on performance? - LLM processing of identity instructions vs built-in identity? - Context window considerations for identity messages? ### 4. Agent Session Integration Current working pattern:
Copy code
python
_# This works perfectly - TTS model is dynamic_
session = AgentSession(_tts_=deepgram.TTS(_model_=voice_model))
Should agent identity follow the same pattern (set at session creation time)? ### 5. Alternative Approaches Are there other LiveKit patterns for: - Dynamic agent personality based on user preferences? - Runtime agent configuration changes? - Agent identity management in multi-persona applications?
t
Thanks for reaching out, Albert. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you set up a dynamic agent identity based on user preferences, here are some friendly tips and things to keep in mind: • Agent Construction Timing: It’s best to use explicit agent dispatch during token generation. This way, your agent is all set up with the right settings by the time the user connects, which helps keep things running smoothly without any delays. • Dynamic Identity Patterns: You can assign custom participant identities and update media on the fly. For example, using participant attributes or RPC (Remote Procedure Call) lets you tweak the agent’s voice, style, or instructions while it’s running—pretty handy, right? • Performance Considerations: To keep things speedy, try preloading models like TTS and take advantage of LiveKit’s low-latency dispatch system. Also, avoid reconnecting unnecessarily by only updating what really needs to change when you switch up the agent’s identity or media. • Alternative Approaches: Another idea is to use dynamic tool configuration or identity replacement patterns to make runtime adjustments. You can also let users update their preferences through UI controls for a more interactive experience. Following these tips will help create a smooth, responsive experience for your users while keeping your setup efficient. If you want to dive deeper into any of these, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | avatars/hedra/dynamically_created_avatar/agent.py | web/src/components/configuration-form.tsx | Protocol & WebRTC | livekit/livekit_composite | DeepWiki | Dispatching agents | LiveKit Docs
j
I need │ │ │ │ clarification on several implementation details: │ │ │ │ │ │ │ │ 1. Agent Dispatch Metadata vs Participant Metadata │ │ │ │ │ │ │ │ Current: We pass voice settings via participantMetadata to agents │ │ │ │ Question: How does agent dispatch metadata relate to participant │ │ │ │ metadata? Are they different systems? │ │ │ │ │ │ │ │ 2. Dynamic Agent Instructions via Dispatch │ │ │ │ │ │ │ │ LiveKit mentioned: "assign custom participant identities and update │ │ │ │ media on the fly" │ │ │ │ Question: Can we pass dynamic agent instructions through dispatch │ │ │ │ metadata? How does this work with Agent constructor instructions? │ │ │ │ │ │ │ │ 3. Agent Dispatch Integration with Current System │ │ │ │ │ │ │ │ Current: We use AgentDispatchClient.createDispatch() but only for │ │ │ │ agent selection │ │ │ │ Question: How to extend current dispatch to include voice identity │ │ │ │ configuration? Does dispatch metadata affect agent behavior? │ │ │ │ │ │ │ │ 4. Runtime Voice Identity Changes │ │ │ │ │ │ │ │ LiveKit mentioned: "RPC lets you tweak the agent's voice, style, or │ │ │ │ instructions while it's running" │ │ │ │ Question: Can users change voice identity mid-conversation? How to │ │ │ │ implement voice switching during active session? │ │ │ │ │ │ │ │ 5. Participant Attributes vs Dispatch Metadata │ │ │ │ │ │ │ │ LiveKit mentioned: "using participant attributes or RPC" │ │ │ │ Question: What's the difference between participant attributes and │ │ │ │ dispatch metadata for voice identity? Which approach is better? │ │ │ │ │ │ │ │ 6. Agent Constructor vs Runtime Configuration │ │ │ │ │ │ │ │ Question: If we configure identity via dispatch, do we still need │ │ │ │ Agent constructor changes? Or can runtime configuration override │ │ │ │ constructor instructions? │ │ │ │ │ │ │ │ 7. Performance and Preloading │ │ │ │ │ │ │ │ LiveKit mentioned: "preloading models like TTS" │ │ │ │ Question: How to preload TTS models for multiple voice options? │ │ │ │ Should we configure multiple TTS instances or switch dynamically? │ │ │ │ │ │ │ │ These clarifications will help determine the optimal implementation │ │ │ │ approach for dynamic voice identity based on LiveKit's recommended │ │ │ │ patterns.
t
Thanks for your questions! Here’s a friendly breakdown and some tips to help you out: 1. Agent Dispatch Metadata vs Participant Metadata: Think of dispatch metadata as the agent’s setup info at the start (like user ID or phone number)—once set, it stays fixed. Participant metadata is more flexible and tied to each room participant, so you can update things like voice preferences on the fly during the session. 2. Dynamic Agent Instructions via Dispatch: You can include initial instructions in the dispatch metadata, but don’t worry—you’re not stuck with those! You can tweak the agent’s behavior anytime using methods like
agent.update_instructions()
. 3. Extending Dispatch for Voice Identity: While you can set a starting voice identity with dispatch metadata, switching voices dynamically works best through participant attributes. For example, updating
participant.attributes["voice"]
lets you smoothly change voices mid-session. 4. Runtime Voice Identity Changes: If users want to switch voices during a conversation, updating the TTS options dynamically is the way to go. Just make sure the voice change happens between speech turns to keep things glitch-free. 5. Participant Attributes vs Dispatch Metadata: Use dispatch metadata for the initial setup, and lean on participant attributes when you want to make things interactive and change stuff in real time, like switching voices. 6. Agent Constructor vs Runtime Configuration: The constructor is great for setting defaults, but runtime methods like
update_instructions()
and
update_tools()
give you the flexibility to update things without restarting your agent. 7. Preloading TTS Models for Multiple Voice Options: To keep things running smoothly, use the
prewarm()
function to load TTS models and voice data when the worker starts up. This helps reduce any lag when switching voices later on. I hope this helps! If you want me to dive deeper or share some code snippets for any of these points, just let me know—I’m here to help. Sources: livekit-agents/livekit/agents/worker.py | Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | Making calls using SIP | LiveKit Docs | agent/main.py
j
does this change the voice of the participant or the voice of the agent? Extending Dispatch for Voice Identity: While you can set a starting voice identity with dispatch metadata, switching voices dynamically works best through participant attributes. For example, updating
participant.attributes["voice"]
lets you smoothly change voices mid-session.
t
Just a quick heads-up: when you update
participant.attributes["voice"]
, it actually changes the voice of the agent, not the participant. Think of it as the participant sending a little note to the agent, asking it to switch up its TTS (text-to-speech) voice for replies. The participant’s own audio or voice stays just as it is. If you want, I’m happy to walk you through it with some examples or clear things up further—just let me know! Sources: frontend/src/components/Assistant.tsx
j
Agent Dispatch Implementation Details ## Follow-up Questions for LiveKit Support Subject: Agent Dispatch Metadata and Dynamic Voice Identity - Implementation Clarification --- Hi LiveKit team, Thank you for the guidance on using agent dispatch for dynamic identity! We have several follow-up questions to clarify the implementation details for our voice selection system. ## Background Context ### Current Implementation We currently use:
Copy code
python
_# Agent dispatch for agent selection_
dispatch = _await_ dispatchClient.createDispatch(
    roomName,
    agentName,  _# cora-voice-agent or cora-ptt-agent_
    { metadata: JSON.stringify({ mode, threadId, patientId }) }
)

_# Participant metadata for voice configuration_
participantMetadata = { voiceModel, voiceSettings, ... }
_# Agent reads this via participant.metadata_
### Goal Configure agent identity (name) dynamically based on user voice selection while maintaining our existing voice model configuration. ## Specific Implementation Questions ### 1. Agent Dispatch Metadata vs Participant Metadata Current setup: We pass voice configuration via
participantMetadata
to agents Your recommendation: Use "explicit agent dispatch during token generation" Questions: - How does agent dispatch metadata differ from participant metadata? - Should voice identity go in dispatch metadata or participant metadata? - Can agents access both dispatch metadata and participant metadata? Example:
Copy code
python
_# Dispatch metadata (agent configuration)_
dispatch_metadata = { voice_identity: "Gabriel", agent_instructions: "You are Gabriel..." }

_# Participant metadata (session configuration)_  
participant_metadata = { voiceModel: "aura-2-draco-en", voiceSettings: {...} }
### 2. Dynamic Agent Instructions via Dispatch Question: Can agent dispatch metadata include custom instructions that override the Agent constructor? Current agent constructor:
Copy code
python
class CoraAssistant(Agent):
    def __init__(_self_):
        super().__init__(_instructions_="You are Cora...")  _# ← Can dispatch override this?_
Desired: Agent dispatch configures instructions dynamically:
Copy code
python
_# In token generator_
dispatch_metadata = {
    custom_instructions: "You are Gabriel, a supportive AI reflection guide..."
}
### 3. Agent Access to Dispatch Configuration How do agents access dispatch metadata? - Available via
ctx.job.metadata
? - Different from
participant.metadata
? - Timing: Available immediately when agent starts? Example access pattern:
Copy code
python
_# In agent entrypoint_
async def entrypoint(_ctx_: JobContext):
    dispatch_config = ctx.job.metadata  _# ← How to access dispatch metadata?_
    voice_identity = dispatch_config.get('voice_identity')
### 4. Integration with Current Agent Creation Current pattern:
Copy code
python
assistant = CoraAssistant(_chat_ctx_=initial_ctx)
session = AgentSession(_tts_=deepgram.TTS(_model_=voice_model))
With dispatch configuration:
Copy code
python
_# How to integrate dispatch metadata with agent creation?_
dispatch_config = get_dispatch_metadata()  _# ← How to get this?_
assistant = create_dynamic_agent(dispatch_config, initial_ctx)
session = AgentSession(_tts_=deepgram.TTS(_model_=voice_model))
### 5. Runtime Voice Identity Updates You mentioned: "RPC lets you tweak the agent's voice, style, or instructions while it's running" Questions: - Can users switch voice identity mid-conversation? - RPC methods for updating agent identity during session? - Best practices for seamless voice identity transitions? ### 6. Performance Optimization You mentioned: "preloading models like TTS" Questions: - Should we preload multiple TTS models for different voices? - Dynamic TTS switching vs multiple preloaded instances? - Dispatch-time optimization for voice configuration? ## Current Working Systems ### What Works Well ✅ - Voice model selection (dynamic TTS via participant metadata) - Voice timing settings (dynamic session configuration) - Agent dispatch (correct agent selection per mode) ### What Needs Enhancement - Voice identity consistency (agent should identify with selected voice) - Gender-appropriate identity (male voices saying "I'm Gabriel" not "I'm Cora") ## Use Case Requirements Mental health therapy app where: - Users select voice personality (Cora, Gabriel, Leo, Emma, etc.) - Agent identity must match selected voice (gender consistency critical) - Therapeutic rapport depends on consistent identity - Professional quality expected for sensitive conversations ## Request Could you provide: 1. Specific implementation guidance for agent dispatch metadata 2. Code examples showing dispatch metadata access in agents 3. Best practices for dynamic agent identity configuration 4. Performance recommendations for voice preloading and switching We're excited to implement this properly using LiveKit's recommended patterns! Thank you for your continued excellent support! ---
t
Here are some detailed answers and recommendations to help with your follow-up questions: 1. Agent Dispatch Metadata vs Participant Metadata: Think of dispatch metadata as the agent’s setup instructions at the very start — once set, they can’t be changed. Participant metadata, on the other hand, is tied to each room participant and can be updated on the fly during the session. So, if you want to set the voice identity right from the beginning, put it in dispatch metadata. But if you want to tweak things while the session is running, participant metadata is your friend. 2. Dynamic Agent Instructions via Dispatch: You can include custom instructions right in the dispatch metadata to override how the agent behaves. For instance, by passing
custom_instructions
in dispatch metadata, you can shape the agent’s behavior dynamically as it initializes. 3. Agent Access to Dispatch Configuration: Agents can grab the dispatch metadata easily through
ctx.job.metadata
in their entrypoint. This info is ready to go as soon as the agent starts up. 4. Integration with Current Agent Creation: When creating agents, use dispatch metadata to configure them dynamically. Just pull the metadata with
ctx.job.metadata
and feed it into the agent constructor or initialization steps. 5. Runtime Voice Identity Updates: Want to change the voice mid-conversation? No problem! Just update the participant attributes like
participant.attributes["voice"]
. You can listen for changes with events such as
participant_attributes_changed
and update the TTS voice on the fly. 6. Performance Optimization: To keep things running smoothly, preload your TTS models and voice metadata during the
prewarm()
function. If you’re working with multiple voices, preload all the necessary models upfront and switch between them dynamically when needed. These tips follow LiveKit’s best practices for managing dynamic agent identities and boosting performance. If you’d like, I’m happy to share some specific code examples or clarify any of these points further—just let me know! Sources: Job lifecycle | LiveKit Docs | Dispatching agents | LiveKit Docs | agent/main.py | Agent dispatch | LiveKit Docs
j
Accessing Dispatch Metadata via ctx.job.metadata - API Clarification** --- Hi LiveKit team, Following up on your guidance about using dispatch metadata for agent configuration, I have a specific question about accessing dispatch metadata in agents. ## Implementation Context ### Current Dispatch Creation (Working)
Copy code
typescript
_// In livekit-token-generator.ts_
const dispatch = await dispatchClient.createDispatch(
  roomName,
  agentName,
  { metadata: JSON.stringify({ mode, threadId, patientId }) }  _// Current working dispatch_
);
### Proposed Extension for Voice Identity
Copy code
typescript
const dispatch_metadata = {
  mode, threadId, patientId,  _// Existing_
  voice_name: "Gabriel",      _// New: voice identity_
  custom_instructions: "You are Gabriel, a supportive AI reflection guide..."  _// New: dynamic instructions_
};

const dispatch = await dispatchClient.createDispatch(
  roomName,
  agentName,
  { metadata: JSON.stringify(dispatch_metadata) }
);
## Agent Access Question ### Current Agent Code
Copy code
python
_# In agent entrypoint - we already access ctx.job successfully_
async def entrypoint(_ctx_: JobContext):
    logger.info(f"Job ID: {ctx.job.id}")  _# ← This works_

    _# Proposed: Access dispatch metadata_
    dispatch_config = json.loads(ctx.job.metadata) _if_ ctx.job.metadata _else_ {}  _# ← Will this work?_
    voice_name = dispatch_config.get('voice_name', 'Cora')
## Specific Questions ### 1. ctx.job.metadata Availability Is
ctx.job.metadata
the correct way to access dispatch metadata?
- Does
ctx.job.metadata
contain the metadata passed to
createDispatch()
? - Is this metadata available immediately when the agent entrypoint starts? - Any difference between
ctx.job.metadata
and the dispatch metadata we send? ### 2. Metadata Structure How is the dispatch metadata structured in ctx.job.metadata? - Is it already JSON parsed or still a string requiring
json.loads()
? - Does the metadata structure match what we send in
createDispatch()
? - Any additional fields or wrapper objects to be aware of? ### 3. Error Handling Best practices for accessing dispatch metadata safely:
Copy code
python
_# Is this the right error handling pattern?_
_try_:
    dispatch_config = json.loads(ctx.job.metadata) _if_ ctx.job.metadata _else_ {}
    voice_name = dispatch_config.get('voice_name', 'Cora')
_except_ (json.JSONDecodeError, AttributeError) _as_ e:
    logger.error(f"Error parsing dispatch metadata: {e}")
    voice_name = 'Cora'  _# Fallback_
### 4. Alternative Access Methods Are there other ways to access dispatch configuration? - Alternative APIs for dispatch metadata access? - Different timing or access patterns we should consider? - Any performance considerations for metadata access? ## Use Case Context Mental health therapy app where: - Voice identity must be consistent (Gabriel voice says "I'm Gabriel") - 7 different voice personalities need dynamic configuration - Dispatch metadata will contain voice_name and custom_instructions - Reliable access to dispatch configuration essential ## Current Status Working elements: - ✅ Agent dispatch system working perfectly - ✅ ctx.job.id access confirmed working - ✅ Dispatch metadata creation in token generator Need clarification: - ❓ ctx.job.metadata structure and access pattern - ❓ Metadata parsing and error handling best practices ## Request Could you confirm: 1. Correct API for accessing dispatch metadata in agents 2. Metadata structure and parsing requirements 3. Best practices for safe metadata access and error handling 4. Any gotchas or considerations for dispatch metadata usage This will help us complete our dynamic voice identity implementation using the proper LiveKit APIs! Thank you for your excellent guidance so far!
t
Here are some helpful answers and best practices for working with
ctx.job.metadata
in LiveKit agents: 1. Availability of `ctx.job.metadata`: Yep,
ctx.job.metadata
holds the metadata you pass to
createDispatch()
. It’s ready to go as soon as your agent’s entrypoint starts and will exactly match what you sent during dispatch. 2. Metadata Structure: The metadata comes as a string inside the
Job
message. If you’re sending JSON, just remember to parse it with
json.loads()
. The structure will be exactly what you sent in
createDispatch()
, without any extra wrapper objects. 3. Error Handling Best Practices: `import json try: dispatch_config = json.loads(ctx.job.metadata) if ctx.job.metadata else {} voice_name = dispatch_config.get('voice_name', 'Cora') except (json.JSONDecodeError, AttributeError) as e: logger.error(f"Error parsing dispatch metadata: {e}") voice_name = 'Cora' # Fallback`It’s a good idea to always validate your JSON and check for the keys you need to keep things running smoothly without surprises. 4. Alternative Access Methods:
ctx.job.metadata
is your go-to for accessing dispatch metadata. There aren’t other APIs for this, so just make sure your metadata is passed correctly during dispatch to keep everything reliable. If you want me to walk through any part of this or need examples tailored to your setup, just let me know—I’m here to help! Sources: telephony/survey_caller/survey_calling_agent.py | livekit-agents/livekit/agents/job.py | External data and RAG | LiveKit Docs | Job lifecycle | LiveKit Docs | Agent dispatch | LiveKit Docs