Whats the ideal setup for handling multiple agent ...
# ask-ai
b
Whats the ideal setup for handling multiple agent configs for different customers. Our customers each have their own config with different prompts and functions. So when one of their client calls their twilio phone number we give them it should load their config and handle the call with their customizations?
t
Thanks for reaching out, Maximilian. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Handling multiple agent configurations for different customers can feel a bit tricky, but LiveKit’s SIP integration and job metadata features make it much more manageable. Here’s a friendly overview to help you get started: 1. First, set up multiple Twilio phone numbers, each one linked to a specific customer. 2. Next, create dispatch rules in LiveKit for each phone number. These rules can carry customer-specific metadata, like customer IDs or configuration details. 3. Then, implement a routing agent that reads the metadata from incoming calls and dynamically loads the right configuration. This might include prompts and functions stored externally, like in files or a database. 4. Make use of LiveKit’s job metadata to pass structured data (such as JSON), which tells the system which customer configuration to use. 5. Lastly, to keep conversations smooth and continuous, preserve context when transferring between agents by using patterns like the UserData structure. If you’d like, I’m here to walk you through any of these steps in more detail—just let me know! Sources: examples/voice_agents/restaurant_agent.py | src/setup-twilio.ts | Inbound calls with Twilio Voice | LiveKit docs | Agent dispatch | LiveKit Docs | complex-agents/personal_shopper/README.md
b
In the current metadata there is no information about which customers phone number is called. So there is no called phone number parameter. I am sturggling to figure out which number was callend inside the worker session
t
I understand it can be a bit tricky when the called phone number isn’t showing up in the metadata. You can usually fix this by making sure the number is passed along during the dispatch process. Here are some friendly steps to help you out: 1. Double-check that the
hide_phone_number
setting is turned off when you create SIP participants. This way, the phone number gets included in the participant attributes. 2. Make sure to explicitly pass the called phone number in the
job.metadata
field when dispatching the agent. This is the most dependable way to have the number available in the worker session. 3. Take a look at the participant’s
identity
field—by default, LiveKit uses the phone number there unless a custom identity is set or
hide_phone_number
is enabled. If you’d like, I’m here to help you walk through these steps or answer any questions you might have. Just let me know! Sources: livekit-api/src/services/sip.rs | SIP APIs | LiveKit docs | Preserving Caller ID During SIP Transfers in LiveKit Agents | Agents telephony integration | LiveKit Docs | Job lifecycle | LiveKit Docs
b
how do i pass the phone number into the job metadata. Is it in the dispatch rule?
t
I'd be happy to help you include the phone number in the job metadata! You can do this by adding it to the
metadata
field of your dispatch rule. Since the
metadata
field is a string, using JSON is a great way to keep your data organized. For instance, when you're creating a dispatch rule, you might include the phone number like this:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "customer1-"
      }
    },
    "metadata": "{\"phone_number\": \"+1234567890\", \"customer_id\": \"customer1\"}"
  }
}
Then, in your agent's
entrypoint
function, you can easily parse this metadata to get the phone number:
Copy code
import json
async def entrypoint(ctx: JobContext):
    dial_info = json.loads(ctx.job.metadata)
    phone_number = dial_info["phone_number"]
    # Use the phone_number as needed
