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! Could you share a bit more about your question or what’s going on? That way, I can help you out in the best way possible.
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") study this code i want to close session immitietly once call end bye the user
t
Hey there! To close a session right when a call ends, a handy way is to keep an eye on how many participants are in the room. If it drops to zero, you can go ahead and clean things up by ending the session. Here’s a simple way to do it: • Check out the
ctx.room.participants
attribute to see how many people are still in the room. • Once the count hits zero, just call
session.end()
to wrap things up. • Don’t forget to tidy up any other resources, like ending Tavus avatar sessions too. If you want a hand setting this up or have any questions, just give me a shout—I’m here to help!
l
please provide code for this
t
Here’s a handy little code snippet that closes a session right away when a call ends:
Copy code
async def entrypoint(ctx):
    session = AgentSession()

    await session.start(
        agent=MyAgent(),
        room=ctx.room
    )

    # Keep an eye out for when participants leave
    def on_participant_disconnect(_):
        if len(ctx.room.remote_participants) == 0:
            asyncio.create_task(session.aclose())  # Close the session immediately

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

    try:
        # This keeps the session going until it’s closed or everyone leaves
        await session.wait_until_closed()
    finally:
        ctx.room.off("participant_disconnected", on_participant_disconnect)
This code listens for when participants leave and closes the session as soon as no one’s left in the room. If you want to chat more about it or need a hand with anything else, just let me know! Sources: examples/voice_agents/realtime_joke_teller.py | basics/exit_message.py | Job lifecycle | LiveKit Docs
l
provide deep week url
t
Hey there! I didn’t find the term "Deep Week" in the documentation, but if you meant "DeepWiki," here’s the link for you: https://deepwiki.com/livekit/livekit_composite If that’s not quite what you were after, just let me know—I’m happy to help you find the right info! Sources: Knowledge Management System | livekit/livekit_composite | DeepWiki | Development Tools | livekit/livekit_composite | DeepWiki
l
can you please fix my existing code
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!