what is the webhook event that can be used to know...
# ask-ai
o
what is the webhook event that can be used to know end user actually picked up the call?
t
Thanks for reaching out, Jaivarsan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're looking for the webhook that indicates a call was actually answered. Use the participant_joined webhook for the SIP participant and check the participant's
sip.callStatus
attribute — when it changes to
active
, that indicates the end user picked up the call. You can also track call lifecycle with
sip_call_initiated
and
sip_call_ended
webhooks if you need broader context. Sources: SIP participant | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki
o
in the case of outbound calls, where there is ringing then? we are getting
active
for user picked missed calls and no such sip call status for end user answering. in livekit, we create sip participant request and rooms etc. so help here
t
Thanks — I’ll help troubleshoot where ringing vs answered should appear and what to check in your outbound flow. You're asking about outbound calls where you see
active
even for missed calls and no
sip.callStatus
for the end user answering. To diagnose, please confirm two quick things: 1. Are you creating the SIP participant with
wait_until_answered
set to true or false? 2. Which webhook events are you actually receiving after creating the participant (e.g.,
participant_joined
,
participant_metadata_changed
,
sip_call_initiated
,
sip_call_ended
) and do any include
sip.callStatus
values? What to expect and what to check next: • If
wait_until_answered: true
, the create call blocks until answer — failures/timeouts return an error instead of a non-answered participant. That can mask ringing events. Use
wait_until_answered: false
to get immediate participant creation and then track state via events. • Ringing should appear as
sip.callStatus: "ringing"
on participant attribute updates. Those updates arrive via
participant_metadata_changed
(or the webhook equivalent).
participant_joined
may happen only after answer in some flows. •
sip.callStatus: "active"
means media connected (user actually answered). You should not see
active
unless the call is connected; if you do, verify whether your SIP provider is forwarding voicemail/auto-answer as connected. • Also watch
sip_call_initiated
and
sip_call_ended
webhooks for lifecycle context and SIP status codes (486, 408, etc.) which indicate busy/no-answer. If you confirm your
wait_until_answered
setting and which webhooks/attributes you’re receiving, I’ll give the exact checks and a short debugging checklist to pinpoint why ringing isn’t observed in your setup. Sources: SIP participant | LiveKit docs | Make outbound calls | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki
o
what does play dialtone mean? for outbound calls?
t
"Play dialtone" means LiveKit will emit a dial tone audio into the room while an outbound SIP call is being connected (during ringing). Use cases: • Let agents/other participants hear that an outbound call is in progress and waiting for the callee to pick up. • Improves UX by providing audible feedback until the remote party answers. Behavior: • Enabled via the
play_dialtone
option on
CreateSIPParticipant
. • Dial tone plays only during the call setup/ringing phase; once
sip.callStatus
becomes
active
(call answered) the dial tone stops. Sources: Make outbound calls | LiveKit docs | SIP APIs | LiveKit docs
o
should it be true, if we are using wait_until_answered: tru
t
You can set
play_dialtone: true
even when using
wait_until_answered: true
. Quick guidance: •
wait_until_answered: true
blocks the CreateSIPParticipant call until the remote party answers (or the call fails). •
play_dialtone: true
only controls audible feedback inside the LiveKit room during the dialing/ringing phase. • If both are enabled, callers/agents in the room will hear the dial tone while the API call is waiting for answer; when
sip.callStatus
becomes
active
the dial tone stops. Recommendation: enable
play_dialtone
when you want in-room audible feedback during the wait; leave it off if you don’t want any audio while the call is pending.
o
this is how we are dialling
Copy code
class LiveKitDialer(Dialer):
    """Dialer implementation for LiveKit SIP provider.

    LiveKit uses SIP trunks configured on their platform to make outbound calls.
    This dialer creates a SIP participant in a LiveKit room which dials out
    to the destination phone number via the configured SIP trunk.

    Required environment variables:
        LIVEKIT_URL: LiveKit server URL (e.g., wss://your-project.livekit.cloud)
        LIVEKIT_API_KEY: LiveKit API key
        LIVEKIT_API_SECRET: LiveKit API secret

    SIP line metadata should contain:
        sip_trunk_id: The LiveKit SIP trunk ID to use for outbound calls
    """

    async def _create_sip_participant_async(self, request: CreateSIPParticipantRequest):
        """
        Create LiveKitAPI within the running event loop and make the API call.

        LiveKitAPI uses aiohttp internally which binds to the event loop at creation time.
        Since async_to_sync creates a new event loop for each call, we must create a fresh
        LiveKitAPI instance each time to avoid 'Event loop is closed' errors.
        """
        livekit_url = os.getenv("LIVEKIT_URL")
        if not livekit_url:
            raise ValueError("LIVEKIT_URL environment variable is required")

        api = LiveKitAPI(
            url=livekit_url,
            api_key=os.getenv("LIVEKIT_API_KEY"),
            api_secret=os.getenv("LIVEKIT_API_SECRET"),
        )
        try:
            result = api.sip.create_sip_participant(request)
            if inspect.isawaitable(result):
                return await result
            return result
        finally:
            await api.aclose()

    def dial(self, body: dict, virtual_number_data: dict, sip_line_data: dict, chosen_worker: dict) -> bool:
        """
        Create a SIP outbound call via LiveKit.

        LiveKit SIP outbound calls work by creating a SIP participant that dials
        out to the destination number through a configured SIP trunk.
        """
        try:
            call_uuid = body['call_uuid']
            caller_number = body['caller_number']
            virtual_number = body['virtual_number']

            # Get SIP trunk ID from metadata
            sip_trunk_id = sip_line_data.get('metadata', {}).get('sip_trunk_id')
            if not sip_trunk_id:
                logger.error(f"LiveKit dial error: sip_trunk_id not found in sip_line metadata for call {call_uuid}")
                return False

            # sip_call_to is the destination phone number in E.164 format (e.g., +14155551234)
            # LiveKit routes the call through the configured SIP trunk
            sip_call_to = caller_number
            # sip_number is the caller ID / virtual number presented on the call
            sip_number = virtual_number

            # Room name - use call_uuid for unique room per call
            room_name = f"call-{call_uuid}"

            # Participant identity for the SIP participant
            participant_identity = f"sip_{call_uuid}"

            call_type = "OUTBOUND"

            # Build metadata to pass call context
            participant_metadata = json.dumps({
                "call_uuid": call_uuid,
                "virtual_number": virtual_number,
                "caller_number": caller_number,
                "language_code": body.get('language_code', ''),
                "call_type": call_type
            })

            # Additional SIP headers if needed
            sip_headers = {}
            sip_headers["X-CallType"] = call_type
            if virtual_number:
                # Set caller ID via P-Asserted-Identity or From header
                sip_headers["X-Virtual-Number"] = virtual_number

            # Create the SIP participant request
            request = CreateSIPParticipantRequest(
                sip_trunk_id=sip_trunk_id,
                sip_call_to=sip_call_to,
                sip_number=sip_number,
                room_name=room_name,
                participant_identity=participant_identity,
                participant_metadata=participant_metadata,
                play_dialtone=False,  # Don't play dialtone, agent will handle audio
                wait_until_answered=True
            )

            if sip_headers:
                # Protobuf map fields must be mutated, not reassigned
                for key, value in sip_headers.items():
                    request.headers[key] = value

            logger.debug(f"LiveKit CreateSIPParticipant request for call {call_uuid}: room={room_name}, trunk={sip_trunk_id}, to={sip_call_to}")

            # Make the API call
            response = async_to_sync(self._create_sip_participant_async)(request)

            logger.info(f"LiveKit SIP participant created for call {call_uuid}: participant_id={response.participant_id}, sip_call_id={response.sip_call_id}")

            return True

        except ImportError as e:
            logger.error(f"LiveKit SDK not installed: {e}. Install with: pip install livekit-api")
            sentry_sdk.capture_exception(e)
            return False
        except Exception as e:
            logger.error(f"LiveKit dial error for call {body.get('call_uuid', 'unknown')}: {str(e)}")
            sentry_sdk.capture_exception(e)
            return False
