My Code import json import aiohttp import asyncio...
# ask-ai
f
My Code import json import aiohttp import asyncio from uuid import uuid4 from dotenv import load_dotenv from typing import AsyncIterable, Literal, Tuple, Dict, Any, Optional, List from pathlib import Path from datetime import datetime, timezone from openrouter_client import call_openrouter_messages, OpenRouterError from livekit.agents import ( Agent, AgentSession, JobContext, JobProcess, RoomInputOptions, WorkerOptions, cli, FunctionTool, ModelSettings, inference, APIConnectOptions ) from livekit.agents import llm from livekit.plugins import noise_cancellation, silero from livekit.plugins.turn_detector.multilingual import MultilingualModel from livekit.agents.llm import ChatContext, ImageContent from livekit import rtc load_dotenv(".env.local") WorkKind = Literal["speak", "action", "canvas_changes"] WorkItem = Tuple[WorkKind, str] WorkBatch = List[WorkItem] LONG_TIMEOUT = APIConnectOptions( max_retry=3, retry_interval=2.0, timeout=40.0, ) class LongTimeoutLLM(inference.LLM): def chat( self, *, chat_ctx: llm.ChatContext, tools: list[llm.FunctionTool | llm.RawFunctionTool] | None = None, conn_options: APIConnectOptions = LONG_TIMEOUT, **kwargs, ) -> llm.LLMStream: # Always use LONG_TIMEOUT, ignore whatever AgentSession passes return super().chat( chat_ctx=chat_ctx, tools=tools, conn_options=LONG_TIMEOUT, **kwargs, ) class Assistant(Agent): def __init__(self, room: rtc.Room): super().__init__( instructions="You are an AI Tutor assistant. Your role is to help students learn effectively." ) self.room = room async def process_batches(self): for batch_idx, batch in enumerate(self.all_work_batch, start=1): prefetch_task: Optional[asyncio.Task] = None # If last item is canvas_changes, start prefetch # if batch and batch[-1][0] == "canvas_changes": # last_changes = batch[-1][1] # prefetch_task = asyncio.create_task( # self.create_canvas_actions(last_changes) # ) for kind, payload in batch: if kind == "speak": await self.session.say(payload, allow_interruptions=True) elif kind == "canvas_changes": print(payload) async def llm_node( self, chat_ctx: llm.ChatContext, tools: List[FunctionTool], model_settings: ModelSettings, ) -> AsyncIterable[llm.ChatChunk]: buffer = "" current_batch: List[WorkItem] = [] all_batches: List[WorkBatch] = [] tag_pairs = [ ("<what_to_explain_now>", "</what_to_explain_now>", "plan"), ("<current_canvas>", "</current_canvas>", "current"), ("<new_changes_on_canvas>", "</new_changes_on_canvas>", "changes"), ("<speak>", "</speak>", "speak"), ("<canvas_changes>", "</canvas_changes>", "canvas_changes"), ("<update_name>", "</update_name>", "update_name"), ("<create_new_page>", "</create_new_page>", "create_page"), ] async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings): if chunk.delta and chunk.delta.content: buffer += chunk.delta.content while True: earliest = None for open_tag, close_tag, kind in tag_pairs: s = buffer.find(open_tag) if s == -1: continue e = buffer.find(close_tag, s + len(open_tag)) if e == -1: continue if earliest is None or s < earliest[0]: earliest = (s, e, kind, open_tag, close_tag) if earliest is None: break s, e, kind, open_tag, close_tag = earliest inner = buffer[s + len(open_tag) : e].strip() buffer = buffer[:s] + buffer[e + len(close_tag) :] if not inner: continue if kind == "speak": current_batch.append(("speak", inner)) elif kind == "canvas_changes": current_batch.append(("canvas_changes", inner)) all_batches.append(current_batch.copy()) current_batch.clear() elif kind == "update_name": if not self.pending_title_update and inner.strip(): self.pending_title_update = inner.strip() elif kind == "create_page": if not self.pending_new_page_title and inner.strip(): self.pending_new_page_title = inner.strip() if current_batch: all_batches.append(current_batch.copy()) self.all_work_batch = all_batches self._kickoff_processing_if_idle() def _kickoff_processing_if_idle(self): if not self._processing_batches: asyncio.create_task(self._run_batches_safe()) async def _run_batches_safe(self): if self._processing_batches: return self._processing_batches = True try: async with self._process_lock: await self._apply_pending_page_create() await self._apply_pending_title_update() await self.process_batches() finally: self._processing_batches = False def prewarm(proc: JobProcess): proc.userdata["vad"] = silero.VAD.load() async def entrypoint(ctx: JobContext): print("[ENTRYPOINT] starting") # --- construct assistant + session --- try: assistant = Assistant(room=ctx.room) print("[ENTRYPOINT] assistant created") session = AgentSession( stt="assemblyai/universal-streaming:en", llm=LongTimeoutLLM.from_model_string("google/gemini-2.5-flash"), tts=inference.TTS( model="cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc", language="en", extra_kwargs={"speed": 0.9, "volume": 1.2}, ), turn_detection=MultilingualModel(), vad=ctx.proc.userdata["vad"], ) print("[ENTRYPOINT] session created") except Exception as e: print(f"[ENTRYPOINT] Error creating assistant/session: {e}") return # --- connect to the LiveKit room --- print("[ENTRYPOINT] calling ctx.connect()") try: await ctx.connect() print("[ENTRYPOINT] ctx.connect() finished") except Exception as e: print(f"[ENTRYPOINT] ctx.connect() failed: {e}") return # --- clear session files (optional hygiene) --- try: assistant._clear_session_files() print("[ENTRYPOINT] cleared session files") except Exception as e: print(f"[ENTRYPOINT] Failed to clear session files: {e}") # --- read session UUID from room metadata --- try: meta = json.loads(ctx.room.metadata or "{}") print(f"[ENTRYPOINT] room metadata: {meta}") session_uuid = meta.get("sessionId") print(f"[ENTRYPOINT] session_uuid: {session_uuid}") except Exception as e: print(f"[ENTRYPOINT] Error parsing room metadata: {e}") session_uuid = None if not session_uuid: print("[ENTRYPOINT] No session_uuid found, telling user and returning") await session.say("Hello! I couldn’t find your session. Please try again.") return base_prompt = "" prompt_text = "" images: List[str] = [] # --- fetch dynamic prompt from your backend --- try: print(f"[ENTRYPOINT] Fetching dynamic prompt for session {session_uuid}") async with aiohttp.ClientSession() as http_session: url = f"http://localhost:3000/start-learning-prompt/{session_uuid}" async with http_session.get( url, timeout=aiohttp.ClientTimeout(total=7.0) ) as resp: print(f"[ENTRYPOINT] HTTP GET {url} -> {resp.status}") if resp.status == 200: data = await resp.json() base_prompt = data.get("basePrompt", "") or "" prompt_text = data.get("promptText", "") or "" images = data.get("images", []) or [] print( "[ENTRYPOINT] Loaded dynamic prompt: " f"base_prompt_len={len(base_prompt)}, " f"prompt_text_len={len(prompt_text)}, " f"num_images={len(images)}" ) else: print( f"[ENTRYPOINT] Failed to fetch dynamic prompt: HTTP {resp.status}" ) except asyncio.TimeoutError: print("[ENTRYPOINT] Timeout fetching dynamic prompt") except Exception as e: print(f"[ENTRYPOINT] Error fetching dynamic prompt: {e}") if not images and not prompt_text and not base_prompt: print("[ENTRYPOINT] No prompt content found; informing user and returning") await session.say("I couldn’t load your lesson content. Please try again.") return # --- update assistant instructions --- try: print("[ENTRYPOINT] Updating assistant instructions") await assistant.update_instructions(base_prompt) print("[ENTRYPOINT] Instructions updated") except Exception as e: print(f"[ENTRYPOINT] Error updating instructions: {e}") await session.say( "I couldn’t load the lesson instructions. Please try again." ) return # --- seed initial chat context with text + images --- initial_ctx = ChatContext() parts: List[Any] = [] if prompt_text: parts.append(prompt_text) for img_b64 in images: if img_b64: parts.append( ImageContent( image=f"data:image/png;base64,{img_b64}" ) ) initial_ctx.add_message( role="user", content=parts, ) print("[ENTRYPOINT] Initial chat context prepared") try: await assistant.update_chat_ctx(initial_ctx) print("[ENTRYPOINT] Assistant chat context updated") except Exception as e: print(f"[ENTRYPOINT] Error updating assistant chat context: {e}") # Not fatal, but you can return here if you want strict behavior # return # --- start the LiveKit AgentSession --- print("[ENTRYPOINT] Starting AgentSession") await session.start( agent=assistant, room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) print("[ENTRYPOINT] AgentSession started") if name == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm)) 2025-11-17 133302,103 - INFO livekit.agents - process initialized {"pid": 20824, "elapsed_time": 0.77} 2025-11-17 133302,103 - DEBUG asyncio - Using selector: KqueueSelector {"pid": 20824, "job_id": "AJ_ApsBVZ5UwZvd"} [ENTRYPOINT] starting [ENTRYPOINT] assistant created [ENTRYPOINT] session created [ENTRYPOINT] calling ctx.connect() 2025-11-17 133312,208 - WARNING livekit.agents - The room connection was not established within 10 seconds after calling job_entry. This may indicate that job_ctx.connect() was not called. {"pid": 20824, "job_id": "AJ_ApsBVZ5UwZvd"} it getting stuck here? why so? it gets stuck here, why so?
t
Thanks for reaching out, arpit. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand how frustrating it can be when the connection seems to get stuck after calling
ctx.connect()
. Let’s walk through some common reasons this might happen and see if we can get things moving smoothly for you: • Missing Participant Wait Logic: Sometimes, if the agent is waiting for participants to join but none do, it might look like it’s stuck. Using
ctx.wait_for_participant()
can help manage this waiting period properly. • Event Listener Setup: It’s important to set up event listeners (like for
participant_connected
) before calling
ctx.connect()
, so events are handled right away. • Connection Timeout Warning: If the connection isn’t established within 10 seconds, it’s a good idea to double-check your room and token configurations. • Session Management: For more complex setups, make sure all asynchronous operations are well coordinated to avoid any hiccups. • Error Handling: Adding proper exception handling for connection failures can really help catch issues early. To dig a bit deeper, try checking your logs for any warnings, verify your room and token settings, and confirm that event handling and timeouts are set up correctly. If you’d like, I’m here to help you with specific code tweaks or any other troubleshooting steps. Just let me know! Sources: Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | livekit-agents/livekit/agents/job.py | meditation_assistant/agent.py | Building an Automated IVR Menu Caller | LiveKit Docs | Troubleshooting Guide | livekit/livekit_composite | DeepWiki
f
You must call
await ctx.connect()
first – only then can you check for / wait for participants. After connecting,
JobContext
already gives you a helper:
ctx.wait_for_participant(...)
.
t
You're absolutely right, and I’m glad you brought this up! The
await ctx.connect()
call does need to happen first to establish that connection. Once that’s set, you can then use
ctx.wait_for_participant(...)
to wait for participants. This way, you’re making sure everything is nicely connected before handling any participant events. If you’d like, I’m here to help you walk through the implementation or debug anything along the way—just let me know!
f
but my ctx.connect is not working correctly, why so? i have shared the above code with you
t
I'm sorry to hear you're having trouble with
ctx.connect()
. Let's work through some common reasons this might happen together: • Connection Timeout: Sometimes the connection might take longer than the default 20 seconds. You can try increasing the timeout to see if that helps. • Network Issues: Firewalls or VPNs can sometimes block WebSocket, WebRTC, or TURN connections. You might want to use LiveKit's connection test tools to check if something is being blocked. • Worker Availability: It's good to double-check that your agent workers are up and running, and properly registered with the LiveKit server. • Invalid URL or Token: Make sure that the server URL and token you're using are accurate and haven't expired. • Environment Support: Confirm that your environment supports WebRTC and all the necessary APIs for the connection. For next steps, I recommend looking at the logs for any error messages, validating your network setup, and ensuring your worker processes are active. If you'd like, I'm here to help you with any specific diagnostics or adjustments you want to try. Just let me know! Sources: packages/react/src/hooks/useAgent.ts | Diagnosing Connection Errors with Connection Test Utility | Operational Best Practices | livekit/livekit_composite | DeepWiki | src/room/Room.ts
f
token and everything is correct
t
Thanks for confirming that the token and configuration are correct! To help you better, could you please share a bit more about what happens when you call
ctx.connect()
? For example: • Do you see any error messages or warnings in the logs? • Does the connection time out, or does it seem to hang without responding? • Have you had a chance to test the network connectivity using LiveKit's connection test tools? Getting these details will really help us figure out what’s going on and find the best solution for you.
f
2025-11-17 135323,073 - WARNING livekit.agents - The room connection was not established within 10 seconds after calling job_entry. This may indicate that job_ctx.connect() was not called. {"pid": 22983, "job_id": "AJ_9B849bBGj6jQ"} i see this
t
It looks like the warning is letting us know that the room connection wasn’t established within 10 seconds after calling
job_ctx.connect()
. This can happen for a few reasons, so let’s walk through them together: • Network Issues: Sometimes firewalls or VPNs might block WebSocket, WebRTC, or TURN connections. It’s a good idea to use LiveKit’s connection test tools to check if everything’s clear on your end. • Worker Availability: Make sure that your agent workers are up and running, and properly registered with the LiveKit server to handle the session smoothly. • Timeout Configuration: By default, the timeout is set to 20 seconds. If your connection is taking longer, adjusting this timeout might help. To get this sorted, try checking your network setup, confirming the workers are active, and keeping an eye on the logs for any other clues. If you’d like, I’m here to help you with any of these steps—just let me know!
f
• Worker Availability: Make sure that your agent workers are up and running, and properly registered with the LiveKit server to handle the session smoothly. how can i do this?
t
Let's make sure your agent workers are up and running smoothly with the LiveKit server. Here’s a simple guide to help you through: • Worker Registration: When a worker starts, it connects to the LiveKit server via WebSocket and sends a registration request. You can check the server logs for a message like
"worker registered"
that includes details such as
namespace
,
jobType
, and
workerID
. This confirms the worker is recognized. • Agent Token: It’s important that the worker uses a valid access token with the
agent
grant in the VideoGrant. Without this, the server won’t accept the connection, so double-check this part. • Health Checks: Workers send status updates regularly to let the server know they’re healthy and available. This helps keep everything running smoothly. • Job Assignment: Once registered properly, workers will get job assignment requests when new rooms are created or tracks are published. Keep an eye on these to confirm things are working as expected. • Deployment: For the best reliability, try deploying multiple workers per
agent_name
, allocate resources specifically for agents, and consider using load balancing and auto-scaling. If you’d like, I’m here to help you verify the logs or walk you through setting up your workers. Just let me know! Sources: pkg/service/agentservice.go | livekit-agents/livekit/agents/worker.py | LiveKit Docs | Operational Best Practices | livekit/livekit_composite | DeepWiki
f
these are the logs i can see over dashboard
t
Thanks so much for sharing the logs! It looks like the room is being created successfully, and participants are joining and leaving just as expected. That’s great to see. 😊 However, it seems the challenge might be with the agent worker’s ability to handle the session smoothly or maintain a steady connection. To help us dig a little deeper, could you please: • Check if the agent worker logs show successful registration with the LiveKit server (look out for messages like
"worker registered"
). • See if the worker is receiving job assignments after the room is created. • Make sure the worker’s environment has enough resources and isn’t facing any connectivity hiccups. If you’d like, I’m here to help you access or understand the worker logs, or if there’s anything else you want to share, just let me know. We’ll get this sorted together!