If you have any questions or need a hand with this setup, please don't hesitate to reach out. I'm here to help! Sources: Agent dispatch | LiveKit Docs | agent.py
b
so i need a dispatch rule for each client/phone number?
t
Great question! You actually don’t need a separate dispatch rule for each client or phone number. You can use just one dispatch rule to cover multiple phone numbers by listing them in the
inbound_numbers
field. Here’s a quick example:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleCallee": {
        "inbound_numbers": [
          "+15105550123",
          "+12025550198"
        ]
      }
    },
    "metadata": "{\"customer_id\": \"shared_config\"}"
  }
}
This makes it easier to manage multiple clients or numbers all in one place. If you’d like, I’m here to help you set this up step-by-step—just let me know! Sources: SIP dispatch rule | LiveKit docs | livekit-protocol/src/livekit.rs | Accepting inbound calls | LiveKit docs
b
but how does the agent figure out which number was called?
t
Hi there! To help you figure out which phone number was called, an agent can use one of these friendly methods: 1. Room Name Structure: If you're using a Callee dispatch rule, you can set up the room name to include the called number. For instance, by setting a
roomPrefix
like "number-", the room name will show the called number, making it super easy to identify. 2. Participant Attributes: During call processing, LiveKit adds a participant attribute called
livekit.AttrSIPTrunkNumber
that holds the called number (from the SIP "To" header). Agents can check this attribute to programmatically find out which number was dialed. If you'd like, I’m here to help you set up either of these methods—just let me know! Sources: SIP dispatch rule | LiveKit docs | sip/sip.go
b
room name includes the caller number not the called number
t
To make sure the called number is easily accessible, here are a couple of friendly ways you can try: 1. Use a Callee Dispatch Rule: You can set up the dispatch rule to include the called number right in the room name. For example:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleCallee": {
        "roomPrefix": "number-",
        "randomize": false
      }
    },
    "name": "My dispatch rule"
  }
}
This approach will create room names like
number-+15105550123
, so the called number becomes part of the room name, making it easier to identify. 1. Access Participant Attributes: You can also find the called number included in participant attributes, such as
sip.trunkPhoneNumber
, which you can access programmatically. If you'd like, I’m here to help you set this up or answer any questions you have! Sources: SIP dispatch rule | LiveKit docs | test/integration/sip_test.go | Make outbound calls | LiveKit docs
b
how can i acces this programmatically: sip.trunkPhoneNumber
t
I'm happy to help you access
sip.trunkPhoneNumber
from the
attributes
field of a SIP participant once they join a room. Here's a simple way to do it: 1. Listen for Participant Events: Use the SDK to listen for when participants connect and then check their attributes. For example, in Node.js:
Copy code
room.on('participantConnected', (participant) => {
  if (participant.kind === 'SIP') {
    const trunkPhoneNumber = participant.attributes['sip.trunkPhoneNumber'];
    console.log('Trunk Phone Number:', trunkPhoneNumber);
  }
});
1. Query Existing Participants: You can also get all participants in a room and look at their attributes like this:
Copy code
const participants = room.getParticipants();
participants.forEach((participant) => {
  if (participant.kind === 'SIP') {
    const trunkPhoneNumber = participant.attributes['sip.trunkPhoneNumber'];
    console.log('Trunk Phone Number:', trunkPhoneNumber);
  }
});
One important thing to double-check is that
hide_phone_number
is not enabled in your dispatch rules because that would stop the phone number from showing up in the attributes. If you have any questions or want me to walk you through this further, just let me know—I’m here to help! Sources: livekit-protocol/livekit/protocol/sip.pyi | lib/livekit/proto/livekit_sip_pb.rb | SIP inbound trunk | LiveKit docs | SIP participant | LiveKit docs | livekit/attrs.go
b
this is my current code: async def entrypoint(ctx: JobContext): ctx.log_context_fields = { "room": ctx.room.name, } call_start_time = datetime.now() phone_number = "+test-number" logger.info(*f*"Using hardcoded phone number: {phone_number}") room2 = await ctx.connect() logger.info(*f*"Room participants: {ctx.job}") logger.info(*f*"Room participants: {ctx.room.participant}") logger.info(*f*"Room local participant: {ctx.room.local_participant}") logger.info(*f*"Room remote participants: {ctx.room.remote_participants}") config_service = ConfigService() config = await config_service.get_config_by_phone(phone_number) if not config: logger.error(*f*"No config found for phone: {phone_number}") return logger.info( *f*"Loaded config for agent: {config.agent_id} " *f*"(workspace: {config.workspace_id}, assistant: {config.assistant_name})" ) factory = AgentFactory(config) session = factory.create_session(ctx, ctx.proc.userdata["vad"]) usage_collector = metrics.UsageCollector() @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() logger.info(*f*"Usage: {summary}") webhook_service = WebhookService(config.agent_id, phone_number) async def send_webhook(): try: call_end_time = datetime.now() duration = (call_end_time - call_start_time).total_seconds() transcript = [] for msg in session.chat_ctx.messages: transcript.append({ "role": msg.role, "message": msg.content if hasattr(msg, 'content') else str(msg), "interrupted": False, "originalMessage": None, }) participant_identity = ( ctx.room.local_participant.identity if ctx.room.local_participant else "unknown" ) await webhook_service.send_conversation_webhook( conversation_id*=*ctx.room.name, room_name*=*ctx.room.name, participant_identity*=*participant_identity, transcript*=*transcript, duration*=*duration, start_time*=*call_start_time, end_time*=*call_end_time, ) logger.info(*f*"Webhook sent successfully for room: {ctx.room.name}") except Exception as e: logger.error(*f*"Failed to send webhook: {e}") ctx.add_shutdown_callback(log_usage) ctx.add_shutdown_callback(send_webhook) background_audio = factory.create_background_audio() await session.start( agent*=*factory.create_main_assistant(), room*=*ctx.room, room_input_options*=*factory.get_room_input_options(), ) await background_audio.start(room*=ctx.room, agent_session=*session) logger.info(*f*"Agent session started for {config.assistant_name}") if name == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc*=entrypoint, prewarm_fnc=prewarm, agent_name=*"Tara"))
t
To help you access the
sip.trunkPhoneNumber
programmatically in your current code, you can retrieve it from the participant attributes right after connecting to the room. Here's a little update to your code that should do the trick:
Copy code
async def entrypoint(ctx: JobContext):
    # Connect to the room
    room2 = await ctx.connect()

    # Access remote participants
    for participant in ctx.room.remote_participants:
        if participant.kind == "SIP":
            trunk_phone_number = participant.attributes.get("sip.trunkPhoneNumber")
            logger.info(f"Trunk Phone Number: {trunk_phone_number}")

    # Continue with your existing logic
    ...