t
You're currently creating the SIP participant with
wait_until_answered: true
and
play_dialtone: False
. Quick answers and guidance: • play_dialtone simply controls audible feedback inside the LiveKit room while the outbound call is connecting. It does not affect SIP signalling or whether the CreateSIPParticipant call blocks. • You can set
play_dialtone: true
even when
wait_until_answered: true
. With that combo agents/participants in the room will hear the dial tone while the API call waits for answer; the tone stops when
sip.callStatus
becomes
active
. • If you want room participants to hear that the system is ringing while the outbound call is pending, set
play_dialtone: true
. If you don’t want any audio while waiting, keep it false. Given your earlier issue (seeing
active
for missed calls / not seeing
ringing
): • With
wait_until_answered: true
, failures or no-answer typically return an error instead of a non-answered participant. That can make it look like you only see
active
when calls succeed. To observe
ringing
and state transitions reliably, use
wait_until_answered: false
and monitor
participant_metadata_changed
(or your webhook) for
sip.callStatus
→ "ringing" then "active" or "hangup". • If you prefer blocking behavior but still want in-room tone while waiting, enable
play_dialtone: true
with
wait_until_answered: true
. If you want, I can: • Suggest the minimal code change to switch to non-blocking dialing and listen for
sip.callStatus
updates, or • Show how to keep blocking behavior but enable dialtone and handle possible Twirp errors for no-answer. Which would you like?
o
i don't see ringing status at all. why? our bots calls are getting connected and talking with end user because we are not getting any updates.
t
You're not seeing "ringing" because of timing and how you're creating the SIP participant. Based on your code and symptoms, do the following to diagnose and fix it: 1. Confirm current behavior • Verify your CreateSIPParticipant is called with
wait_until_answered: true
(your code shows it is). That blocks until answer, so you will not observe intermediate state updates from the API response. 1. Switch to non-blocking to observe states • Set
wait_until_answered: false
and keep
play_dialtone
as desired. • Create the SIP participant immediately, then monitor events for state changes. 1. Ensure you are listening for the right event • Listen for
participant_metadata_changed
(or the webhook equivalent) and check
sip.callStatus
on that participant. • Expect values:
"dialing"
→
"ringing"
→
"active"
or
"hangup"
. •
participant_joined
may only occur after answer in some flows, so do not rely on it alone. 1. Add logging for SIP lifecycle webhooks/errors • Log
sip_call_initiated
and
sip_call_ended
webhook payloads and any Twirp/API errors from the CreateSIPParticipant call (with
wait_until_answered: true
errors can include SIP status codes like 486/408). • If voicemail/auto-answer is present, provider may immediately return `active`; check SIP status codes in
sip_call_ended
or API error metadata. 1. Quick test plan • Temporarily set
wait_until_answered: false
, enable
play_dialtone: true
, initiate a call to a phone you control, and watch your webhook logs for
participant_metadata_changed
updates showing
ringing
then
active
. • If you still never see
ringing
, capture full webhook payloads and any SIP status codes from `sip_call_initiated`/`sip_call_ended`. If you want, I can give the exact minimal code change to make the request non-blocking and a short webhook-check snippet for validating
sip.callStatus
. Which would you prefer?
a
Can you give me the example code for listening to
participant_metadata_changed
in a tool call?
t
Below are two concise examples showing how to observe
participant_metadata_changed
and read
sip.callStatus
— one for handling LiveKit webhooks (server-side) and one for listening from a room using the JavaScript Room SDK. Use the one that fits your "tool call" architecture. 1) Webhook receiver (Python + Flask) • Use this when LiveKit is configured to POST webhook events to your service.
Copy code
# app.py
from flask import Flask, request, jsonify
import logging

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

