fierce-answer-55580
08/26/2025, 2:29 PMtall-airline-16756
08/26/2025, 2:29 PMtall-airline-16756
08/26/2025, 2:29 PMsetAttributes() on the local participant like this:
room.localParticipant.setAttributes({ 'user.role': 'moderator' });
2. Backend (Server SDK): You can grab those attributes by using the ListParticipants API:
import { RoomServiceClient } from 'livekit-server-sdk';
const roomService = new RoomServiceClient('ws://your-livekit-server', 'API_KEY', 'API_SECRET');
const participants = await roomService.listParticipants('your-room-name');
participants.forEach(p => {
console.log('Attributes:', p.attributes);
});
3. Backend (AI Agents): If you’re working with AI agents, access the attributes right inside the agent’s entrypoint function like this:
from livekit import rtc
async def entrypoint(ctx: JobContext):
participant = await ctx.wait_for_participant()
language = participant.attributes.get("user.language")
print(f"Participant language: {language}")
@ctx.room.on("participant_attributes_changed")
def on_attributes_changed(changed_attributes: dict, p: rtc.Participant):
if p == participant:
print("Attributes changed:", p.attributes)
One quick heads-up: make sure your participants have the canUpdateOwnMetadata permission in their token so they can set attributes. For all the details, you can check out the Participant Attributes documentation. Hope this helps!
Sources: livekit/src/room/participant/mod.rs | Job lifecycle | LiveKit Docs | Participant attributes and metadata | LiveKit Docsfierce-answer-55580
08/26/2025, 3:06 PMtall-airline-16756
08/26/2025, 3:07 PMroom.localParticipant.setAttributes inside the onConnected callback looks spot on. Just a few friendly reminders to keep everything running smoothly:
• The setAttributes method updates only the keys you provide—it won’t overwrite other existing attributes, so your data stays safe.
• Make sure the participant's token has the canUpdateOwnMetadata permission; otherwise, updates won’t go through.
• Attributes sync across all participants in the room, and you can grab them anytime via participant.attributes.
• Keep in mind there’s a 64 KiB limit for all attributes combined (keys and values together).
• Try not to update attributes too often (not more than once every few seconds) to avoid extra server load.
Here’s your code snippet again for reference:
<LiveKitRoom
audio={true}
video={false}
token={details.token}
serverUrl={details.url}
onConnected={(room) => {
console.log("🔗 Connected to LiveKit, setting sessionId...");
if (room.localParticipant && sessionId) {
room.localParticipant.setAttributes({ sessionId });
console.log("✅ Sent sessionId:", sessionId);
}
}}
>
<LKRoom />
</LiveKitRoom>
This should work just fine! But if you run into any hiccups or have questions, just give me a shout—I’m here to help.
Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/participant/Local... | src/room/participant/LocalParticipant.ts | Participant attributes and metadata | LiveKit Docs | Runtime/Scripts/Participant.cs | lib/src/participant/local.dartfierce-answer-55580
08/26/2025, 3:13 PMtall-airline-16756
08/26/2025, 3:14 PMconst token = new AccessToken(apiKey, apiSecret, {
identity: 'user123',
name: 'John Doe',
attributes: {
role: 'admin',
theme: 'dark'
}
});
If you want, I’m here to help with anything else you might need!
Sources: Participant attributes and metadata | LiveKit Docs | packages/livekit-server-sdk/src/AccessToken.ts | README.mdfierce-answer-55580
08/26/2025, 3:15 PMtall-airline-16756
08/26/2025, 3:16 PMentrypoint function:
async def entrypoint(ctx: agents.JobContext):
metadata = json.loads(ctx.job.metadata)
voice_id = metadata.get("voice_id")
# Use voice_id to configure TTS or other services
tts = cartesia.TTS(model="sonic-2", voice=voice_id)
session = AgentSession(tts=tts, ...)
await session.start(room=ctx.room, agent=Assistant())
2. Participant Attributes: You can also set the voice ID as a participant attribute when the user joins the room. The agent can keep an ear out for any attribute changes and tweak its setup accordingly:
@ctx.room.on("participant_attributes_changed")
def on_participant_attributes_changed(changed_attributes: dict, participant: rtc.Participant):
if "voice" in changed_attributes:
voice_id = participant.attributes.get("voice")
# Update TTS voice
tts._opts.voice = voice_id
3. Room Metadata: Another way is to include the voice ID in the room metadata, especially if it’s the same for all participants.
Honestly, using job metadata tends to be the simplest and most direct way for what you’re aiming to do. But if you want to chat more about how to set it up or run into any bumps, just let me know—I’m here to help!
Sources: Handling RAG Delays in Voice Agents | LiveKit Docs | External data and RAG | LiveKit Docs | Job lifecycle | LiveKit Docs | agent/main.pyfierce-answer-55580
08/26/2025, 3:16 PMtall-airline-16756
08/26/2025, 3:17 PMfierce-answer-55580
08/26/2025, 3:18 PMtall-airline-16756
08/26/2025, 3:19 PMmetadata field of the access token. This works really well for structured data like JSON:
const at = new AccessToken(apiKey, apiSecret, {
identity: "user123",
metadata: JSON.stringify({
voice_id: "custom_voice_id_here",
instructions: "Respond in a friendly tone"
}),
});
2. Using Attributes: Another option is to add the voice ID as a key-value pair inside the attributes field:
const at = new AccessToken(apiKey, apiSecret, {
identity: "user123",
attributes: {
voice_id: "EXAVITQu4vr4xnSDxMaL",
},
});
Then, on the agent or client side, you can easily grab this info through:
• Participant.metadata if you used the metadata field
• Participant.attributes['voice_id'] if you went with the attributes field
If you run into any questions or want a hand setting this up, just give me a shout—I’m here to help!
Sources: ElevenLabs TTS integration guide | LiveKit Docs | ElevenLabs TTS integration guide | LiveKit Docs | web/src/app/api/token/route.ts | web/src/app/api/token/route.ts | packages/livekit-server-sdk/src/AccessToken.tsfierce-answer-55580
08/26/2025, 3:20 PMtall-airline-16756
08/26/2025, 3:21 PMfrom livekit import api
# Generate a token with metadata
token = (
api.AccessToken(api_key="your_api_key", api_secret="your_api_secret")
.with_identity("user123")
.with_name("John Doe")
.with_grants(
api.VideoGrants(
room_join=True,
room="my-room"
)
)
.with_metadata('{"voice_id": "custom_voice_id_here", "role": "admin"}') # Add metadata as a JSON string
.to_jwt()
)
print("Generated Token:", token)
Just a quick tip: make sure your metadata is serialized as a JSON string if you’re sending structured data. This way, the metadata will be included in the token and easily accessible to the participant or agent when they join the room.
If you have any questions or need a hand with anything else, feel free to ask!
Sources: cmd/lk/token.go | web/src/app/api/token/route.ts | Participant attributes and metadata | LiveKit Docs | README.mdfierce-answer-55580
08/26/2025, 3:23 PMtall-airline-16756
08/26/2025, 3:24 PMimport json
from livekit import agents
async def entrypoint(ctx: agents.JobContext):
# Grab metadata from the job context
metadata = json.loads(ctx.job.metadata)
voice_id = metadata.get("voice_id")
print(f"Voice ID: {voice_id}")
# Use the voice_id to do cool stuff
# For example: Set up TTS or other services
tts = cartesia.TTS(model="sonic-2", voice=voice_id)
session = AgentSession(tts=tts, ...)
await session.start(room=ctx.room, agent=Assistant())
In this snippet, the metadata comes as a JSON string inside the access token when it’s created. Your agent then parses it and uses it right when it starts.
If you want me to walk you through any part of this or need a hand, just give me a shout!
Sources: packages/livekit-server-sdk/src/AccessToken.test.ts | livekit-api/src/access_token.rs | livekit-api/livekit/api/access_token.pyfierce-answer-55580
08/26/2025, 3:52 PMtall-airline-16756
08/26/2025, 3:52 PMTokenVerifier class to decode and verify it. Here’s a quick example to get you started:
from livekit.api import TokenVerifier
# Set up the TokenVerifier with your API key and secret
verifier = TokenVerifier(api_key="your_api_key", api_secret="your_api_secret")
# Verify and decode the token
claims = verifier.verify(token="your.jwt.token.here")
# Now, access the metadata
metadata = claims.metadata
print("Participant metadata:", metadata)
The metadata field will have the string you added when creating the token. If you used JSON data, you can easily parse it with json.loads(metadata).
Feel free to reach out if you want me to walk you through anything else!
Sources: Authentication | LiveKit Docs | Participant attributes and metadata | LiveKit Docs | Participant attributes and metadata | LiveKit Docs | Participant attributes and metadata | LiveKit Docs | README.mdfierce-answer-55580
08/26/2025, 3:53 PMtall-airline-16756
08/26/2025, 3:54 PMvoice_id and session_id in your agent, you just need to pull and parse the metadata from the job context. Here’s a friendly little Python snippet to show you how:
import json
from livekit import agents
async def entrypoint(ctx: agents.JobContext):
# Grab the metadata from the job context
metadata = json.loads(ctx.job.metadata)
voice_id = metadata.get("voice_id")
session_id = metadata.get("session_id")
print(f"Voice ID: {voice_id}")
print(f"Session ID: {session_id}")
# Now you can use voice_id and session_id however you need
# For example: setting up TTS or other services
tts = cartesia.TTS(model="sonic-2", voice=voice_id)
session = AgentSession(tts=tts, ...)
await session.start(room=ctx.room, agent=Assistant())
This example works assuming your metadata comes in as a JSON string during token generation, just like in your example. Then your agent can easily parse out the voice_id and session_id and put them to good use.
If you want me to walk you through anything else or if something’s unclear, just give me a shout—I’m here to help!fierce-answer-55580
08/26/2025, 4:20 PMtall-airline-16756
08/26/2025, 4:21 PMon_participant_connected event looks spot on. The participant.metadata field is synced up and ready to go as soon as someone joins the room. Here’s a quick look at your code:
@ctx.room.on("participant_connected")
def on_participant_connected(participant: rtc.Participant) -> None:
nonlocal session_id, voice_id, session
logger.debug(f"PARTICIPANT CONNECTED {participant.metadata}")
if participant.metadata:
try:
meta = json.loads(participant.metadata)
session_id = meta.get("session_id")
voice_id = meta.get("voice_id")
logger.info(f"✅ Participant metadata: session_id={session_id}, voice_id={voice_id}")
except Exception as e:
logger.error(f"⚠️ Failed to parse metadata: {e}")
else:
logger.warning("⚠️ No metadata found on participant")
This way, you’re making sure to properly parse and log the metadata. And as long as the metadata is included in the access token when it’s created, you’ll see it in the participant.metadata field right when they connect.
If you want to chat more or need a hand with anything else, just let me know!
Sources: example/sample.ts | Inside a session | LiveKit Docs | Participant attributes and metadata | LiveKit Docs | src/room/events.ts | Participant attributes and metadata | LiveKit Docsfierce-answer-55580
08/26/2025, 4:26 PMtall-airline-16756
08/26/2025, 4:27 PMon_participant_connected event happens whenever someone joins the room successfully. It triggers for everyone, including you, and gives you all the details about the participant right when they connect.
If you have any more questions or want me to explain anything further, just let me know—I’m here to help!fierce-answer-55580
08/26/2025, 4:29 PMsessions array
doc_ref = db.collection("users").document(ctx.room.id)
doc_ref.update({
"sessions": firestore.ArrayUnion([session_data])
})
logger.info(_f_"✅ Session {session_id} saved to Firestore for user {ctx.room.id}")
except Exception as e:
logger.error(_f_"Error writing to Firestore: {e}")
ctx.add_shutdown_callback(write_to_firestore)
await session.start(
room=ctx.room,
agent=agent_instance,
_room_input_options_=RoomInputOptions(
audio_enabled=True,
video_enabled=False,
noise_cancellation=None,
),
)
async def run_agent(_metadata_: dict = {}) -> None:
ctx = agents.JobContext(metadata=json.dumps(metadata))
await start_session(ctx)
if name == "__main__":
agents.cli.run_app(
agents.WorkerOptions(entrypoint_fnc=start_session, prewarm_fnc=prewarm)
)tall-airline-16756
08/26/2025, 4:29 PMon_participant_connected event is doing a great job grabbing and parsing the metadata from the participant object. This means session_id and voice_id get updated on the fly whenever someone joins.
• The VOICE_MAP dictionary is nicely used to link the voice_id with the right voice setup, so the TTS works just right.
• The write_to_firestore function is smartly set as a shutdown callback to save all the session info, including the summary, to Firestore.
If you want to dive deeper or have any questions about any part of this, just let me know—I’m here to help!fierce-answer-55580
08/26/2025, 4:33 PMtall-airline-16756
08/26/2025, 4:34 PMimport asyncio
from livekit import api
async def create_explicit_dispatch():
lkapi = api.LiveKitAPI()
dispatch = await lkapi.agent_dispatch.create_dispatch(
api.CreateAgentDispatchRequest(
agent_name="test-agent",
room="my-room",
metadata='{"user_id": "123", "user_name": "Alice", "user_phone": "+1234567890"}' # JSON string
)
)
print("created dispatch", dispatch)
Then, in your agent, you can grab this metadata inside the entrypoint function like this:
import json
async def entrypoint(ctx: JobContext):
metadata = json.loads(ctx.job.metadata)
user_id = metadata["user_id"]
user_name = metadata["user_name"]
user_phone = metadata["user_phone"]
2. Via Participant Access Token:
async def create_token_with_agent_dispatch() -> str:
token = (
api.AccessToken()
.with_identity("my_participant")
.with_grants(api.VideoGrants(room_join=True, room=room_name))
.with_room_config(
api.RoomConfiguration(
agents=[api.RoomAgentDispatch(
agent_name="test-agent",
metadata='{"user_id": "123", "language": "en"}'
)],
),
)
.to_jwt()
)
return token
Just a quick tip: make sure the metadata is serialized as a JSON string using json.dumps() before sending, and then parse it with json.loads() in your agent. If you run into any questions or need a hand, feel free to ask—I'm here to help!
Sources: Agent dispatch | LiveKit Docs | Job lifecycle | LiveKit Docs | livekit-rtc/livekit/rtc/participant.pyfierce-answer-55580
08/26/2025, 5:13 PMtall-airline-16756
08/26/2025, 5:13 PMagent_name in your dispatch request exactly matches the name you used when registering the worker. Even a small difference can stop the worker from being assigned to the room.
• Make sure you're making the dispatch request correctly with the AgentDispatchService. Here's a quick example:
dispatch = await lkapi.agent_dispatch.create_dispatch(
api.CreateAgentDispatchRequest(
agent_name="test-agent",
room="my-room",
metadata='{"key": "value"}'
)
)
• Take a peek at the worker logs to confirm the worker is running and registered under the right agent_name.
• Also, check that the worker process is actively listening for dispatch requests and hasn’t been paused or stopped.
If you’ve gone through these steps and things still aren’t working, just let me know! I’m here to help you figure it out.
Sources: Agents telephony integration | LiveKit Docs | Agents telephony integration | LiveKit Docs | SIP troubleshooting guide | LiveKit Docs | Dispatching agents | LiveKit Docs | Dispatching agents | LiveKit Docsfierce-answer-55580
08/26/2025, 5:17 PMtall-airline-16756
08/26/2025, 5:18 PMagent_name in WorkerOptions: Make sure your agent is registered with the right agent_name (like "test-agent") in your worker setup. This helps you have clear control over dispatching.
2. Include Agent Dispatch in Access Token: When you generate the participant's access token, add the agent dispatch configuration inside the RoomConfiguration. Here’s an example:
at.roomConfig = new RoomConfiguration({
agents: [
new RoomAgentDispatch({
agentName: "test-agent",
metadata: '{"key": "value"}',
}),
],
});
1. Ensure the Agent Worker is Running: Double-check that the agent with the specified agent_name is up and running, and properly registered with the LiveKit server. If it’s not running, dispatch won’t work.
2. Use Metadata (Optional): You can pass extra info (like a user ID) through the metadata field — this will be available in the agent’s JobContext for added context.
If you hit any bumps or want a hand with anything else, just let me know! I’m here to help.
Sources: Agent dispatch | LiveKit Docs | Web and mobile frontends | LiveKit Docs | Dispatching agents | LiveKit Docs | examples/agent-dispatch/index.tsfierce-answer-55580
08/26/2025, 5:18 PMtall-airline-16756
08/26/2025, 5:18 PMagent_name ("Evi") exactly matches the name you have set up in the worker configuration. If they don’t match, the agent won’t get dispatched.
• Take a quick look at the metadata variable and confirm it’s a properly formatted JSON string. For example:
metadata = json.dumps({
"key": "value",
"another_key": "another_value"
})
• Verify that your agent worker is up and running, ready to listen for dispatch requests.
• Peek at the LiveKit server logs to see if the dispatch request is going through smoothly.
If the agent still isn’t joining the room, just let me know—we’ll figure it out together!fierce-answer-55580
08/26/2025, 5:23 PMtall-airline-16756
08/26/2025, 5:23 PMfierce-answer-55580
08/26/2025, 5:47 PM