Im doing outbound calls with this code in the work...
# ask-ai
c
Im doing outbound calls with this code in the worker.py:
Copy code
...
# --- 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:
Copy code
llk dispatch create \
  --new-room \
  --agent-name cobranzas_telefonico_outbound
And see this:
Copy code
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 metadata
t
Thanks for reaching out, Tobias. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help sort out the duplicate dispatch issue, could you please clarify a few things for me? • Are there any retries or loops in your application logic that might be causing multiple calls to
CreateSIPParticipantRequest
? • 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.go
c
no there is no loops or retries, just the code i showed you. i checked the sip trunks and they are working properly, i can get the agent to call me. Im not using any custom logic, just running the agent with python agent.py dev and creating the dispatch
t
Since there are no retries, loops, or custom logic in your setup, and the SIP trunks are working as they should, the duplicate dispatch issue might be tied to how LiveKit manages deduplication. Here are a few friendly steps to help you troubleshoot: • Take a look at the logs for any entries mentioning "dropping duplicate data message" and check the
nonce
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.ts
c
but deduplication features for what? my problem is that livekit is creating an automatic dispatch when i create the room. This is a code i made to debug:
Copy code
import 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:
Copy code
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?
t
Hey there! Just wanted to share a bit about how LiveKit handles automatic dispatches. When a room is created, it sets up an automatic dispatch without any metadata because this system is all about keeping things simple and getting assignments done right away. If you need more control and want to include metadata, that’s where explicit dispatch methods come in—they’re designed for that purpose. So, automatic dispatch kicks in automatically when someone joins a room that doesn’t exist yet, but it doesn’t have any extra info like user details or business data at that moment. On the other hand, explicit dispatch options—like using the API, configuring tokens, or SIP calls—let you add all the metadata you want during dispatch. If your setup needs metadata attached to agent jobs, the best move is to turn off automatic dispatch by setting an
agent_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 Docs
c
As i showed you, i already have an agent_name: 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))
t
Hey there! Just a heads-up: LiveKit won’t create automatic dispatches when you’ve set an
agent_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.pyi
c
you can see it in the logs i showed you, im getting an automatic dispatch with no room agent name or metadata: 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]"}
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!