@app.route("/livekit/webhook", methods=["POST"])
def livekit_webhook():
    event = request.get_json()
    event_type = event.get("type")

    # participant metadata changed event arrives with participant and metadata
    if event_type == "participant_metadata_changed":
        participant = event.get("participant", {})
        attrs = participant.get("metadata") or participant.get("attributes") or {}
        sip_status = attrs.get("sip.callStatus") or attrs.get("sip.call_status")
        logging.info(f"participant_metadata_changed for {participant.get('sid') or participant.get('id')}: sip.callStatus={sip_status}")

        if sip_status == "ringing":
            # handle ringing
            logging.info("📞 Call is ringing")
        elif sip_status == "active":
            # handle answered
            logging.info("✅ Call answered")
        elif sip_status == "hangup":
            logging.info("❌ Call ended")

    # also handle lifecycle webhooks for extra context
    if event_type == "sip_call_initiated":
        logging.info("SIP call initiated")
    if event_type == "sip_call_ended":
        logging.info(f"SIP call ended: {event.get('sip_status_code')}")

    return jsonify({"ok": True})
• Deploy this endpoint and ensure your LiveKit project is configured to send webhooks to its URL. • Log full payloads during testing to confirm where
sip.callStatus
appears (some payloads include attributes under
participant.metadata
or
participant.attributes
). 2) Room SDK listener (JavaScript) • Use this when your tool is connected as a participant in the LiveKit room and can observe participant updates.
Copy code
import { connect } from "livekit-client";

