acceptable-motorcycle-5430
11/27/2025, 9:58 AMcrooked-action-53836
11/27/2025, 11:49 AMacceptable-motorcycle-5430
11/27/2025, 1:00 PMcrooked-action-53836
11/28/2025, 3:50 PMimport time
import logging
import asyncio
from service.sip_call_handler_service import SipCallHandler
from utility.config_loader import ConfigLoader
logger = logging.getLogger(__name__)
class CallMonitor:
"""
Monitors user responsiveness and handles no-response scenarios with retry prompts.
Flow:
1. Agent speaks → mark_agent_waiting() → start silence timer
2. Monitor wakes every check_interval, checks silence duration
3. Silence > timeout → send retry prompt, increment counter
4. User speaks → reset_no_response() → reset counter
5. Max retries reached → final grace period → end call
Design:
- Background asyncio task, integrates via conversation_item_added events
- Lock-free (asyncio single-threaded, stale reads are safe)
- Enforces max_call_duration as safety limit
- Config-driven: all timeouts/prompts from config.yaml
"""
def __init__(self, config: dict = None):
"""Initialize with config.yaml settings (loads if not provided)."""
if config is None:
config = ConfigLoader().load()
monitoring_config = config["call_monitoring"]
self.max_no_response = monitoring_config["max_no_response_attempts"]
self.silence_timeout = monitoring_config["silence_timeout_seconds"]
self.check_interval = monitoring_config["check_interval_seconds"]
self.final_check_grace_period = monitoring_config["final_check_grace_period"]
self.max_call_duration = monitoring_config["max_call_duration_seconds"]
self.farewell_delay = monitoring_config["farewell_delay_seconds"]
self.retry_prompts = monitoring_config["retry_prompts"]
self.no_response_goodbye = monitoring_config["no_response_goodbye"]
self.max_duration_goodbye = monitoring_config["max_duration_goodbye"]
# State tracking
self.no_response_count = 0
self.silence_start_time = time.time()
self.agent_waiting_for_response = False
self.call_active = True
<http://logger.info|logger.info>(
f"CallMonitor initialized: max_attempts={self.max_no_response}, "
f"silence_timeout={self.silence_timeout}s, check_interval={self.check_interval}s, "
f"max_duration={self.max_call_duration}s, retry_prompts={len(self.retry_prompts)}"
)
async def reset_no_response(self):
"""
Reset counter when user speaks or agent becomes busy.
Order matters: Set flag False FIRST to stop monitor checks, then reset counter.
"""
old_count = self.no_response_count
self.agent_waiting_for_response = False # Stop monitoring
self.no_response_count = 0
if old_count > 0:
<http://logger.info|logger.info>(f"User responded - reset no-response counter from {old_count} to 0")
async def mark_agent_waiting(self):
"""
Mark that agent is waiting for user response.
Starts the silence timer for detecting no-response.
"""
self.silence_start_time = time.time()
self.agent_waiting_for_response = True
<http://logger.info|logger.info>(
f"Agent waiting for user response - monitoring started (attempt {self.no_response_count}/{self.max_no_response})"
)
def increment_no_response(self) -> int:
"""
Increment and return counter atomically (prevents TOCTOU bugs).
Returns count AFTER incrementing so caller can make decisions on stable value,
even if user speaks and resets counter before caller uses the returned value.
"""
self.no_response_count += 1
new_count = self.no_response_count
logger.warning(f"No response count: {new_count}/{self.max_no_response}")
return new_count
def get_retry_prompt(self, attempt_count: int) -> str:
"""
Get retry prompt for attempt (1-indexed). Reuses last prompt if attempt exceeds available prompts.
"""
attempt_index = attempt_count - 1 # Convert to 0-indexed
prompt_index = min(attempt_index, len(self.retry_prompts) - 1)
prompt_index = max(0, prompt_index)
return self.retry_prompts[prompt_index]
async def monitor_no_response_task(self, session, room, participant):
"""
Background task: Detect user silence, send retry prompts, enforce safety limits.
Algorithm (wakes every check_interval):
1. Check if session is still running → stop if closed
2. Check max_call_duration → end call if exceeded
3. If not agent_waiting_for_response → skip
4. Check silence > timeout → increment counter
5. If count < max → send retry prompt
6. If count >= max → final grace period → end call
Lock-free design: asyncio single-threaded, stale reads are safe.
TOCTOU prevention: Capture count from increment_no_response() for decisions.
"""
<http://logger.info|logger.info>(
f"Starting no-response monitoring: check every {self.check_interval}s, "
f"timeout after {self.silence_timeout}s, max_duration={self.max_call_duration}s"
)
call_start_time = time.time()
while self.call_active:
await asyncio.sleep(self.check_interval)
# Check if session is still running (stop if user disconnected)
try:
if hasattr(session, '_started') and hasattr(session, '_closed'):
if not session._started or session._closed:
<http://logger.info|logger.info>("Session closed detected - stopping monitor gracefully")
self.call_active = False
break
except Exception:
# If we can't check session state, continue - will be caught when trying to speak
pass
# Check max call duration
call_duration = time.time() - call_start_time
if call_duration > self.max_call_duration:
logger.warning(
f"Max call duration reached ({call_duration:.0f}s / {self.max_call_duration}s) - ending call"
)
try:
await session.say(self.max_duration_goodbye)
await asyncio.sleep(self.farewell_delay)
await SipCallHandler.end_call(room, participant, "max_duration_exceeded")
self.call_active = False
except Exception as e:
# Session likely closed (user disconnect, error, etc.)
if "isn't running" in str(e) or "closed" in str(e).lower():
<http://logger.info|logger.info>(f"Session already closed - stopping monitor gracefully")
else:
logger.error(f"Error ending call due to max duration: {e}")
self.call_active = False
break
# Skip check if agent not waiting
if not self.agent_waiting_for_response:
logger.debug("Monitor: Agent not waiting for response, skipping check")
continue
# Check silence duration
silence_duration = time.time() - self.silence_start_time
logger.debug(f"Monitor: Silence duration: {silence_duration:.1f}s (threshold: {self.silence_timeout}s)")
if silence_duration > self.silence_timeout:
# Capture count atomically (prevents TOCTOU)
current_count = self.increment_no_response()
if current_count >= self.max_no_response:
# Max retries reached - final safety check before ending
logger.warning(f"Max no-response attempts reached ({current_count}/{self.max_no_response}) - final check before ending call")
# Grace period to catch in-flight user speech
await asyncio.sleep(self.final_check_grace_period)
# Final check: Did user speak during grace period?
if not self.agent_waiting_for_response:
<http://logger.info|logger.info>("Monitor: User responded during final check - canceling call end")
continue
# Confirmed no response - end call
logger.warning(f"Monitor: Confirmed no response - ending call now")
try:
await session.say(self.no_response_goodbye)
await asyncio.sleep(self.farewell_delay)
await SipCallHandler.end_call(room, participant, "no_response_timeout")
self.call_active = False
except Exception as e:
# Session likely closed (user disconnect, error, etc.)
if "isn't running" in str(e) or "closed" in str(e).lower():
<http://logger.info|logger.info>(f"Session already closed - stopping monitor gracefully")
else:
logger.error(f"Error ending call: {e}")
self.call_active = False
break
else:
# Send retry prompt (use captured count, not self.no_response_count)
retry_prompt = self.get_retry_prompt(current_count)
<http://logger.info|logger.info>(f"Prompting user (attempt {current_count}): {retry_prompt}")
try:
await session.say(retry_prompt)
logger.debug(f"Retry prompt sent")
except Exception as e:
# Session likely closed (user disconnect, error, etc.)
if "isn't running" in str(e) or "closed" in str(e).lower():
<http://logger.info|logger.info>(f"Session closed during retry prompt - stopping monitor gracefully")
else:
logger.error(f"Error sending retry prompt: {e}")
self.call_active = False
breakcrooked-action-53836
11/28/2025, 3:51 PM"""
SIP call handler for managing telephony call termination.
Provides utilities to properly hang up SIP calls while preserving logs.
"""
import logging
import os
import asyncio
import aiohttp
from livekit import rtc
from livekit.api import room_service
logger = logging.getLogger(__name__)
class SipCallHandler:
"""
Handles SIP call termination using LiveKit RoomService API.
This approach removes the SIP participant to trigger proper SIP BYE signal,
then disconnects the agent, allowing the room to auto-close naturally.
This preserves all call logs, recordings, and analytics in LiveKit Cloud.
"""
@staticmethod
async def end_call(room: rtc.Room, participant: rtc.RemoteParticipant, reason: str = "call_ended") -> None:
"""
Properly end a SIP call by removing the participant and disconnecting.
Args:
room: The LiveKit room containing the call
participant: The SIP participant to remove
reason: Brief reason for ending the call (for logging)
Note:
Exceptions are caught and logged. If RoomService API fails, falls back to room.disconnect().
This method never raises exceptions.
"""
<http://logger.info|logger.info>(f"Ending SIP call - Reason: {reason}")
try:
livekit_url = os.getenv("LIVEKIT_URL")
livekit_api_key = os.getenv("LIVEKIT_API_KEY")
livekit_api_secret = os.getenv("LIVEKIT_API_SECRET")
if not all([livekit_url, livekit_api_key, livekit_api_secret]):
logger.error("Missing LiveKit API credentials, falling back to room.disconnect()")
await room.disconnect()
return
# Remove the SIP participant to trigger proper SIP hangup
# This keeps room logs intact while ending the phone call
async with aiohttp.ClientSession() as session:
svc = room_service.RoomService(session, livekit_url, livekit_api_key, livekit_api_secret)
await svc.remove_participant(room_service.RoomParticipantIdentity(
room=room.name,
identity=participant.identity
))
<http://logger.info|logger.info>(f"SIP participant {participant.identity} removed - call ending")
# Give a moment for the participant removal to process
await asyncio.sleep(1)
# Then disconnect the agent - room will auto-close and preserve logs
await room.disconnect()
<http://logger.info|logger.info>("Agent disconnected - SIP call ended successfully")
except Exception as e:
logger.error(f"Error ending call via RoomService: {e}")
# Fallback to simple disconnect
await room.disconnect()
<http://logger.info|logger.info>("Fallback: Disconnected from room")crooked-action-53836
11/28/2025, 3:51 PMthis is the code i am using, hope this helps