l
hi
t
Thanks for reaching out, Pavan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! What can I help you with today?
l
@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") can you please fixed my code for session close after call end
t
Hey there! Could you help me understand a bit better what’s going on with the session closing after the call ends? For instance, is the session not closing like it should, or are you seeing any errors when it tries to clean up? If you’ve noticed any error messages or anything acting weird, please feel free to share those details—I’m here to help!
l
it is not cloasing session immitiatly taking so much time when user left
t
To make sure the session closes right away when a user leaves, here are some easy ways to handle it: • Default Automatic Closure: LiveKit automatically closes the room once the last non-agent participant leaves. Just double-check that this is turned on. • Custom Immediate Closure: You can listen for the
participant_disconnected
event and then call
await session.aclose()
to close the session immediately. • Handle Inactivity: Set up
user_away_timeout
in
AgentSession
and watch for
user_state_changed
events to close sessions when users are inactive. • Clean Up Resources: Don’t forget to call
ctx.delete_room()
after closing the session to tidy everything up properly. If you want, I’d be happy to walk you through any of these methods in more detail! Sources: Worker lifecycle | LiveKit Docs | Anatomy of an Agent | LiveKit Docs | examples/warm-transfer/warm_transfer.py | basics/exit_message.py | Agents Core Architecture | livekit/livekit_composite | DeepWiki
l
can you please proper code for this
t
Here's a friendly example to help you make sure the session closes right away when a user leaves:
Copy code
import asyncio
from livekit import rtc

async def monitor_and_close_session(ctx, session):
    room_empty_future = asyncio.get_running_loop().create_future()

    def on_participant_disconnected(participant):
        if len(ctx.room.remote_participants) == 0 and not room_empty_future.done():
            room_empty_future.set_result(None)

    ctx.room.on("participant_disconnected", on_participant_disconnected)

    # Wait for the room to become empty
    await room_empty_future

    # Close the session immediately
    await session.aclose()

    # Clean up the room
    try:
        await ctx.api.room.delete_room(ctx.room.name)
        print(f"Room {ctx.room.name} deleted successfully.")
    except Exception as e:
        print(f"Oops, something went wrong deleting room {ctx.room.name}: {e}")

# Example usage
async def main(ctx):
    session = rtc.AgentSession()
    await monitor_and_close_session(ctx, session)

# Just swap 'ctx' with your actual JobContext instance when you call main()
This snippet listens for the
participant_disconnected
event, waits until the room is empty, then closes the session and deletes the room. If you want to chat more about this or need a hand with anything else, just let me know!
l
2025-09-01 124243,478 - INFO livekit.agents - job runner initialized {"tid": 3632, "elapsed_time": 0.0} 2025-09-01 124243,478 - DEBUG asyncio - Using proactor: IocpProactor 2025-09-01 124249,502 - WARNING livekit - livekit:rtc engine453livekit:rtc_engine - received session close: "signal client closed: \"stream closed\"" UnknownReason Resume 2025-09-01 124249,506 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false} 2025-09-01 124249,508 - DEBUG livekit.agents - job exiting {"reason": "", "tid": 15288, "job_id": "AJ_ywW5N9h9Be7X"} 2025-09-01 124249,509 - DEBUG livekit.agents - http_session(): closing the httpclient ctx
t
Hey there! I noticed the logs show a session close event with the message
signal client closed: "stream closed"
. Just wanted to check in— is this the issue you're trying to sort out, or are there other problems popping up? For instance, is the session not closing like you expected, or are you seeing delays when things are cleaning up? Let me know so I can help you better!
l
yes
t
Hey there! The log message
signal client closed: "stream closed"
usually means the session is closing, but it might not be happening as quickly as you'd like. To help with that, you can make sure the session closes right away by explicitly handling the session close event and tidying up resources promptly. Here's a little updated code snippet that does just that:
Copy code
import asyncio
from livekit import rtc

async def monitor_and_close_session(ctx, session):
    room_empty_future = asyncio.get_running_loop().create_future()

    def on_participant_disconnected(participant):
        if len(ctx.room.remote_participants) == 0 and not room_empty_future.done():
            room_empty_future.set_result(None)

    ctx.room.on("participant_disconnected", on_participant_disconnected)

    # Wait for the room to become empty
    await room_empty_future

    # Close the session immediately
    await session.aclose()

    # Clean up the room
    try:
        await ctx.api.room.delete_room(ctx.room.name)
        print(f"Room {ctx.room.name} deleted successfully.")
    except Exception as e:
        print(f"Error deleting room {ctx.room.name}: {e}")

# Example usage
async def main(ctx):
    session = rtc.AgentSession()
    await monitor_and_close_session(ctx, session)

# Replace 'ctx' with your actual JobContext instance when calling main()
This code listens for the
participant_disconnected
event, waits until the room is empty, then closes the session and deletes the room. If you want me to help tweak this or if anything’s unclear, just let me know—I’m here to help!