async function joinAndListen(url, token, roomName) {
  const room = await connect(url, token, { room: roomName });

  // existing participants
  room.participants.forEach(p => {
    watchParticipant(p);
  });

  // watch new participants
  room.on("participantConnected", (participant) => {
    watchParticipant(participant);
  });

  function watchParticipant(participant) {
    // initial metadata
    const attrs = participant.metadata || participant.attributes || {};
    checkSipStatus(participant.sid || participant.identity, attrs);

    // listen for metadata/attribute changes
    participant.on("metadataChanged", () => {
      const attrs = participant.metadata || participant.attributes || {};
      checkSipStatus(participant.sid || participant.identity, attrs);
    });

    // some SDKs expose attribute changes differently (trackPublished, updated)
    participant.on("updated", () => {
      const attrs = participant.metadata || participant.attributes || {};
      checkSipStatus(participant.sid || participant.identity, attrs);
    });
  }

  function checkSipStatus(id, attrs) {
    const sipStatus = attrs["sip.callStatus"] || attrs["sip.call_status"];
    console.log(`participant ${id} sip.callStatus=${sipStatus}`);
    if (sipStatus === "ringing") console.log("📞 ringing");
    if (sipStatus === "active") console.log("✅ answered");
    if (sipStatus === "hangup") console.log("❌ ended");
  }
}
Troubleshooting tips (short) • If you currently use
wait_until_answered: true
, switch to
wait_until_answered: false
for testing so you can observe
ringing
updates. • Log the full webhook/SDK participant payloads to see where
sip.callStatus
is present (metadata vs attributes). • Ensure your webhook receiver or SDK connection is up and authenticated and that LiveKit is configured to send webhooks for your project. • If you see
active
immediately, check whether your SIP provider is auto-answering (voicemail/auto-attendant) or returning early SIP status codes. If you want, I can give the minimal diff to your existing dialer code to set
wait_until_answered: false
and a short test script to verify
ringing
. Which would you prefer?
a
I am deploying to livekit cloud as an agent. Can you share the code snippet for the python sdk?
t
Below is a concise Python example showing how an agent (a participant) can connect to LiveKit Cloud using the Python Room SDK, watch other participants, and handle metadata updates to read
sip.callStatus
. It assumes you already have a valid room token for the agent.
Copy code
# watch_sip_status.py
import asyncio
import logging
from livekit import Room, RoomEvent

logging.basicConfig(level=logging.INFO)

LIVEKIT_URL = "wss://your-project.livekit.cloud"  # replace with your LiveKit Cloud URL
ROOM_NAME = "call-<call_uuid>"                    # the room your dialer created
TOKEN = "<AGENT_ROOM_TOKEN>"                      # short-lived token for agent participant

