@staticmethod
async def entrypoint(ctx: JobContext):
"""Entrypoint function that runs a single session"""
await ctx.connect()
global _session_running, _session_lock, _last_speech_time
# Prevent multiple sessions from running
async with _session_lock:
try:
logger.info(f"Starting single session - {time.strftime('%Y-%m-%d %H:%M:%S')}")
# Initialize user data for new session
userdata = UserData()
# Parse metadata first
try:
metadata = json.loads(ctx.job.metadata)
# print(f"Parsed metadata: {metadata}")
except Exception as e:
print(f"Error parsing metadata: {e}")
metadata = {}
# Extract voice_id, language_code, replica_id, and persona_id from metadata
voice_id = metadata.get('voice_id')
language_code = metadata.get('language_code')
replica_id = metadata.get('replica_id', 'r4317e64d25a') # Default fallback
persona_id = metadata.get('persona_id', 'p5d11710002a') # Default fallback
agent = None
print("metadata :",metadata)
if metadata.get('agent_name') == 'multi-lingual-health-assistant':
agent = HospitalAssistant(metadata=metadata)
elif metadata.get('agent_name') == 'mincron-erp-assistant':
agent = MincronAssistant(metadata=metadata)
else:
agent = VishwakarmaAssistant(metadata=metadata)
# Create session with agent's custom STT and TTS
session = AgentSession[UserData](
userdata=userdata,
stt=agent.custom_stt, # Use agent's custom STT
llm=azure_llm,
tts=agent.tts, # Use agent's custom TTS
vad=silero.VAD.load(),
max_tool_steps=5,
)
tavus_avatar = tavus.AvatarSession(persona_id=persona_id, replica_id=replica_id, api_key=os.getenv("TAVUS_API_KEY"))
session_start_time = time.time()
try:
# Try to start Tavus avatar with error handling
try:
await tavus_avatar.start(session, room=ctx.room)
except Exception as tavus_error:
logger.error(f"Failed to start Tavus avatar: {tavus_error}")
if any(phrase in str(tavus_error).lower() for phrase in [
"maximum concurrent conversations",
"out of conversational credits",
"rate limit"
]):
logger.error("Tavus API limit reached - cannot start session")
return
else:
raise tavus_error
await session.start(
agent=agent,
room=ctx.room,
room_output_options=RoomOutputOptions(
audio_enabled=False, # Let Tavus handle audio
),
)
# Wait for session completion or timeout
timeout_task = asyncio.create_task(asyncio.sleep(SESSION_TIMEOUT_SECONDS))
# Monitor session state
session_completed = False
last_participant_count = 0
empty_room_start_time = None
consecutive_empty_checks = 0
last_activity_time = time.time()
while not session_completed and not timeout_task.done():
# Check if session is still active
if hasattr(session, 'is_active') and not session.is_active():
session_completed = True
logger.info("Session marked as inactive - ending session")
break
# Check if room is empty or participants disconnected
try:
current_participant_count = len(ctx.room.participants) if hasattr(ctx.room, 'participants') else 1
except:
current_participant_count = 1 # Assume at least one participant if we can't check
# Log session state periodically for debugging
if time.time() % 30 < 4: # Log every 30 seconds
logger.debug(f"Session state: participants={current_participant_count}, empty_time={time.time() - empty_room_start_time if empty_room_start_time else 0:.1f}s, consecutive_checks={consecutive_empty_checks}")
# If participants are present, reset empty room tracking and update activity time
if current_participant_count > 0:
empty_room_start_time = None
consecutive_empty_checks = 0
last_participant_count = current_participant_count
last_activity_time = time.time()
else:
# Room is empty - start tracking
if empty_room_start_time is None:
empty_room_start_time = time.time()
consecutive_empty_checks = 1
else:
consecutive_empty_checks += 1
# Check if there was a sudden drop in participants (likely a disconnection)
if last_participant_count > 0 and current_participant_count == 0:
logger.info(f"Sudden participant drop detected: {last_participant_count} -> {current_participant_count}")
# Only end session if room has been empty for a significant time (5 minutes)
# and we've checked multiple times to avoid false positives
# Also ensure we haven't spoken recently (within last 2 minutes)
time_since_last_speech = time.time() - _last_speech_time
if (time.time() - empty_room_start_time > 300 and consecutive_empty_checks >= 75 and time_since_last_speech > 120):
session_completed = True
logger.info(f"Room empty for {time.time() - empty_room_start_time:.1f} seconds with {consecutive_empty_checks} consecutive checks and {time_since_last_speech:.1f}s since last speech - ending session")
break
# Small delay before checking again
await asyncio.sleep(2) # Increased from 2 to 4 seconds
# Cancel timeout task if session completed naturally
if session_completed:
timeout_task.cancel()
logger.info("Session completed naturally")
else:
logger.info(f"Session timed out after {SESSION_TIMEOUT_MINUTES} minutes")
except Exception as e:
logger.error(f"Error in session: {e}")
# Check if it's a Tavus API error
if "maximum concurrent conversations" in str(e) or "out of conversational credits" in str(e):
logger.error("Tavus API limit reached - session cannot continue")
else:
logger.error(f"Session error: {e}")
finally:
# Ensure proper cleanup
try:
if hasattr(tavus_avatar, 'end') and callable(tavus_avatar.end):
await tavus_avatar.end()
elif hasattr(tavus_avatar, 'close') and callable(tavus_avatar.close):
await tavus_avatar.close()
except Exception as e:
logger.error(f"Error ending Tavus avatar session: {e}")
# Clean up session
try:
if hasattr(session, 'end') and callable(session.end):
await session.end()
except Exception as e:
logger.warning(f"Error ending session: {e}")
# Delete the room
try:
request = api.DeleteRoomRequest(room=ctx.room.name)
await ctx.api.room.delete_room(request)
logger.info(f"Room {ctx.room.name} deleted successfully.")
except Exception as e:
logger.error(f"Error deleting room {ctx.room.name}: {e}")
# Calculate session duration
session_duration = time.time() - session_start_time
logger.info(f"Session ended after {session_duration:.2f} seconds")
_session_running = False
logger.info("Session cleanup completed")
finally:
_session_running = False
logger.info("Session cleanup completed")
study this code i want to close session immitietly once call end bye the user