How can I dynamically pass all the configuration f...
# ask-ai
h
How can I dynamically pass all the configuration for the agent and dynamically use all the STT, LLM and TTS plugins?
t
Thanks for reaching out, Shawn. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! Could you share a bit more about how you're planning to use dynamic configurations with the STT, LLM, and TTS plugins? For example: • Are you hoping to set these up programmatically through an API? • Would you like some help with installing or integrating specific plugins into your workflow? • Are there particular plugins or settings you're working with right now? The more details you can share, the better I can support you!
h
Yes I would like to programmatically configure the agent configuration on every job before joining a room
t
If you want to set up the agent programmatically before joining a room, you can use the RoomConfiguration inside the participant's access token. This way, you get to decide which agents should be dispatched when someone joins a room, and you can even add some optional metadata for the agent job. Here’s a friendly example in Node.js:
Copy code
import { AccessToken } from 'livekit-server-sdk';
import { RoomConfiguration, RoomAgentDispatch } from '@livekit/protocol';

const at = new AccessToken();
at.identity = 'my-participant';
at.addGrant({ roomJoin: true, room: 'my-room' });

// Set up agent dispatch in the room config
at.roomConfig = new RoomConfiguration({
  agents: [
    new RoomAgentDispatch({
      agentName: 'test-agent',
      metadata: '{"mydata": "myvalue"}', // Optional data for the job
    }),
  ],
});

const token = await at.toJwt();
And if you prefer Python, here’s how you can do it:
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

token = (
    AccessToken()
    .with_identity("my_participant")
    .with_grants(VideoGrants(room_join=True, room="my-room"))
    .with_room_config(
        RoomConfiguration(
            agents=[RoomAgentDispatch(agent_name="test-agent", metadata='{"user_id": "12345"}')],
        ),
    )
    .to_jwt()
)
Just a few things to keep in mind: • The agent needs to be running with an
agent_name
set in
WorkerOptions
. If not, automatic dispatch will take over. • Any metadata you include in
RoomAgentDispatch
gets passed to the agent’s
JobContext
, so it’s accessible while the agent is running. • The agent’s entrypoint function runs before the agent actually joins the room, which is perfect for initializing and setting things up. This approach gives you complete control over how agents are dispatched and configured before anyone joins the room. If you have any questions or want to chat more about it, just let me know! Sources: examples/agent-dispatch/index.ts | Authentication | LiveKit Docs | Agent dispatch | LiveKit Docs | examples/agent_dispatch.py | Dispatching agents | LiveKit Docs
h
How can I do the same with a incoming sip call
t
Hey there! If you want to programmatically set up agent settings for an incoming SIP call, you’ll need to create a SIP dispatch rule that tells the system which agent(s) to send the call to. Here’s a friendly step-by-step to get you going: 1. Name Your Agent: Make sure your agent has a name defined in
WorkerOptions
. This stops automatic dispatch and gives you full control. Here’s a quick Python example:
Copy code
if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(
        entrypoint_fnc=entrypoint,
        agent_name="my-telephony-agent"  # This is super important for explicit dispatch
    ))
1. Create a SIP Dispatch Rule: Set up a rule that directs incoming SIP calls to a room and dispatches your chosen agent. Here’s what your
dispatch-rule.json
might look like:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "call-"
      }
    },
    "roomConfig": {
      "agents": [
        {
          "agentName": "my-telephony-agent"
        }
      ]
    }
  }
}
Then, create the rule using the CLI:
Copy code
lk sip dispatch create dispatch-rule.json
1. Programmatic Setup Using SDKs: You can also handle everything programmatically! Here’s an example in Python:
Copy code
from livekit.api import LiveKitAPI, CreateSIPInboundTrunkRequest, SIPInboundTrunkInfo, CreateSIPDispatchRuleRequest, SIPDispatchRule

lk_api = LiveKitAPI(
    url="https://your-livekit-url",
    api_key="your-api-key",
    api_secret="your-api-secret",
)

# Create inbound trunk
inbound_trunk = await lk_api.sip.create_sip_inbound_trunk(
    CreateSIPInboundTrunkRequest(
        trunk=SIPInboundTrunkInfo(
            name="inbound-trunk",
            numbers=["+1234567890"],
            auth_username="your-username",
            auth_password="your-password"
        )
    )
)

# Create dispatch rule with agent
dispatch_rule = await lk_api.sip.create_sip_dispatch_rule(
    CreateSIPDispatchRuleRequest(
        trunk_ids=[inbound_trunk.sip_trunk_id],
        rule=SIPDispatchRule(
            dispatch_rule_individual=SIPDispatchRuleIndividual(room_prefix="call")
        ),
        room_config={
            "agents": [
                {"agentName": "my-telephony-agent"}
            ]
        }
    )
)
Just a quick heads-up: make sure the agent name in your code exactly matches the one in your dispatch rule. If they don’t line up, the agent won’t get dispatched. If you have any questions or want me to walk you through anything, just let me know—I’m here to help! Sources: Creating SIP Inbound Trunks and Dispatch Rules with Python SDK | src/setup-livekit.ts | Agents telephony integration | LiveKit Docs | SIP troubleshooting guide | LiveKit Docs
h
How will I get the sip phone number before the session starts
t
Hey there! To grab the SIP phone number before a session kicks off, it really depends on whether you’re dealing with an outbound or inbound call: • Outbound Calls: The phone number is clearly set during dispatch and you can find it in the
job.metadata
before the session begins. For example, in your agent’s
entrypoint
function, you can pull the number from the metadata like this:
Copy code
def entrypoint(ctx: JobContext):
    # Parse job metadata before session starts
    dial_info = json.loads(ctx.job.metadata)
    phone_number = dial_info["phone_number"]
    
    # This phone number is available before any participant connects
    logger.info(f"Outbound phone number (pre-session): {phone_number}")
    
    # Proceed to create SIP participant and start session
    ...