def check_sip_status(participant_id: str, metadata: dict):
    sip_status = None
    if metadata:
        sip_status = metadata.get("sip.callStatus") or metadata.get("sip.call_status")
    logging.info(f"participant {participant_id} sip.callStatus={sip_status}")
    if sip_status == "ringing":
        logging.info("📞 Call is ringing")
    elif sip_status == "active":
        logging.info("✅ Call answered")
    elif sip_status == "hangup":
        logging.info("❌ Call ended")

async def run():
    room = Room()
    await room.connect(LIVEKIT_URL, TOKEN, room=ROOM_NAME)

    # Watch existing participants
    for pid, participant in room.participants.items():
        check_sip_status(pid, participant.metadata or participant.info.metadata)

        # subscribe to participant updates
        async def on_participant_updated(p):
            # some SDKs expose metadata on p.metadata or p.info.metadata
            meta = getattr(p, "metadata", None) or getattr(p, "info", None) and getattr(p.info, "metadata", None)
            check_sip_status(p.sid or p.identity, meta)

        participant.on(RoomEvent.PARTICIPANT_UPDATED, on_participant_updated)

    # Watch new participants
    async def on_participant_connected(p):
        check_sip_status(p.sid or p.identity, p.metadata or (p.info.metadata if hasattr(p, "info") else None))
        p.on(RoomEvent.PARTICIPANT_UPDATED, lambda updated_p: asyncio.create_task(on_participant_updated(updated_p)))

    room.on(RoomEvent.PARTICIPANT_CONNECTED, on_participant_connected)

    # Keep running
    await room.wait_until_disconnected()

if __name__ == "__main__":
    asyncio.run(run())
Notes and quick tips: • Ensure the agent token has permission to join the room and receive participant updates. • If you do not see
ringing
, create the SIP participant with
wait_until_answered: false
and verify LiveKit webhooks/participant attributes are being updated. • Log full participant payloads during testing to find where
sip.callStatus
appears (some SDK versions expose metadata differently). • If your agent runs in a server environment, make sure outbound websocket connections to LiveKit Cloud are allowed.
a
find me the link in the docs that describe this
t
Use the SIP participant attributes doc which describes
sip.callStatus
and how to observe it (via participant metadata/attributes and events): • SIP participant attributes (includes
sip.callStatus
): https://docs.livekit.io/sip/sip-participant/#sip-attributes Additional useful pages: • Participant attributes and metadata: https://docs.livekit.io/home/client/state/participant-attributes/ • Outbound calls / creating a SIP participant (
wait_until_answered
): https://docs.livekit.io/sip/outbound-calls/ Sources: SIP participant | LiveKit docs | Participant attributes and metadata | LiveKit docs | Make outbound calls | LiveKit docs
a
is there a simpler way to directly subscribe to the participant_metadata_changed event in a room from within a tool call?
t
Yes — you can subscribe to participant metadata changes directly from an agent/tool connected to the room; that’s often the simplest way to observe
sip.callStatus
in real time. Below is a minimal, focused Python example using the LiveKit Room SDK to join a room and watch metadata changes on any SIP participant.
Copy code
# watch_metadata_simple.py
import asyncio
import logging
from livekit import Room, RoomEvent

logging.basicConfig(level=logging.INFO)

LIVEKIT_URL = "wss://your-project.livekit.cloud"
ROOM_NAME = "call-<call_uuid>"
TOKEN = "<AGENT_ROOM_TOKEN>"

def handle_sip_status(participant_id: str, metadata: dict):
    sip_status = (metadata or {}).get("sip.callStatus") or (metadata or {}).get("sip.call_status")
    logging.info(f"{participant_id} sip.callStatus={sip_status}")
    if sip_status == "ringing":
        logging.info("📞 ringing")
    elif sip_status == "active":
        logging.info("✅ answered")
    elif sip_status == "hangup":
        logging.info("❌ ended")

