<@U07FRRZH2GN> I'm building a voice AI agent usin...
# ask-ai
f
@icy-policeman-64898 I'm building a voice AI agent using the LiveKit Agents Python SDK and need to reliably capture call outcome data and store it in MongoDB when calls end. I'm experiencing inconsistent behavior with the disconnect handler. Current Setup: - Python voice agent using
livekit.agents.voice.Agent
- SIP trunk integration for outbound calls - Room-based architecture (one room per call) - Using
on_room_disconnected
event handler to detect call end Data I need to capture when each call ends: 1. Call outcome (answered, no_answer, voicemail, failed) 2. Call duration (total seconds from start to disconnect) 3. Disconnection reason (user hung up, voicemail detected, connection failed, etc.) 4. Number of user responses/turns 5. Transcript data (already being saved to file) 6. Ended timestamp Problem: My
on_room_disconnected
handler fires inconsistently: - ✅ Works reliably for no-answer calls (~30 second updates) - ❌ Often fails to fire for answered calls where user talks and hangs up - When it fails, the database stays at
status="initiated"
forever Current Implementation:
Copy code
python
async def entrypoint(ctx: JobContext, ...):
    # ... agent setup ...

    async def on_room_disconnected():
        """Called when room disconnects - should update database"""
        logger.info(":electric_plug: Room disconnected, updating call outcomes...")

        # Calculate duration
        call_duration = (datetime.now() - call_start_time).total_seconds()

        # Determine outcome based on conversation
        if detected_voicemail:
            outcome = "voicemail"
            reason = "voicemail_detected_by_llm"
        elif user_response_count >= 2:
            outcome = "answered"
            reason = "successful_conversation"
        else:
            outcome = "no_answer"
            reason = "no_user_response"

        # Update MongoDB
        await mongo_manager.update_call_outcome(
            call_id=call_id,
            outcome=outcome,
            reason=reason,
            metadata={"duration": call_duration, ...}
        )

    # Register handler
    ctx.room.on("disconnected", on_room_disconnected)
Questions: 1. Is
room.on("disconnected")
the right event
to capture when a SIP call ends? Or should I use a different event? 2. Why might this event not fire consistently for answered calls vs no-answer calls? 3. Are there alternative hooks to guarantee I capture call end data? (agent lifecycle events, participant disconnect, etc.) 4. Should I be using
ctx.add_shutdown_callback()
instead or in addition to room disconnect? 5. For SIP trunk calls specifically, is there a SIP-level disconnect event I should monitor? 6. Best practices: What's the recommended pattern for persisting call metadata when using LiveKit for production telephony? Workaround I'm using: I have a background cleanup task that runs every 5 minutes, finds calls stuck at
status="initiated"
, checks for transcript files, and backfills the data. This works but adds 5-10 minute delay. Ideal outcome: Immediate (< 5 second) database update when any call ends, regardless of outcome type. Any guidance on the correct event lifecycle hooks or patterns for reliable call-end detection would be greatly appreciated!
t
Thanks for reaching out, Abhishek. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you reliably capture call outcome data and know exactly when a SIP call ends using the LiveKit Agents Python SDK, here are some friendly best practices to consider: • Keep an Eye on Participant Disconnection Events: Instead of using
room.on('disconnected')
, try using the
participant_disconnected
event. This way, you’ll catch when the SIP participant leaves the room — a clear sign the call has ended. • Watch Participant Attributes Closely: Keep track of attributes like
sip.callStatus
and listen for
participant_attributes_changed
events. This helps you spot updates such as when a call connects or fails. • Use Explicit Room Deletion: Calling the server API
delete_room
is a great way to definitively end the call for everyone involved, making sure the session wraps up neatly. • Detect Silence and Voicemail: Adding silence detection and LLM-based voicemail detection can be really useful for handling cases like voicemail systems or inactive calls. • Register Shutdown Callbacks: Don’t forget to use
ctx.add_shutdown_callback()
to tidy up any background tasks and manage resources properly. Following these steps should help you get consistent and quick (<5 seconds) updates to your database when calls end. If you’d like, I’m here to provide more details or share some code examples for any of these methods — just let me know! Sources: Making outbound calls | LiveKit Docs | Agent Testing & CI/CD | livekit/livekit_composite | DeepWiki | examples/voice_agents/error_callback.py | telephony/sip_lifecycle.py | Agents telephony integration | LiveKit Docs