dry-salesmen-44030
02/19/2026, 1:05 PMtall-airline-16756
02/19/2026, 1:05 PMtall-airline-16756
02/19/2026, 1:06 PMfrom livekit.agents import get_job_context, function_tool, RunContext
@function_tool
async def end_call(self, context: RunContext):
"""End the current call (hang up SIP) after announcing failure."""
# Let the caller know the transfer failed and we're ending the call
await context.session.generate_reply(
instructions="I'm sorry, I couldn't complete the transfer. Ending the call now."
)
# Ensure the spoken audio finishes before disconnecting
await context.wait_for_playout()
# Obtain the job context (gives access to the server-side API)
job_ctx = get_job_context()
if not job_ctx:
return "Failed to end call: No job context available"
# Delete the room to disconnect all participants (hang up SIP)
try:
await job_ctx.api.room.delete_room(
job_ctx.room.name # pass the room name/ID
)
return "Call ended successfully."
except Exception as e:
return f"Failed to end call: {e}"
How to call this when a transfer fails
1. In your transfer function, detect the transfer failure (exception, timeout, or other condition).
2. Call await self.end_call(context) to announce and hang up.
Example sketch:
@function_tool
async def transfer_call(self, context: RunContext, phone_number: str):
try:
# your transfer logic here
...
except Exception as e:
# transfer failed — end the call
return await self.end_call(context)
Notes and tips
• context.session.generate_reply() sends the agent’s voice reply; context.wait_for_playout() ensures that audio finishes before deletion.
• Deleting the room disconnects everyone, so if you need to only remove the SIP participant (not others), let me know and I can show an alternate approach if your setup supports removing individual participants instead of deleting the whole room.
• If you use different SDKs or need a JavaScript/TypeScript example, tell me which environment and I’ll provide that version.
Would you like a JS/TS version or an example that removes only the SIP participant instead of deleting the room?
Sources: SIP Lifecycle Management Agent | LiveKit Documentation | Agents telephony integration | LiveKit Documentation | Agent speech and audio | LiveKit Documentation