async def run():
    room = Room()
    await room.connect(LIVEKIT_URL, TOKEN, room=ROOM_NAME)

    # helper to attach update listener to a participant
    def watch(p):
        # check initial metadata if present
        meta = getattr(p, "metadata", None) or (getattr(p, "info", None) and getattr(p.info, "metadata", None))
        handle_sip_status(p.sid or p.identity, meta)

        # subscribe to participant updates
        async def on_updated(updated_p):
            meta = getattr(updated_p, "metadata", None) or (getattr(updated_p, "info", None) and getattr(updated_p.info, "metadata", None))
            handle_sip_status(updated_p.sid or updated_p.identity, meta)

        p.on(RoomEvent.PARTICIPANT_UPDATED, on_updated)

    # attach to existing participants
    for _, p in room.participants.items():
        watch(p)

    # attach to new participants
    async def on_connected(p):
        watch(p)
    room.on(RoomEvent.PARTICIPANT_CONNECTED, on_connected)

    await room.wait_until_disconnected()

if __name__ == "__main__":
    asyncio.run(run())
Key notes: • Join the same room the dialer created (room name = call-<call_uuid>) with a valid agent token. • The SDK exposes participant metadata on
participant.metadata
or
participant.info.metadata
depending on version; listen for
RoomEvent.PARTICIPANT_UPDATED
(aka participant metadata/attributes changed) to get
sip.callStatus
transitions. • For reliable ringing events during outbound calls, create the SIP participant with
wait_until_answered: false
so the room agent can observe
dialing
→
ringing
→
active
updates in real time. • If you prefer webhooks instead,
participant_metadata_changed
webhook delivers the same attribute updates server-side. Would you like a one-line diff to toggle
wait_until_answered
in your dialer code or a short snippet to generate an agent token for LiveKit Cloud?
a
I mean tool call as in something like a
function_tool
t
You can’t reliably register long‑running room event listeners from inside a single short‑lived
function_tool
invocation. Tool calls should be quick — subscribe to room events from the agent’s persistent process (the tool host) and have the tool read the current state when invoked. Minimal pattern: • Have a persistent watcher (agent runtime / tool host) connect to the room and subscribe to participant updates (
participant_updated
/
participant_attributes_changed
). • When that watcher sees
sip.callStatus
transitions (ringing → active → hangup), store the state in a short cache, DB, or push a message. • The
function_tool
reads that stored state (or receives a synchronous callback) when executed. Concise example — persistent watcher (Python, LiveKit Room SDK):
Copy code
# persistent_watcher.py
import asyncio, logging
from livekit import Room, RoomEvent

logging.basicConfig(level=logging.INFO)

ROOM_URL = "wss://your-project.livekit.cloud"
ROOM = "call-<call_uuid>"
TOKEN = "<AGENT_ROOM_TOKEN>"

state = {}  # in-memory; replace with Redis/DB for production

def handle_meta(p):
    meta = getattr(p, "metadata", None) or (getattr(p, "info", None) and getattr(p.info, "metadata", None)) or {}
    sip = meta.get("sip.callStatus") or meta.get("sip.call_status")
    logging.info(f"{p.identity or p.sid} sip.callStatus={sip}")
    state[p.identity or p.sid] = sip

async def run():
    room = Room()
    await room.connect(ROOM_URL, TOKEN, room=ROOM)

    # watch existing participants
    for _, p in room.participants.items():
        handle_meta(p)
        p.on(RoomEvent.PARTICIPANT_UPDATED, lambda up: handle_meta(up))

    # watch new participants
    async def on_connected(p):
        handle_meta(p)
        p.on(RoomEvent.PARTICIPANT_UPDATED, lambda up: handle_meta(up))
    room.on(RoomEvent.PARTICIPANT_CONNECTED, on_connected)

    await room.wait_until_disconnected()

if __name__ == "__main__":
    asyncio.run(run())
Minimal tool (function_tool) that reads state:
Copy code
# function_tool.py
def check_call_status(participant_id):
    # read from the same store used by the watcher (in-memory only works if same process)
    return state.get(participant_id)  # in prod, query Redis/DB or call watcher API
If you’d like, I can: • Provide a one-line change to your dialer to set
wait_until_answered: false
for testing, or • Show a small Redis-backed example so the tool and watcher can run in separate processes. Which do you prefer? Sources: SIP participant | LiveKit docs | SIP APIs | LiveKit docs | Handling events | LiveKit docs