This way, you'll be able to log or use the
sip.trunkPhoneNumber
for whatever comes next. If you run into any bumps or want to explore this further, just let me know—I’m here to help!
b
for participant in ctx.room.remote_participants: logger.info(*f*"Participant: {participant}") if participant.kind == "SIP": trunk_phone_number = participant.attributes.get("sip.trunkPhoneNumber") logger.info(*f*"Trunk Phone Number: {trunk_phone_number}") logs: 2025-11-16 155733,778 - INFO agent - Participant: sip_+fake {"room": "call-_+fake_HvQ92GakxWrY", "pid": 96279, "job_id": "AJ_fXaSXBUtZzPD"} 2025-11-16 155733,778 - ERROR livekit.agents - unhandled exception while running the job task Traceback (most recent call last): File "/Users/maxi/imperia/backend/agent/.venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/maxi/imperia/backend/agent/.venv/lib/python3.11/site-packages/livekit/agents/ipc/job_proc_lazy_main.py", line 240, in _traceable_entrypoint await self._job_entrypoint_fnc(job_ctx) File "/Users/maxi/imperia/backend/agent/src/agent.py", line 44, in entrypoint if participant.kind == "SIP": ^^^^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'kind' {"room": "call-_+491736774403_HvQ92GakxWrY", "pid": 96279, "job_id": "AJ_fXaSXBUtZzPD"}
t
It looks like the error is happening because the
participant
object is being treated as a string instead of a full participant object. This sometimes happens if the
ctx.room.remote_participants
list contains string representations rather than the actual participant objects. To help fix this, please make sure you're accessing the correct participant objects. You can update your code to log the type of each participant, which is a great way to debug:
Copy code
for participant in ctx.room.remote_participants:
    logger.info(f"Participant: {participant}, Type: {type(participant)}")
    if hasattr(participant, "kind") and participant.kind == "SIP":
        trunk_phone_number = participant.attributes.get("sip.trunkPhoneNumber")
        logger.info(f"Trunk Phone Number: {trunk_phone_number}")
If you find that the participants are strings, it might mean there’s an issue with how the room or participants are being set up. Please don’t hesitate to reach out if this keeps happening—I’m here to help you sort it out!