If i am giving agent_name in `WorkerOptions` then...
# ask-ai
w
If i am giving agent_name in
WorkerOptions
then agent isn't joining the room i want it to :-
Copy code
token.with_room_config({
            RoomConfiguration(
                agents=[
                    RoomAgentDispatch(agent_name="local-agent", metadata='{"user_id": "12345"}')
                ],
            )
        })
Copy code
cli.run_app(WorkerOptions(
        entrypoint_fnc=entrypoint,
        prewarm_fnc=prewarm,
        # Configure for production deployment
        port=8081,  # Default port for most cloud platforms
        host="0.0.0.0",  # Listen on all interfaces
        # Note: agent_name is not set to allow automatic dispatch via RoomAgentDispatch
        # The agent will be filtered by the job_request_callback
        agent_name="local-agent",
    ))
t
Thanks for reaching out, Rahul. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
When you set
agent_name
in
WorkerOptions
, it turns off automatic dispatch. This means the agent won’t join rooms automatically, and instead, you’ll need to assign them explicitly using methods like the
create_dispatch
API or SIP dispatch rules that match the agent name. To help you move forward, you have two options: • Remove the
agent_name
from
WorkerOptions
to get automatic dispatch working again. • Or, use explicit dispatch methods to assign the agent to the room you want. If you’d like, I’m here to guide you through setting these up or answer any questions you have. Just let me know! Sources: Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | Agents telephony integration | LiveKit Docs | SIP troubleshooting guide | LiveKit Docs
w
I'm setting agent_name because i want to make sure while development my production agent don't join the room and vice-verse
t
To help keep your production and development agents from joining the same room, here are some friendly recommendations you can try: • Use separate LiveKit projects: Give each environment its own API credentials (URL, API key, and secret). This way, production and development stay nicely separated. • Enable explicit agent dispatch: By setting
agent_name
, you can manually assign agents to rooms using the
AgentDispatchService
API or room configuration in tokens. This helps avoid any accidental agent mix-ups. • Namespace-based routing: Assign agents to specific namespaces so they only work on jobs meant for their environment. • Use unique room names: Adding timestamps or UUIDs to room names is a simple way to prevent rooms from overlapping across environments. If you’d like, I’m here to help you implement any of these options or chat about what fits best for your setup. Just let me know! Sources: Managing participants | LiveKit Docs | Docs::Home | test/agent_test.go | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | Deployment and scaling | LiveKit Docs
w
can you explain 3rd and 4th point in detail, by adding a namespace i also have to add conditions in entrypoint of agent ryt to discard the not needed request?
t
I’d love to walk you through the 3rd and 4th points in a bit more detail: • Namespace-based routing: Assigning agents to specific namespaces is a great way to make sure they only handle jobs meant for their environment. For instance, you can set up your development agents to respond exclusively to jobs in a "dev" namespace, while production agents focus on a "prod" namespace. To get this going, you’d add some logic in the
entrypoint
or
request_fnc
of the agent to check the namespace of incoming requests and gracefully skip any that don’t match the agent’s assigned namespace. • Unique room names: To prevent any mix-ups with room names across different environments, try appending unique identifiers like timestamps or UUIDs to each room name. For example, instead of just "meeting-room," you might use "meeting-room-prod-20231010-12345" for production and "meeting-room-dev-20231010-67890" for development. This little tweak helps ensure that even if a room gets recreated, it won’t overlap with rooms from other environments. If you’d like, I’m here to help you implement these strategies or answer any questions you might have along the way.
w
can you give code for _`request_fnc`_ to check room_name and skip gracefully? in python
t
Here’s a friendly example of how you can use
request_fnc
in
WorkerOptions
to check the
room_name
and skip jobs gracefully in Python:
Copy code
async def request_fnc(req: JobRequest):
    # Access room information from the request
    room_name = req.room.room_name  # Get the room name from the request

    # Define logic to accept or reject based on room_name
    if room_name.startswith("allowed_"):
        await req.accept(
            name="agent",                  # Display name of the agent
            identity="agent-" + req.job_id,  # Unique identity for the agent
            attributes={"agent_type": "transcriber"}
        )
    else:
        # Reject the job gracefully; it will be dispatched to another worker
        await req.reject()

# Pass the request_fnc to WorkerOptions
opts = WorkerOptions(
    entrypoint_fnc=entrypoint,   # Your main agent logic
    request_fnc=request_fnc,     # Custom dispatch logic
    worker_type=WorkerType.ROOM
)