• Inbound Calls: The caller’s phone number (
sip.phoneNumber
) only shows up after the SIP participant has connected to the room. Unfortunately, you can’t access it before the session starts unless your SIP provider includes it in a custom SIP header. If that’s the case, you can map it to dispatch metadata using
headers_to_attributes
. For inbound calls, just make sure
HidePhoneNumber
is turned off in your dispatch rule so the phone number is available once the participant joins. If you want to chat more about this or have a specific scenario in mind, I’m here to help! Sources: telephony/survey_caller/survey_calling_agent.py | Agents telephony integration | LiveKit Docs
h
How do you get the phone number which received the call
t
Could you help me understand your situation a bit better when it comes to retrieving the phone number that received the call? For example: • Are you talking about an inbound SIP call where you want to find out which number on your SIP trunk was dialed? • Do you need to get this info during the call session or even before it starts? • Are you working with a specific SIP provider or using any custom headers for this setup? The more details you can share, the better I can assist you!
h
Yes for inbound SIP call, I want to know which SIP trunk was dialed
t
Hey there! If you want to find the phone number that was dialed for an inbound SIP call, you can grab it from the
sip.trunkPhoneNumber
attribute on the SIP participant object once the call connects to a room. This attribute holds the phone number linked to the SIP trunk that was dialed. Here’s a quick look at how you can get it programmatically: • Node.js Example:
Copy code
// Assuming you have a participant object from room events or listing
if (participant.kind === ParticipantKind.SIP) {
  const dialedNumber = participant.attributes['sip.trunkPhoneNumber'];
  const trunkId = participant.attributes['sip.trunkID'];

  console.log('Dialed number:', dialedNumber);
  console.log('Trunk ID:', trunkId);
}
• Python Example:
Copy code
from livekit import rtc

# After participant joins room
if participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP:
    dialed_number = participant.attributes.get('sip.trunkPhoneNumber')
    trunk_id = participant.attributes.get('sip.trunkID')

    print(f"Dialed number: {dialed_number}")
    print(f"Trunk ID: {trunk_id}")
And if you want to dig into details about the SIP trunk itself (like all the phone numbers tied to it), you can use the
GetSIPInboundTrunk
API. Here’s an example:
Copy code
# Using LiveKit CLI
lk sip inbound get --id <trunk-id>
Feel free to reach out if you have any questions or need a hand with anything else! Sources: SIP APIs | LiveKit Docs | SIP participant | LiveKit Docs
h
I need to access it in the entry function
t
Hey there! Just a quick heads-up: the SIP trunk phone number (
sip.trunkPhoneNumber
) isn’t immediately available in the entry function for inbound SIP calls. You’ll see it pop up only after the SIP participant joins the room, as part of their participant attributes. If you’d like to grab the dialed number a bit earlier, a good trick is to set up your SIP trunk to send this info through custom SIP headers. Then, you can use the
headers_to_attributes
setting to map those headers to metadata fields, making them accessible right in the entry function. Feel free to reach out if you want a hand setting up custom headers or if there’s anything else you’re curious about! Sources: SIP participant | LiveKit Docs | SIP APIs | LiveKit Docs
h
Where can I access the headers_to_attributes?
t
Hey there! The
headers_to_attributes
field in your SIP trunk settings is a handy way to map custom SIP
X-*
headers to participant attributes. This means you can easily attach extra info to your SIP participants based on the headers that come through during SIP communication. Here’s a quick guide on how to set it up: • For Inbound Trunks: You can map SIP
X-*
headers from the INVITE to participant attributes. For example:
Copy code
{\n  "trunk": {\n    "name": "Demo trunk",\n    "numbers": ["+15105550100"],\n    "headers_to_attributes": {\n      "X-Custom-Header": "custom_attribute"\n    }\n  }\n}
• For Outbound Trunks: Similarly, you can map SIP
X-*
headers from the 200 OK response to participant attributes. Once you’ve got this configured, the mapped attributes will show up in the SIP participant object within the room. You can set this either when creating the trunk or update an existing one using the
CreateSIPInboundTrunk
,
UpdateSIPInboundTrunk
, or similar APIs. If you want a hand with this or have any questions, just let me know—I’m here to help! Sources: livekit/livekit_sip.pb.go | SIP APIs | LiveKit Docs | SIP participant | LiveKit Docs