jolly-eve-3916
08/26/2025, 5:51 AMpython
_# 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
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:
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:
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):
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:
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?tall-airline-16756
08/26/2025, 5:51 AMtall-airline-16756
08/26/2025, 5:51 AMjolly-eve-3916
08/26/2025, 6:04 AMtall-airline-16756
08/26/2025, 6:05 AMagent.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.pyjolly-eve-3916
08/26/2025, 6:06 AMparticipant.attributes["voice"] lets you smoothly change voices mid-session.tall-airline-16756
08/26/2025, 6:06 AMparticipant.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.tsxjolly-eve-3916
08/26/2025, 6:08 AMpython
_# 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:
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:
python
class CoraAssistant(Agent):
def __init__(_self_):
super().__init__(_instructions_="You are Cora...") _# ← Can dispatch override this?_
Desired: Agent dispatch configures instructions dynamically:
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:
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:
python
assistant = CoraAssistant(_chat_ctx_=initial_ctx)
session = AgentSession(_tts_=deepgram.TTS(_model_=voice_model))
With dispatch configuration:
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!
---tall-airline-16756
08/26/2025, 6:08 AMcustom_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 Docsjolly-eve-3916
08/26/2025, 6:48 AMtypescript
_// 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
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
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:
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!tall-airline-16756
08/26/2025, 6:49 AMctx.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