@function_tool async def generate_questions_from_k...
# ask-ai
i
@function_tool async def generate_questions_from_knowledge_base(query: str, job_role: str) -> str: """ Generates a list of quiz questions based on a query and a job role by searching the knowledge base. Use this tool to get all the questions you must ask the user at once. """ try: result = await generate_questions_from_context(query, job_role) logger.info(f"Tool 'generate_questions_from_knowledge_base' returned: {result}") # This function calls our new RAG pipeline return result except Exception as e: logger.error(f"Error generating questions from knowledge base: {e}") return f"An error occurred while trying to generate questions: {e}" # --- UPDATED AGENT LOGIC --- class QuizBot(Agent): def __init__(self, topic: str) -> None: # The 'topic' here is the job role (e.g., "HPLC Analyst") SYSTEM_PROMPT = f"""You are an automated training quiz bot for a '{topic}' role. Your behavior is strictly governed by the following rules. Do not deviate. Core Directive: Your ONLY task is to administer a quiz. Execution Flow: 1. Greeting: Start the conversation by greeting the user and stating you will begin the quiz on the topic of '{topic}'. 2. One-Time Question Retrieval: Immediately after the greeting, you MUST use the
generate_questions_from_knowledge_base
tool exactly ONCE and never again. Use it with these arguments: - `query`: "generate 10 quiz questions, including multiple-choice and subjective questions" - `job_role`: "{topic}" 3. Administer the Quiz: - After the tool returns a list of questions, your ONLY job is to ask them. Read each question verbatim, one by one, in the exact order received. - For multiple-choice questions, read the question and then each option clearly with a small pause. - After asking a question, say "Please provide your answer." - Once the user answers, provide a neutral transition like "Okay, moving on." and ask the next question. - User Interaction Rules: - If the user is confused: If the user expresses confusion or asks you to repeat the question (e.g., "I don't understand," "Can you say that again?"), you MUST repeat the current question verbatim and then say, "Please provide your answer." - If the user doesn't know: If the user indicates they do not know the answer (e.g., "I don't know," "skip"), you MUST respond with, "Alright, it's okay. Let's move on to the next question," and then proceed immediately to the next question. 4. Handling No Questions: If the tool returns a message indicating that no questions could be found or an error occurred, you MUST inform the user about the problem (e.g., "I couldn't retrieve any questions for this topic right now.") and then end the conversation. 5. Conclusion: After the very last question from the list has been answered, thank the user for their time and end the session. Strict Prohibitions: - Interruption Handling: If the user interrupts you while you are speaking, stop talking immediately. When it's your turn to speak again, you MUST continue your previous sentence from exactly where you left off. For example, if you were saying "Question 3: Commonly used modifiers in..." and the user spoke, your next response should be "...Reversed Phase Chromatography are...". - DO NOT end the conversation or disconnect until all questions have been administered, or if the question retrieval tool fails. - DO NOT call the
generate_questions_from_knowledge_base
tool more than once. - DO NOT invent your own questions. - DO NOT provide answers, hints, or feedback on user responses. - DO NOT engage in small talk. - IMPORTANT FOR SPEECH: Your spoken output must be clean, plain text. Do not include markdown like asterisks (
*
). """ super().__init__( instructions=SYSTEM_PROMPT, tools=[generate_questions_from_knowledge_base] ) # --- ENTRYPOINT (Unchanged) --- # --- ENTRYPOINT with Fixed Text Handling --- async def entrypoint(ctx: JobContext) -> None: await ctx.connect() logger.info("Connected to LiveKit room") department = "HPLC Analyst" # A fallback user_participant = None if ctx.room.remote_participants: user_participant = list(ctx.room.remote_participants.values())[0] if user_participant and user_participant.metadata: try: metadata = json.loads(user_participant.metadata) department = metadata.get("department", "Default Department") current_user_email = metadata.get("loggedin_user", "unknown") #fetch user id from postgres user_id=await get_id_by_email(current_user_email) logger.info(f"Here is the user id :{user_id}") if user_id is not None: logger.info(f"Found DB user_id: {user_id} for email {current_user_email}") else: logger.warning(f"No DB user found for email {current_user_email}") logger.info(f"Successfully retrieved department from USER metadata: {department}") logger.info(f"Logged in user: {current_user_email}") except json.JSONDecodeError: logger.error("Failed to parse user participant metadata.") else: logger.warning("Could not find a user participant with metadata.") base_llm = openai.LLM(model="gpt-4o-mini") session = AgentSession( vad=silero.VAD.load(), turn_detection='stt', stt=assemblyai.STT( end_of_turn_confidence_threshold=0.7, min_end_of_turn_silence_when_confident=160, max_turn_silence=2400, ), llm=base_llm, tts=openai.TTS(model="tts-1", voice="alloy"), ) #save the final conversation when the room closes async def write_transcript_on_shutdown(): ts=datetime.now().strftime("%Y%m%d_%H%M%S") room=ctx.room.name if ctx.room else "no_room" base_dir=os.path.dirname(os.path.abspath(file)) # out_dir=os.environ.get("TRANSCRIPT_DIR", "/tmp") # path=os.path.join(out_dir,f"transcript_{room}_{ts}.json") #path to the backend directory backend_dir = os.path.join(base_dir, "backend") #make sure backend directory exists os.makedirs(backend_dir, exist_ok=True) filename=f"transcript_{ts}.json" filepath=os.path.join(backend_dir,filename) answers_path=r'D:\ai_voice_project\prototype-11\backend\generated_questions\room-3a960a0d_20251028_151703.txt' # with open(filepath, "w", encoding="utf-8") as f: # json.dump(session.history.to_dict(),f,ensure_ascii=False,indent=2) transcript_data=session.history.to_dict() from result_agent import process_interview_evaluation scoreCard=process_interview_evaluation(transcript_data,answers_path) if scoreCard and "error" not in scoreCard: print(f"[scorecard] Generated successfully") print(json.dumps(scoreCard, indent=2)) conn=None try: owner_id=user_id if user_id is not None else -1 #1.connect to the database conn=await asyncpg.connect(PG_CONN_STRING) #serialize the scorecard to json for the JSONB column result_json_data=json.dumps(scoreCard) #prepare and execute the insert statement insert_query=""" INSERT INTO result_data (owner_id, result) VALUES ($1, $2) """ #execute the insert statement by giving the connection, query, owner_id and result_json_data await conn.execute(insert_query, owner_id, result_json_data) print(f"[database] Scorecard for owner_id {owner_id} saved successfully.") except Exception as e: print(f"[database] ERROR: Failed to save scorecard. Reason: {e}") finally: #ensure the connection is closed if conn: await conn.close() print("[database] Connection closed.") else: print("[scorecard] Generation failed or scorecard contains an error.") print(f"[transcript] saved -> {filepath}") ctx.add_shutdown_callback(write_transcript_on_shutdown) # Create avatar session avatar = bey.AvatarSession( avatar_id="694c83e2-8895-4a98-bd16-56332ca3f449", api_key=os.getenv("BEYOND_PRESENCE_API_KEY") ) await avatar.start(session, room=ctx.room) # Start the agent session await session.start( agent=QuizBot(topic=department), room=ctx.room, room_input_options=RoomInputOptions( text_enabled=True, noise_cancellation=noise_cancellation.BVC(), ), ) name="Hrishab Shetty" await session.generate_reply(instructions=f"greet the {name} and ask about their day") # Set up data packet handler AFTER session starts # This handler will receive data packets from the frontend def handle_data_packet(data_packet): """Handle incoming data packets from participants""" try: # Skip if from the agent itself participant = data_packet.participant if participant and hasattr(participant, 'identity'): if 'agent' in participant.identity.lower() or 'bot' in participant.identity.lower() or 'bey' in participant.identity.lower(): logger.debug(f"Skipping data from agent: {participant.identity}") return # Decode the data text = data_packet.data.decode("utf-8") logger.info(f"Received text from {participant.identity if participant else 'unknown'}: '{text}'") print(f"the users says: '{text}'") # Add the text to the session as user input # asyncio.session.generate_reply(text) # asyncio.create_task(session.generate_reply(user_input=text)) # logger.info(f"Added text to session: '{text}'") handle=session.generate_reply(user_input=text) logger.info("generate_reply returned speech handle: %s", handle) except Exception as e: logger.error(f"Error handling data packet: {e}", exc_info=True) # Register the data packet handler on the room ctx.room.on("data_received", handle_data_packet) logger.info("Data packet handler registered") if name == "__main__": mp.set_start_method('spawn', force=True) cli.run_ app(WorkerOptions(entrypoint_fnc=entrypoint)) Now why is that in this code if restart the livekit server and a new room is created the conversation goes well but if another room is created then the Agent does not respond after the 1st question
t
Thanks for reaching out, HRISHAB. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you please share a bit more about your agent implementation? Specifically: • Are you using any particular agent framework or SDK? • How are you managing the agent session state? • Have you noticed any error messages or logs that might give us clues about what's going on? Your insights will really help us understand the situation better and find the right solution together. Sources: Deploying to production | LiveKit Docs | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | Operational Best Practices | livekit/livekit_composite | DeepWiki | Job lifecycle | LiveKit Docs | delay-handling/agent.py
i
no errors are been displayed but its just that the livekit agent does not respond
t
The issue where the LiveKit agent stops responding after the first question can be a bit tricky, but don’t worry—we’re here to figure it out together. Even if no errors pop up, there are a few common reasons this might happen, so let’s walk through some possibilities and steps you can take: • Resource Contention: It’s a good idea to check that the server running the agent has enough resources and isn’t busy with other processes that might slow things down. • Network and Latency: Sometimes, network delays or less-than-ideal configurations can cause the agent to respond slowly or not at all. Taking a look here can help. • Audio Detection: The agent might be having trouble picking up audio input—this could be due to silent audio tracks or noise suppression interfering. Double-checking this can be helpful. • State Management: Keeping an eye on how the agent tracks whether it’s speaking or listening can reveal if it’s stuck in the wrong state. • Connection Timeouts: It’s worth investigating if the agent is experiencing connection timeouts or trouble maintaining a stable connection. To dig a little deeper, here are some steps you might try: 1. Monitor how much of the server’s resources are being used while the agent runs. 2. Check latency metrics like Time To First Token (TTFT) to see if there are delays. 3. Make sure you have multiple agent instances deployed to handle requests smoothly. 4. Watch the agent’s connection status and whether it’s correctly switching between speaking and listening modes. 5. Review the audio track status for any warnings about silence or audio detection issues. If you’d like, I’m more than happy to guide you through setting up these checks or help troubleshoot further. Just let me know! Sources: Knowledge Base Collection & Management | livekit/livekit_composite | DeepWi... | Troubleshooting Guide | livekit/livekit_composite | DeepWiki | Operational Best Practices | livekit/livekit_composite | DeepWiki | Understanding "silence detected on local audio track" warning | agent/main.py
i
1. Monitor how much of the server’s resources are being used while the agent runs. how to do this
t
To keep an eye on your server’s resource usage while running a LiveKit agent, here are some friendly steps you can follow: • Built-in Monitoring: LiveKit agents come with handy built-in memory monitoring. If memory usage goes beyond a certain point, you’ll see warnings in your agent logs, and the agent process will stop if it gets too high. Look out for messages like "process memory usage is high" or "process exceeded memory limit" in your logs. • Prometheus Metrics: When using LiveKit Ingress or Egress services, you can access CPU and memory metrics through Prometheus. These can be connected with tools like Grafana to create clear and insightful visual dashboards. • External Observability Tools: Platforms such as Datadog, AWS CloudWatch, or Sentry are great for monitoring runtime logs and resource usage. They offer a unified dashboard to help you keep track of both system and agent performance easily. • LiveKit CLI: During development or smaller deployments, you can use the LiveKit CLI (
lk agent logs
) to watch real-time logs and stay informed. If you’d like, I’m here to help guide you through setting up any of these monitoring options—just let me know! Sources: agents/src/ipc/supervised_proc.ts | livekit-agents/livekit/agents/ipc/supervised_proc.py | pkg/stats/monitor.go | pkg/stats/monitor.go | Logs, metrics, and telemetry | LiveKit docs
i
1.json ERRORlivekit.agentsjob shutdown is taking too much time.. 2025-11-14 110031,209 - ERROR livekit.agents - job shutdown is taking too much time.. {"tid": 10368, "job_id": "AJ_DscgE9EBCH2P"} ERRORlivekit.agentsjob shutdown is taking too much time.. 2025-11-14 110032,675 - ERROR livekit.agents - job shutdown is taking too much time.. {"tid": 22808, "job_id": "AJ_khrEeXtGnnux"} WHAT COULD BE THE CASE
t
The error "job shutdown is taking too much time" happens when the LiveKit agent process doesn’t finish shutting down within the allowed timeout. This usually means that some shutdown hooks, like cleanup tasks or saving data, are taking longer than expected. By default, the system waits 60 seconds before it forcefully stops the process. Here are a few friendly tips to help you resolve this: • Optimize Shutdown Hooks: Try to keep any cleanup or post-processing tasks in shutdown callbacks quick and efficient. It’s best to avoid long operations during shutdown. • Adjust Timeout Settings: If your shutdown tasks need a bit more time, you can increase the
shutdown_process_timeout
parameter in your worker configuration. • Proper Shutdown Handling: Make sure all asynchronous tasks in shutdown callbacks are properly awaited, and don’t forget to call
ctx.shutdown()
to start the graceful shutdown process. If you’d like, I’m here to help you walk through these changes step-by-step. Just let me know! Sources: agents/src/ipc/job_proc_lazy_main.ts | Job lifecycle | LiveKit Docs