how to check if the outbound call to a specific ph...
# ask-ai
a
how to check if the outbound call to a specific phone number was rejected in SIP livekit python?
t
Thanks for reaching out, Jacob. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to detect if an outbound SIP call to a phone number was rejected using LiveKit in Python — here are the practical ways to do that. 1) Handle the create_sip_participant response/error • Wrap the call in try/except. A rejected call triggers an exception from
create_sip_participant
. Inspect the exception metadata for
sip_status_code
and
sip_status
to see SIP rejection details.
Copy code
try:
    participant = await livekit_api.sip.create_sip_participant(request)
    print("Call initiated:", participant)
except Exception as e:
    print("Call rejected or failed:", e)
    sip_status_code = getattr(e, "metadata", {}).get("sip_status_code")
    sip_status = getattr(e, "metadata", {}).get("sip_status")
    print(f"SIP code: {sip_status_code}, SIP status: {sip_status}")
2) Monitor the participant
sip.callStatus
attribute • After initiating the call (or once your agent has joined the room), watch participant attribute changes.
sip.callStatus
values: ◦
dialing
— placing call ◦
active
— connected ◦
hangup
— rejected/disconnected • Example event handler:
Copy code
@room.on("participant_attributes_changed")
def on_attributes_changed(changed_attributes: dict[str, str], participant: rtc.Participant):
    if "sip.callStatus" in changed_attributes:
        status = participant.attributes.get("sip.callStatus")
        if status == "hangup":
            print("Call was rejected or disconnected")
        elif status == "active":
            print("Call connected successfully")
Ensure the agent monitoring the room is connected so it receives attribute updates. 3) Use wait_until_answered when creating the SIP participant • Set
wait_until_answered=True
in the
CreateSIPParticipantRequest
. The call will block until answered or rejected; rejection results in an exception immediately after the call ends.
Copy code
request = CreateSIPParticipantRequest(
    sip_trunk_id="<trunk_id>",
    sip_call_to="<phone_number>",
    room_name="my-room",
    participant_identity="caller",
    wait_until_answered=True
)
If you’d like, tell me which method you’re using (immediate API call handling, attribute monitoring, or
wait_until_answered
) and I’ll provide a focused code example tailored to your setup. Sources: Make outbound calls | LiveKit docs | SIP participant | LiveKit docs | Participant attributes and metadata | LiveKit docs
a
I am rejecting the call and then my call status is showing active.
Copy code
if participant.attributes:
                call_status = participant.attributes.get('sip.callStatus', 'Unknown')

                # Log specific call status information
                if call_status == 'active':
                    print("Call is active and connected")
                    # SUCCESS - they picked up!
                    await session.say(
                        "Hi, I have a patient on the line with a medical question. I'll let you two talk.",
                        allow_interruptions=True,
                    )
                    session.userdata.transfer_successful = True
                    return None
becuase I am hearing the session text
t
Thanks — I’m looking into why you hear session text (so your code runs) even after rejecting the call while
sip.callStatus
shows
active
. A few targeted questions to narrow this down: 1. How are you rejecting the call? (e.g., sending a SIP 486/603 via your SIP provider, calling a LiveKit method to hang up, or returning a specific response from your answer URL?) 2. Are you rejecting it before or after the LiveKit participant is created in the room? Do you create the SIP participant, then immediately reject? 3. Are you observing
sip.callStatus
changes via the room event handler (the
participant_attributes_changed
event) or by polling the participant attributes? 4. Do you see any SIP error codes or
sip_status
/
sip_status_code
in the exception metadata when the call is rejected? Quick troubleshooting steps you can try now: • Confirm you receive a
participant_attributes_changed
event with
sip.callStatus
changing to
hangup
. If you only check attributes after the fact, you may miss the change or read stale attributes. • If you use
wait_until_answered=True
, the API raises an exception when the call ends — inspect that exception for
sip_status
/
sip_status_code
. • Ensure your rejection happens at the SIP layer (provider) before the call is bridged into the LiveKit room. If LiveKit already marked the SIP participant as connected, it will set
sip.callStatus
to
active
even if the far end later hangs up — you then need to wait for the hangup attribute/event. • Add logging inside your attribute-change handler to print the full changed attributes and timestamps to verify ordering (e.g., you might be reacting to
active
before the later
hangup
arrives). If you share: • How you send the rejection (exact SIP response or code), and • Whether you’re using event handlers or
wait_until_answered
, I’ll give the precise code checks and a minimal example to ensure your flow stops speaking when the call is rejected.
a
I am just literally hanging up the phone. Not sure what i need to do to send the rejection? Do i need to configure my SIP providers for that? I am using twilio
t
Thanks — you're hanging up the phone manually and seeing LiveKit still report
sip.callStatus = active
. That usually means the SIP BYE or rejection signal from the PSTN side hasn't been surfaced to LiveKit (or your app hasn't observed the later attribute update). I can help you narrow this down and fix it. Quick facts and what to check • Hanging up a phone should send a SIP BYE (or earlier rejection like 486/603 if declined). LiveKit updates
sip.callStatus
when it receives the hangup from the SIP side. • Your SIP provider (Twilio) must forward the call state to LiveKit (via the SIP trunk or webhook behavior). If Twilio doesn't send or LiveKit doesn't receive the BYE / final SIP status, LiveKit may remain
active
until a timeout or another event. Immediate steps to diagnose 1. Check Twilio call logs / SIP logs for the call you hung up: ◦ Confirm Twilio shows a BYE (or final SIP response) when you hang up. ◦ Note any SIP response codes (486, 603, 200 BYE, etc.). 1. Verify Twilio is configured to forward call events to LiveKit: ◦ If you're using a Twilio SIP trunk to LiveKit, ensure the trunk sends the call-termination signal to the LiveKit SIP gateway. ◦ If Twilio uses a webhook/Answer URL for your SIP endpoint, confirm your webhook/path returns the correct signal and that Twilio receives a 200 OK for the hangup event. 1. Observe LiveKit-side events: ◦ Ensure your agent is connected to the room and subscribed to
participant_attributes_changed
so it receives the
sip.callStatus
transitions (you might be reading stale attributes). ◦ Add logging to print the full attribute change payload and timestamps to confirm whether/when
sip.callStatus
becomes
hangup
. Handling in code (what to add) • In addition to the existing
sip.callStatus == 'active'
branch, handle
hangup
immediately by stopping any speech or session actions:
Copy code
if call_status == "hangup":
    # stop speaking, cancel session actions
    session.stop_speaking()  # pseudocode — replace with your stop method
    session.userdata.transfer_successful = False
    return None
• Log attribute changes and any exception metadata from
create_sip_participant
to capture
sip_status
/
sip_status_code
. If Twilio needs configuration • Twilio must send call termination events to the SIP peer. Check Twilio's SIP trunk / voice settings to ensure BYE and final SIP responses are forwarded to your SIP gateway. If Twilio is answering the call and then not forwarding the BYE to LiveKit, LiveKit won't update
sip.callStatus
. If you'd like, I can: • Provide exact Twilio console locations and what log entries to look for (e.g., SIP trace showing BYE or final response). • Give a minimal Python example to stop session speech on
sip.callStatus == "hangup"
and log attribute transitions. Which would you prefer: log guidance for Twilio SIP traces, or the Python example to immediately stop the session when a hangup arrives?