clean-architect-57780
09/02/2025, 3:28 PM...
# --- DIAL using the same fields as the CLI (E.164 + sip_number) ---
try:
req = api.CreateSIPParticipantRequest(
room_name=ctx.room.name,
sip_trunk_id=trunk_id,
sip_call_to=call_to, # <-- E.164 only, no sips:
sip_number=call_from, # <-- caller ID (Twilio number)
participant_identity=call_to, # identity = phone number
wait_until_answered=True, # surface SIP errors
)
logger.info("Dial request: trunk=%s to=%s from=%s", trunk_id, call_to, call_from)
await ctx.api.sip.create_sip_participant(req)
# Wait for the callee to join and wire to the agent
session.userdata.agent = agent
participant = await ctx.wait_for_participant(identity=call_to)
logger.info("SIP participant joined: %s", participant.identity)
agent.set_participant(participant)
except TwirpError as e:
logger.error("create_sip_participant failed: code=%s msg=%s meta=%s", e.code, e.message, getattr(e, "metadata", None))
ctx.shutdown()
if __name__ == "__main__":
agent_name = "cobranzas_telefonico_outbound"
logger.info("Worker registered with agent_name=%s", agent_name)
agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint, agent_name=agent_name))
Then im running connected to the same project:
llk dispatch create \
--new-room \
--agent-name cobranzas_telefonico_outbound
And see this:
livekit) tpucci@AR000H74NX6RF26 livekit-demo % lk dispatch list room-QKuUsu4GjiFH
Using url, api-key, api-secret from environment
DispatchID Room AgentName Metadata
---------------------------------------------------------------------------------------------------
AD_GCV9QEKmXK2u
AD_idojPWKHVMfy room-QKuUsu4GjiFH cobranzas_telefonico_outbound {"call_to": "+[oculto]"}
The call is working properly but im getting a duplicate dispatch. i have no automatic dispatch rules and dont have any room configuration. The "phantom" dispatch is messing my flow because it doesnt have the corresponding metadatatall-airline-16756
09/02/2025, 3:28 PMtall-airline-16756
09/02/2025, 3:29 PMCreateSIPParticipantRequest?
• Have you had a chance to check the configuration of your SIP trunk, like the authentication credentials and outbound number settings?
• Are you using any custom logic or middleware that could be affecting the dispatch process?
Getting a better understanding of these details will really help us figure out what's causing the duplicate dispatches. Thanks so much!
Sources: Making outbound calls | LiveKit Docs | Agents telephony integration | LiveKit Docs | sipclient.goclean-architect-57780
09/02/2025, 3:33 PMtall-airline-16756
09/02/2025, 3:34 PMnonce values to see if deduplication is kicking in properly.
• Make sure your LiveKit SDKs and server versions are up-to-date, as the latest versions come with better deduplication features.
• Double-check that any data messages or dispatches have unique nonce values when they’re supposed to be distinct, and matching nonce values when they’re meant to be retries.
If you’re still running into this, just give me a shout and we can dig into some more debugging together.
Sources: CHANGELOG.md | src/room/RTCEngine.tsclean-architect-57780
09/02/2025, 3:38 PMimport os, json, asyncio, uuid
from datetime import datetime, timezone
from livekit import api
async def main():
async with api.LiveKitAPI(
url=os.getenv("LIVEKIT_URL"),
api_key=os.getenv("LIVEKIT_API_KEY"),
api_secret=os.getenv("LIVEKIT_API_SECRET"),
) as lk:
room_name = f"dispatch-{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}"
print("Creating room:", room_name)
await lk.room.create_room(api.CreateRoomRequest(name=room_name))
# add a nonce to positively identify "our" dispatch
nonce = uuid.uuid4().hex
# after creating the room, BEFORE creating your dispatch:
listed = await lk.agent_dispatch.list_dispatch(room_name)
print("Listed dispatches:", [(d.id, repr(d.metadata)) for d in listed])
for d in listed:
if not (d.metadata or "").strip():
# Delete the default/empty one(s)
try:
await lk.agent_dispatch.delete_dispatch(d.id, room_name)
print("Deleted empty/default dispatch:", d.id)
except Exception as e:
print("Could not delete empty dispatch", d.id, e)
print("after deleting empty dispatches")
listed = await lk.agent_dispatch.list_dispatch(room_name)
print("Listed dispatches:", [(d.id, repr(d.metadata)) for d in listed])
# tiny backoff so the scheduler sees a clean queue
await asyncio.sleep(1)
# now create YOUR dispatch
metadata = json.dumps({"call_to": "+5492944388266", "nonce": nonce})
resp = await lk.agent_dispatch.create_dispatch(
api.CreateAgentDispatchRequest(
agent_name="test-agent", # must match your WorkerOptions agent_name
room=room_name,
metadata=metadata,
)
)
# (optional but recommended) verify there's only your job left
listed2 = await lk.agent_dispatch.list_dispatch(room_name)
print("Dispatches now:", [(d.id, repr(d.metadata)) for d in listed2])
await lk.aclose()
if __name__ == "__main__":
asyncio.run(main())
if i run the code i see:
python dispatch.py
Creating room: dispatch-20250902-153712-24c3ce
Listed dispatches: [('AD_UNSkaBn7B7Cg', "''")]
Deleted empty/default dispatch: AD_UNSkaBn7B7Cg
after deleting empty dispatches
Listed dispatches: []
Dispatches now: [('AD_2CqorSYjboe3', '\'{"call_to": "+5492944388266", "nonce": "32dbca945b2344ac8b65c2ac96826d9d"}\'')]
So there is an automatic dispatch being created with no metadata when i create the room, why?tall-airline-16756
09/02/2025, 3:39 PMagent_name and switch to one of those explicit methods. This way, you can include all the context you need and make everything fit nicely with your business logic or other systems. And hey, if you’d like a hand figuring out how to set this up for your specific needs, just let me know—I’m here to help!
Sources: Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | packages/livekit-server-sdk/src/AgentDispatchClient.ts | SIP APIs | LiveKit Docsclean-architect-57780
09/02/2025, 3:41 PMtall-airline-16756
09/02/2025, 3:42 PMagent_name in WorkerOptions. This setting is purposely designed to turn off automatic dispatch and let you handle dispatches in a more controlled, explicit way.
If you’re still seeing automatic dispatches pop up, don’t worry! Here are a few things that might be causing it and some easy steps to fix it:
• Multiple Agents: Double-check that you don’t have any other agents running without an agent_name. Those unnamed agents will keep getting automatic dispatches.
• Configuration Mismatch: Make sure the agent_name matches exactly in your agent code and in any dispatch rules or participant tokens.
• Legacy Behavior: Confirm you’re using the latest LiveKit version and following the updated v1.x guidelines for setting up agents.
• Agent Restart: After you tweak WorkerOptions, a quick restart of the agent worker can help those changes kick in.
If you want to dig a bit deeper, you can use the API to list active dispatches and see exactly which agents are being dispatched. And hey, if you want a hand reviewing your setup or figuring out what’s going on, just let me know—I’m here to help!
Sources: Agent dispatch | LiveKit Docs | Dispatching agents | LiveKit Docs | SIP troubleshooting guide | LiveKit Docs | Making calls using SIP | LiveKit Docs | livekit-protocol/livekit/protocol/agent_dispatch.pyiclean-architect-57780
09/02/2025, 3:50 PMtall-airline-16756
09/02/2025, 3:50 PM