fierce-answer-55580
08/27/2025, 8:13 AMtall-airline-16756
08/27/2025, 8:13 AMtall-airline-16756
08/27/2025, 8:14 AMlivekit-rtc) to manage audio streams yourself?
• Which external STT, LLM, and TTS services are you planning to connect with?
• Do you need real-time streaming, or would batch processing work for you? Sources: VoicePipelineAgent | LiveKit Docs | agent/main.py | chain-of-thought-tts/agent.py | agents/src/pipeline/pipeline_agent.ts | agent-examples/agent_examples/pipeline_agent.pyfierce-answer-55580
08/27/2025, 8:16 AMtall-airline-16756
08/27/2025, 8:17 AMagent_name in WorkerOptions. Then, you can use the AgentDispatchService to send the agent to the room once the user has joined. Another option is to set up the participant’s access token with a RoomConfiguration that includes the agent.
• Passing Metadata: Just use the metadata field inside the RoomAgentDispatch object. This metadata will be available in the agent’s JobContext.job.metadata. Using JSON is a great way to keep your data structured and easy to work with.
Here’s a quick example of how you might set up a participant token with room configuration:
at.roomConfig = new RoomConfiguration({
agents: [
new RoomAgentDispatch({
agentName: 'test-agent',
metadata: '{"user_id": "123", "name": "Alice"}',
}),
],
});
So, when the user joins with this token, the agent will automatically be dispatched to the room along with the metadata you provided. Pretty handy, right?
Sources: examples/agent_dispatch.py | Agent dispatch | LiveKit Docs | Dispatching agents | LiveKit Docs | Dispatching agents | LiveKit Docs | Authentication | LiveKit Docsfierce-answer-55580
08/27/2025, 8:18 AMtall-airline-16756
08/27/2025, 8:19 AMfierce-answer-55580
08/27/2025, 8:21 AMtall-airline-16756
08/27/2025, 8:22 AMagent_name field in WorkerOptions when you’re initializing your agent. This little tweak stops auto-dispatch for that agent:
opts = WorkerOptions(
entrypoint_fnc=entrypoint,
agent_name="my-agent", # This disables auto-dispatch
)
1. Manually Dispatch Agents with Metadata: You’ll want to dispatch the agent yourself using one of these handy methods:
• Dispatch via API: Use the AgentDispatchService to create a dispatch request and include your metadata:
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": "12345"}'
)
)
print("created dispatch", dispatch)
• Dispatch on Participant Connection: Set up the participant’s access token to dispatch the agent with metadata as soon as they join:
def create_token_with_agent_dispatch() -> str:
token = (
AccessToken()
.with_identity("my_participant")
.with_grants(VideoGrants(room_join=True, room=room_name))
.with_room_config(
RoomConfiguration(
agents=[
RoomAgentDispatch(
agent_name="test-agent",
metadata='{"user_id": "12345"}'
)
],
),
)
.to_jwt()
)
return token
1. Grab Metadata Inside the Agent: When your agent starts, you can access the metadata right in the entrypoint function using ctx.job.metadata. Just decode it with json.loads to get your structured data:
async def entrypoint(ctx: JobContext):
metadata = json.loads(ctx.job.metadata)
user_id = metadata["user_id"]
logger.info(f"Agent started for user: {user_id}")
And that’s it! Following these steps will help you turn off auto-dispatch and work with metadata smoothly. If you have any questions or want to chat more about it, I’m here to help!
Sources: Dispatching agents | LiveKit Docs | Dispatching agents | LiveKit Docs | examples/agent_dispatch.py | External data and RAG | LiveKit Docs | External data and RAG | LiveKit Docsfierce-answer-55580
08/27/2025, 8:38 AMtall-airline-16756
08/27/2025, 8:39 AMWorkerOptions, it's super important to include run_app. Think of WorkerOptions as the setup for your worker, and run_app is the friendly helper that actually gets your worker up and running, whether you're developing or deploying.
Here's a quick example to guide you:
if __name__ == "__main__":
agents.cli.run_app(
agents.WorkerOptions(
entrypoint_fnc=start_session,
prewarm_fnc=prewarm,
ws_url=LIVEKIT_URL,
api_key=API_KEY,
api_secret=API_SECRET
)
)
Doing it this way makes sure your worker starts smoothly and everything runs as expected. Hope this helps!
Sources: runApp | LiveKit Agents | agents/src/worker.ts | Worker options | LiveKit Docs | Worker | LiveKit Agentsfierce-answer-55580
08/27/2025, 8:40 AMtall-airline-16756
08/27/2025, 8:40 AMrun_app with WorkerOptions and set the agent_name field, it won’t automatically send agents to rooms. Setting agent_name actually turns off automatic dispatch, so the agent will only join rooms if you explicitly tell it to, like through:
• The AgentDispatchService API
• Setting up participant access tokens
• Using SIP dispatch rules
Here’s a quick example showing how this disables automatic dispatch:
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
agent_name="my-agent" # Disables automatic dispatch
)
)
On the other hand, if you don’t set agent_name, the agent will hop into new rooms automatically.
Sources: Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | Agents telephony integration | LiveKit Docs | Making calls using SIP | LiveKit Docs | examples/minimal_worker.pyfierce-answer-55580
08/27/2025, 8:41 AMtall-airline-16756
08/27/2025, 8:42 AMJSONDecodeError happens because the metadata string you’re passing to the agent isn’t valid JSON. No worries though — here’s a simple way to fix it:
1. Make Sure Your JSON Is Properly Encoded: When you’re dispatching the agent, double-check that the metadata field is a valid JSON string. For example:
import json
from livekit.api import LiveKitAPI, CreateAgentDispatchRequest
metadata = json.dumps({
"user_name": "Alice",
"phone_number": "+1234567890",
"row_index": 1
})
dispatch = await LiveKitAPI().agent_dispatch.create_dispatch(
CreateAgentDispatchRequest(
agent_name="survey-agent",
room="my-room",
metadata=metadata
)
)
1. Handle Metadata Parsing with Care: It’s a good idea to wrap the json.loads() call in a try-except block. This way, if the input isn’t quite right, your code can handle it smoothly without crashing:
import json
import logging
async def entrypoint(ctx: JobContext):
logger = logging.getLogger("agent")
metadata_str = ctx.job.metadata
try:
metadata = json.loads(metadata_str)
user_name = metadata.get("user_name", "Unknown")
logger.info(f"Successfully parsed metadata for user: {user_name}")
except json.JSONDecodeError as e:
logger.error(f"Failed to decode job metadata as JSON: {e}")
metadata = {} # Fallback to empty dict or default values
# Proceed with agent logic using metadata
Following these steps will help make sure your metadata is formatted and parsed correctly, so you won’t run into that JSONDecodeError again. If you have any questions or need a hand, just let me know!
Sources: Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | telephony/survey_caller/survey_calling_agent.py | Job lifecycle | LiveKit Docsfierce-answer-55580
08/27/2025, 8:56 AMtall-airline-16756
08/27/2025, 8:56 AMRoomAgentDispatch, you’ll want to use the ctx.job.metadata field right in your agent’s entrypoint. Just a heads-up—the metadata comes as a string, so you’ll need to parse it with json.loads to get it into a handy structured format.
Here’s a quick example to make it clearer:
import json
async def entrypoint(ctx: JobContext):
metadata_str = ctx.job.metadata
try:
metadata = json.loads(metadata_str)
user_id = metadata.get("user_id", "Unknown")
print(f"Agent received user_id: {user_id}")
except json.JSONDecodeError as e:
print(f"Failed to parse metadata: {e}")
metadata = {} # Fallback to empty metadata
# Use the metadata as needed in your agent logic
Also, just make sure the metadata is properly JSON-encoded when you’re creating the token or dispatching the agent. For example:
token = AccessToken(
api_key=API_KEY,
api_secret=API_SECRET
).with_grants(
VideoGrants(
room=room.name,
room_join=True,
can_publish=True,
can_subscribe=True,
can_publish_data=True,
can_publish_sources=["microphone"],
can_update_own_metadata=True
)
).with_identity(user_id).with_room_config(
RoomConfiguration(
agents=[
RoomAgentDispatch(agent_name="Evi", metadata=json.dumps({"user_id": "12345"}))
]
)
).to_jwt()
This way, your metadata will be easy to access and perfectly formatted for your agent. Hope this helps!
Sources: Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | Job lifecycle | LiveKit Docs | protobufs/livekit_agent_dispatch.proto | examples/agent_dispatch.pyfierce-answer-55580
08/27/2025, 9:13 AMtall-airline-16756
08/27/2025, 9:13 AMctx.job.metadata) being empty or not valid JSON. Could you help me out by confirming a few things?
• How are you passing the metadata when creating the token or dispatching the agent?
• Is the metadata field set explicitly, and if yes, what value are you assigning?
• Have you checked if the metadata is a valid JSON string?fierce-answer-55580
08/27/2025, 9:13 AMtall-airline-16756
08/27/2025, 9:14 AMctx.job.metadata before parsing it. This can give us a clearer picture:
async def entrypoint(ctx: JobContext):
print(f"Raw metadata: {ctx.job.metadata}")
try:
metadata = json.loads(ctx.job.metadata)
print(f"Parsed metadata: {metadata}")
except json.JSONDecodeError as e:
print(f"Failed to parse metadata: {e}")
1. Check Metadata Dispatch: Double-check that the metadata is being passed correctly when you dispatch the agent. For example, make sure the metadata field in RoomAgentDispatch isn’t empty or malformed.
2. Validate Metadata: Before passing the metadata along, it’s a good idea to validate it to confirm it’s a valid JSON string:
try:
json.loads(metadata) # Validate JSON
except json.JSONDecodeError:
print("Invalid metadata JSON")
1. Inspect Room Configuration: Take a look at the room configuration to ensure the agent includes the correct metadata. You can print out the token or check the room details after creation to verify this.
Hopefully, these steps will help you pinpoint whether the hiccup is happening during metadata creation, dispatch, or parsing. Let me know how it goes or if you want to chat through it more!fierce-answer-55580
08/27/2025, 9:16 AMtall-airline-16756
08/27/2025, 9:16 AMctx.job.metadata is empty, so it can’t be parsed. This usually means the metadata isn’t getting passed to the agent properly. No worries though—here are some friendly steps to help you figure this out:
1. Double-check Metadata Assignment: Make sure the metadata variable is actually filled with the right info before you pass it to RoomAgentDispatch. For example:
metadata = json.dumps({
"voice_id": voice_id,
"session_id": session_id,
})
print(f"Metadata being passed: {metadata}")
1. Take a Look at Token Creation: Confirm that the RoomAgentDispatch object includes the metadata by printing out the token or checking the room setup like this:
print(f"Token: {token}")
1. Debug the Room Creation: See if the room creation is properly linking the agent and metadata. You can log the room details right after it’s created to double-check:
print(f"Room created: {room}")
1. Add a Fallback Just in Case: It’s a good idea to handle situations where metadata might be empty by adding a fallback in the agent, like this:
async def entrypoint(ctx: JobContext):
metadata_str = ctx.job.metadata or "{}" # Fallback to empty JSON
try:
metadata = json.loads(metadata_str)
print(f"Parsed metadata: {metadata}")
except json.JSONDecodeError as e:
print(f"Failed to parse metadata: {e}")
Hopefully, these tips help you spot what’s going on and get the metadata passing smoothly to the agent. If you hit any snags, just let me know—I’m here to help!fierce-answer-55580
08/27/2025, 9:49 AMtall-airline-16756
08/27/2025, 9:50 AMwss://<your-project>.livekit.cloud).
• LIVEKIT_API_KEY: This key helps you authenticate your API requests.
• LIVEKIT_API_SECRET: This secret works with your API key to sign tokens securely.
Make sure to keep these credentials safe in your environment files (for example, .env.local).
Do the credentials need to match between the token server and the agent? Yes, they do! The LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET should be exactly the same on both the token server and the agent. This way, they’ll authenticate properly and connect to the same LiveKit project without any hiccups.
Use these credentials in both places:
• The token server to create access tokens.
• The agent to connect and work with rooms.
Keeping everything consistent will help you avoid any authentication or connection troubles. If you run into any issues, feel free to reach out!
Sources: Authentication Examples | livekit/livekit_composite | DeepWiki | Next.js quickstart | LiveKit Docs | agent/.env.example | examples/.env.example | .env.examplefierce-answer-55580
08/27/2025, 9:55 AMtall-airline-16756
08/27/2025, 9:55 AMwss://<your-project>.livekit.cloud).
• LIVEKIT_API_KEY: Your API key for authentication.
• LIVEKIT_API_SECRET: The secret key you’ll use to sign tokens.
Make sure to copy and keep these credentials somewhere safe—they’re important for setting up your token server and agent configuration. If you need a hand, we’re here to help!fierce-answer-55580
08/27/2025, 10:00 AMtall-airline-16756
08/27/2025, 10:01 AMagentName in WorkerOptions exactly matches the agent_name in your dispatch rule. If these don’t line up, the worker won’t get any jobs.
2. Verify Worker Registration: Double-check that your worker is properly registered with the LiveKit server. You should see logs showing a registered worker ID and a confirmed connection.
3. Inspect WebSocket Connection: Confirm the worker is connecting to the right LIVEKIT_URL and that the WebSocket connection is steady and reliable.
4. Environment Variables: Take a moment to verify that LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET are all correctly set up in the worker’s environment.
5. Logs: Peek at the worker logs for any errors or warnings—they often hold clues about why jobs aren’t coming through.
Hopefully, these tips help you pinpoint and fix the issue. If you want, I’m here to help you dig into any of these steps more deeply—just let me know!
Sources: livekit-agents/livekit/agents/worker.py | Deploying to production | LiveKit Docs | SIP troubleshooting guide | LiveKit Docs | Anatomy of an Agent | LiveKit Docs | pkg/service/agentservice.gofierce-answer-55580
08/27/2025, 11:49 AMtall-airline-16756
08/27/2025, 11:50 AMagent_name in RoomAgentDispatch ("Evi") exactly matches the agentName you set in the worker's WorkerOptions. If these don’t line up, the worker won’t get the job.
2. Metadata: Check that the metadata you’re passing is a valid JSON string. A handy trick is to log it right before dispatching, just to be sure it’s formatted correctly:
print(f"Dispatching with metadata: {metadata}")
1. Worker Logs: Take a peek at the worker logs to confirm it’s connected to the LiveKit server and has registered properly. Look out for any messages that say the worker is ready to receive jobs.
2. Dispatch Confirmation: It’s also a good idea to log the response from the dispatch_agent call to verify the dispatch request went through successfully:
response = await lkapi.room.dispatch_agent(...)
print(f"Dispatch response: {response}")
Following these steps should help pinpoint why the agent worker isn’t getting the job. If you want, I’m here to help you troubleshoot further!