write now whats hapening is if agent has joined on...
# ask-ai
a
write now whats hapening is if agent has joined one room and there is one more call ongoing andnif the agent joins the other room too it stops responding to one person. do i have to make instance for every detail whcih is shared in the room so that agent can soeak to multiple people at once or is there another issue
t
Thanks for reaching out, Aryan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You’re describing the exact symptom that happens when one agent instance is trying to handle multiple rooms: when the agent joins a second room it stops responding in the first. That happens because an AgentSession is tied to a single room/stream and resources (audio processing, turn detection, speech) get redirected to the new session. What you should do • Run one agent instance per room (or per publisher). Use
ServerType.ROOM
(or the per-room/job configuration) so the server spawns a separate agent process for each room. • Create a new
AgentSession
scoped to each JobContext/room; do not share a single
AgentSession
across rooms. • Ensure your deployment has enough processes/resources and enable concurrent job processing (adjust
num_idle_processes
,
loadFunc
,
drain_timeout
, etc.) so multiple agent processes can run simultaneously. If you want, tell me: 1) how you currently start your agent server (code/config), and 2) whether you use
ServerType.ROOM
or a single shared session—I'll point out the exact config/code changes to spawn separate instances. Sources: Agent server | LiveKit docs | Agent server options | LiveKit docs | Agent session | LiveKit docs
a
async def entrypoint(ctx: JobContext): """Main entrypoint for agent worker - handles EMI rooms with proper job context""" # ✅ CRITICAL FIX: Connect to database in EACH worker process global db_manager # Connect if not already connected if not db_manager.connected: await db_manager.connect() if not db_manager.connected: logger.error("❌ Failed to connect to database in worker!") return logger.info(f"🚀 EMI Agent Worker JOB RECEIVED!") logger.info(f" - Room: {ctx.room.name}") logger.info(f" - Audio chunks: {AUDIO_CHUNK_MS}ms") logger.info(f" - VAD threshold: {VAD_SILENCE_THRESHOLD}ms") logger.info(f" - DB Connected: {db_manager.connected}") if not ctx.room.name.startswith("emi-call-"): logger.info(f"⏭️ Skipping non-EMI room: {ctx.room.name}") return try: logger.info(f"🔌 Connecting to room: {ctx.room.name}") await ctx.connect() logger.info(f"✅ Connected successfully!") # ✅ OPTIMIZATION: Minimal delay before starting await asyncio.sleep(1.0) # ✅ CRITICAL FIX: Initialize with minimal defaults - will be overridden by metadata emi_data = EMIReminderInfo( language=INITIAL_LANGUAGE, borrower_name="Unknown", # Will be updated from metadata loan_id="unknown", emi_amount=0.0, due_date="Unknown", days_remaining=0, penalty_amount=0.0 ) # ✅ CRITICAL: Parse metadata from API server if hasattr(ctx.room, 'metadata') and ctx.room.metadata: try: metadata = json.loads(ctx.room.metadata) logger.info(f"📋 Raw metadata: {metadata}") # Extract core fields phone_number = metadata.get("phone_number", "unknown") loanId = metadata.get("loan_id", "unknown") call_id = metadata.get("call_id") if not call_id: logger.error("❌ call_id not found in metadata") return # ✅ FIXED: Update EMI data from metadata (multiple possible formats) if 'emi_data' in metadata: # Format 1: emi_data as nested object emi_dict = metadata['emi_data'] for key, value in emi_dict.items(): if hasattr(emi_data, key): setattr(emi_data, key, value) logger.info(f"✅ EMI data loaded from 'emi_data' key for {emi_data.borrower_name}") else: # Format 2: Fields at top level of metadata if 'borrower_name' in metadata or 'borrowerName' in metadata: emi_data.borrower_name = metadata.get('borrower_name') or metadata.get('borrowerName', 'Unknown') if 'emi_amount' in metadata or 'emiAmount' in metadata: emi_data.emi_amount = float(metadata.get('emi_amount') or metadata.get('emiAmount', 0)) if 'due_date' in metadata or 'dueDate' in metadata: emi_data.due_date = metadata.get('due_date') or metadata.get('dueDate', 'Unknown') if 'language' in metadata: emi_data.language = metadata.get('language', INITIAL_LANGUAGE) logger.info(f"✅ EMI data loaded from top-level metadata for {emi_data.borrower_name}") # Set phone and loan ID emi_data.phone_number = phone_number emi_data.loan_id = loanId logger.info(f"📞 Final EMI Data - Name: {emi_data.borrower_name}, Amount: {emi_data.emi_amount}, Due: {emi_data.due_date}") except Exception as e: logger.error(f"❌ Metadata parsing error: {e}") import traceback traceback.print_exc() agent = EMIReminderAgent(language=emi_data.language) agent.call_id = call_id stt_instance = get_stt(emi_data.language) tts_instance = get_tts(emi_data.language) logger.info(f"✅ TTS/STT ready") vad_instance = silero.VAD.load() # vad_instance.update_options( # # min_speech_duration=0.1, # # min_silence_duration=1.0, # # prefix_padding_duration=0.1, # # max_buffered_speech=10.0, # # activation_threshold=0.5 # ) session = AgentSession( vad=vad_instance, stt=stt_instance, tts=tts_instance, llm=openai.LLM( model="gpt-4o", temperature=0.7, # ✅ Lower for more consistent responses top_p=0.85, # ✅ Slightly lower for faster decoding max_completion_tokens=250, # ✅ Reduced for faster responses parallel_tool_calls=True, tool_choice="auto", # ✅ FIXED: Changed from 'low' to 'medium' (only supported value) timeout=5.0, # ✅ Reduced timeout for faster failures ), userdata=emi_data ) logger.info(f"🎤 Starting agent session...") await session.start( agent=agent, room=ctx.room, room_input_options=RoomInputOptions( audio_enabled=True, text_enabled=False, ), ) logger.info(f"✅ EMI session completed successfully") except Exception as e: logger.error(f"❌ EMI agent error: {e}") import traceback traceback.print_exc() finally: # ✅ CRITICAL FIX: Wait for ALL writes before closing try: if db_manager.connected: queue_size = db_manager.write_queue.qsize() if queue_size > 0: logger.info(f"⏳ [CLEANUP] Waiting for {queue_size} pending writes...") await db_manager.wait_for_writes(timeout=15.0) logger.info("✅ [CLEANUP] All writes completed") else: logger.info("✅ [CLEANUP] No pending writes") # Small delay to ensure everything is flushed await asyncio.sleep(0.5) except Exception as e: logger.error(f"❌ [CLEANUP] Cleanup error: {e}") import traceback traceback.print_exc() if name == "__main__": required_vars = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'] missing_vars = [var for var in required_vars if not os.getenv(var)] if missing_vars: logger.error(f"❌ Missing required environment variables: {missing_vars}") sys.exit(1) logger.info(f"✅ Environment check passed") # ✅ Connect to database before starting worker async def startup(): await db_manager.connect() if not db_manager.connected: logger.error("❌ Failed to connect to database on startup!") sys.exit(1) asyncio.run(startup()) try: cli.run_app( WorkerOptions( entrypoint_fnc=entrypoint, agent_name="emi-reminder-agent-test", worker_type=WorkerType.ROOM, load_threshold=1.0, load_fnc=worker_load, num_idle_processes=MAX_CONCURRENT_CALLS, drain_timeout=60, initialize_process_timeout=20.0 ) ) except Exception as e: logger.error(f"❌ Failed to start agent worker: {e}") import traceback traceback.print_exc() sys.exit(1) finally: # ✅ Ensure writes are flushed before exit async def shutdown(): await db_manager.wait_for_writes(timeout=10.0) await db_manager.close() asyncio.run(shutdown())this is my agent entryb point part
t
Thanks — I reviewed your entrypoint and the issue you described (agent becomes unresponsive in one room when it joins another). Good news: your code already shows the right approach for per-room agents (you're using
WorkerType.ROOM
, spawning a new session per
JobContext
, creating a fresh
AgentSession
, and connecting per-worker). That means a single shared session is not the likely cause. A few targeted checks and small fixes to help find the root cause: 1. Confirm process concurrency • Ensure
MAX_CONCURRENT_CALLS
>= number of simultaneous rooms you expect.
num_idle_processes
+ scaling must allow that many worker processes. 1. Verify each worker actually runs in its own process • When two calls are active, check your process list / logs to confirm two separate agent processes were started (one per room). Look for the per-room logs you instrumented (Room: ctx.room.name, TTS/STT ready, Starting agent session). 1. Check resource constraints • CPU, memory, or model/TT S/STT limits can cause one process to stall. Monitor host metrics during concurrent calls. 1. Confirm VAD / audio routing isolation • Each
AgentSession
creates its own
vad_instance
. Ensure
vad_instance
and STT/TTS instances are not shared globally. (In your code they appear local — good.) Also confirm LiveKit subscriptions/track routing give each process the correct participant audio (per-room connect). 1. Look for blocking calls or global locks • Search for any global state, async blocking calls, or shared DB locks during session runtime. Your DB connect per-process is correct; ensure
db_manager
methods used during the session are fully async and non-blocking. 1. Session lifecycle/timeouts • Confirm
session.start()
completes and the session remains running. Check for exceptions in the per-room logs shortly after start. Also ensure
llm.timeout=5.0
isn’t timing out often and causing session termination. If you'd like, share: • The worker startup logs from two concurrent calls (include timestamps and the per-room log lines), and • Values for
MAX_CONCURRENT_CALLS
,
num_idle_processes
, and observed host CPU/memory during the incident. I can then point to the exact log lines or code locations that indicate why one room lost responsiveness. Would you like to provide those logs?