important-kitchen-1796
11/14/2025, 5:10 AMgenerate_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 questiontall-airline-16756
11/14/2025, 5:10 AMtall-airline-16756
11/14/2025, 5:11 AMimportant-kitchen-1796
11/14/2025, 5:12 AMtall-airline-16756
11/14/2025, 5:13 AMimportant-kitchen-1796
11/14/2025, 5:14 AMtall-airline-16756
11/14/2025, 5:15 AMlk 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 docsimportant-kitchen-1796
11/14/2025, 5:32 AMtall-airline-16756
11/14/2025, 5:32 AMshutdown_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