cli.run_app(opts)
Key Details:
req.room.room_name
is used to check the room name. •
await req.reject()
helps you skip the job gracefully, so other workers can take it on. • If you don’t define
request_fnc
, the worker will accept all jobs by default. Please feel free to reach out if you’d like me to explain anything further or help tailor this to your specific needs. I’m here to help! Sources: Worker options | LiveKit Docs | Agent dispatch | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py
w
Copy code
ERROR livekit.agents - job_request_fnc failed {"job_request": "<livekit.agents.job.JobRequest object at 0x1330024e0>", "agent_name": ""}
Traceback (most recent call last):
  File "/Users/masai/Documents/masaischool/ai-tutor/py-agent/.venv/lib/python3.12/site-packages/livekit/agents/worker.py", line 884, in _job_request_task
    await self._opts.request_fnc(job_req)
  File "/Users/masai/Documents/masaischool/ai-tutor/py-agent/src/agent.py", line 1201, in job_request_callback
    room_name = job_request.room.room_name  # Get the room name from the request
                ^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: room_name
t
It looks like the error is telling us that the
JobRequest
object doesn’t have a
room_name
attribute. This might happen if the structure of the
JobRequest
object is a bit different than expected. Depending on the SDK version or how it’s implemented, you might need to access the room name in another way. Could you try replacing
job_request.room.room_name
with
job_request.room_name
? Or, to be sure, you can take a closer look at the
JobRequest
object by adding a debug statement like this:
Copy code
print(dir(job_request))
This will show you all the attributes available on the
JobRequest
object, so you can spot the right one for the room name. Please feel free to reach out if you want me to help you further after you give this a try. I’m here to support you!
w
Copy code
{'_job': id: "AJ_yAhLtU7k8gDq"
room {
  sid: "RM_HEk44UMEMrW5"
  name: "session-e98fb72b"
  empty_timeout: 300
  creation_time: 1757500514
  enabled_codecs {
    mime: "video/H264"
  }
  enabled_codecs {
    mime: "video/VP8"
  }
  enabled_codecs {
    mime: "video/VP9"
  }
  enabled_codecs {
    mime: "video/AV1"
  }
  enabled_codecs {
    mime: "audio/red"
  }
  enabled_codecs {
    mime: "audio/opus"
  }
  version {
    unix_micro: 1757500514896247
  }
  departure_timeout: 20
  creation_time_ms: 1757500514337
}
state {
  status: JS_RUNNING
  started_at: 1757500651869934454
  updated_at: 1757500651869934454
  worker_id: "AW_orFKCQdwWSBd"
  agent_id: "A_AoWE4a7ZNGPE"
}
no agent_name in the object
t
Thanks for sharing the debug output! It looks like the room name is tucked inside the
room
object as
room.name
. You can grab it like this:
Copy code
room_name = job_request.room.name
Try updating your
request_fnc
to use this path to access the room name. If you run into any more bumps or need a hand with adjustments, just let me know—I’m here to help!
w
and how to assign to custom room name while generating AccessToken?
t
I'd be happy to help you assign a custom room name while generating an AccessToken in LiveKit! You can do this by including the room name in the
VideoGrant
when creating the token. Here’s a friendly example in Python:
Copy code
from livekit import AccessToken, VideoGrant\n\n# Define your API key, secret, and room name\napi_key = \"your_api_key\"\napi_secret = \"your_api_secret\"\nroom_name = \"custom-room-name\"\nidentity = \"user-identity\"\n\n# Create the token\ntoken = AccessToken(api_key, api_secret)\n  .with_identity(identity)\n  .with_grants(VideoGrant(room_join=True, room=room_name))\n\n# Generate the JWT token\njwt_token = token.to_jwt()
Just replace
custom-room-name
with the room name you'd like to use. Don’t worry if the room doesn’t exist yet—LiveKit will create it automatically as soon as the first participant joins. If you have any more questions or need a hand with anything else, please feel free to ask. I’m here to help! Sources: Docs::Home | livekit-api/livekit/api/access_token.py | Docs::Home | web/src/app/api/token/route.ts | web/src/app/api/token/route.ts
w
I had given custom room name but still when accessing room object name is
session-{something}
Let's do something different, let's dispatch agent to room manually
t
To manually dispatch an agent to a room in LiveKit, you can use the
AgentDispatchService
API. Here’s a simple example in Python to help you get started:
Copy code
from livekit import api\n\nlkapi = api.LiveKitAPI()\n\ndispatch = await lkapi.agent_dispatch.create_dispatch(\n    api.CreateAgentDispatchRequest(\n        agent_name="test-agent",\n        room="my-room",\n        metadata='{"user_id": "12345"}'\n    )\n)
Key Details to Keep in Mind:Explicit Dispatch: Make sure your agent is registered with an
agent_name
in its
WorkerOptions
. This setting turns off automatic dispatch, giving you full manual control. • Room Creation: Don’t worry if the room doesn’t exist yet — it will be created automatically when you dispatch the agent. • Metadata: Feel free to include metadata like a user ID during dispatch; this information will be accessible in the agent’s job context. If you’d like, I’m here to help with more examples or guide you through other programming languages. Just let me know! Sources: lib/livekit/agent_dispatch_service_client.rb | Authentication | LiveKit Docs | Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | packages/livekit-server-sdk/src/AgentDispatchClient.ts