I am using the on_track_subscribed event in the en...
# ask-ai
m
I am using the on_track_subscribed event in the entrypoint function to get the identity of the user and update the instructions to the agent as per the participant ,On the first connect when I click on start call agent starts and work fine but when I end call,and click on start call again it says Agent not running ,no activity context found ,How can I resolve this error.In this case ,Agent does not response with anything it gets stuck at this point.If I give 1 min time between Stopping call and Starting it again it works fine without error.
t
Thanks for reaching out, Dikshant. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
It looks like the error you're seeing happens because the agent session isn’t fully initialized or might have been stopped when you try to start the call again. Don’t worry, we can work through this together! Here are some steps that can help resolve the issue: 1. Make sure the agent session is properly started before handling the
on_track_subscribed
event. The session needs to be up and running before any track subscription events are processed. 2. Add some checks in your
on_track_subscribed
event handler to confirm that the agent session is active. For example, check if the agent’s activity context isn’t
None
before moving forward with any operations. 3. Consider adding a short delay or a retry mechanism to give the agent session enough time to fully initialize before processing the event. Sometimes the session needs a moment to become active after restarting. 4. Keep an eye on the agent session state transitions so your event handlers only run when the agent is ready. Using logging can really help track the session’s lifecycle and spot any issues during initialization or cleanup. 5. Make sure to properly clean up the agent session and room connection when ending a call. This helps avoid any leftover references that might cause problems when restarting the session. If you’d like, I’m here to help you implement these steps or provide more detailed guidance and code examples. Just let me know! Sources: examples/multiple_connections.py | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | agents/src/job.ts | src/room/participant/LocalParticipant.ts | livekit-agents/livekit/agents/voice/agent_session.py
m
@ctx.room.on("participant_disconnected") def on_participant_disconnected(participant: rtc.RemoteParticipant): """Called when a user leaves the room""" logger.info(f"User disconnected: {participant}") @ctx.room.on("participant_connected") def on_participant_connected(participant: rtc.RemoteParticipant): """Called when a user enters the room""" logger.info(f"User Connected: {participant}" ) @ctx.room.on("track_subscribed") def on_track_subscribed( track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant, ) -> None: """ Event handler triggered when a remote participant's track is subscribed. Responsibilities: - Extract and log session metadata (session GUID). - Populate appointment assistant user context (name, email, etc.). - Retrieve and set user-related information from the database. - Generate and append contextual instructions asynchronously. Args: track (rtc.Track): The subscribed media track. publication (rtc.RemoteTrackPublication): Publication details. participant (rtc.RemoteParticipant): Remote participant whose track was subscribed. """ try: if not appointment_scheduling_assistant: logger.warning("[on_track_subscribed] Appointment scheduling assistant is not initialized.") return # Extract session GUID from participant metadata if participant.metadata: import json metadata = json.loads(participant.metadata) session_guid = metadata.get("sessionGuid") if session_guid: logger.info(f"[on_track_subscribed] Session GUID: {session_guid}") else: logger.debug("[on_track_subscribed] No session GUID found in metadata.") # Update user information in the assistant session user_data = appointment_scheduling_assistant.session.userdata user_data.user_name = participant.name user_data.user_email = participant.identity user_data.session_guid = session_guid # Check if the user can be identified if not user_data.is_identified(): logger.info(f"[on_track_subscribed] Participant {participant.name} is not yet identified.") return # Retrieve user details from the database user_id = db.get_user_by_email(participant.identity) if user_id: user_data.user_id = user_id logger.info(f"[on_track_subscribed] User found: ID={user_id}") transcript = db.get_transcription(user_id) user_data.last_conversation_for_reference = transcript else: logger.warning(f"[on_track_subscribed] No user found for email: {participant.identity}") return # Build context instructions instructions = ( f"You are assisting {user_data.user_name}, " f"a {user_data.user_age}-year-old {user_data.user_gender}. " f"users email is {user_data.user_email}. Use this mail only as attendees mail while scheduling meetings. " ) if user_data.last_conversation_for_reference: instructions += ( "Here is the last conversation for context:\n" "Pick only the key terms from this text and use them as memory " "while talking with the user:\n" f"{user_data.last_conversation_for_reference}\n" ) # Append contextual instructions asynchronously asyncio.create_task( appointment_scheduling_assistant.append_instructions(instructions) ) logger.info(f"[on_track_subscribed] Instructions appended for user {user_data.user_name}.") except Exception as e: logger.error(f"[on_track_subscribed] Error processing subscription: {str(e)}", exc_info=True) await session.start( agent=appointment_scheduling_assistant, room=ctx.room, room_input_options=RoomInputOptions(noise_cancellation=noise_cancellation.BVC(),), )
suggest the changes you mentioned in the code.
t
Thank you for sharing your code! To help you address the issue, here are some friendly suggestions you might find useful: 1. Ensure Proper Agent Session Initialization: It’s a good idea to initialize the agent session before handling any events. Here’s an example to guide you:
Copy code
await session.start(
    agent=appointment_scheduling_assistant,
    room=ctx.room,
    room_input_options=RoomInputOptions(noise_cancellation=noise_cancellation.BVC(),),
)

@ctx.room.on("track_subscribed")
def on_track_subscribed(
    track: rtc.Track,
    publication: rtc.RemoteTrackPublication,
    participant: rtc.RemoteParticipant,
):
    # Event handler logic here
1. Add Defensive Checks: Before accessing the agent session or participant metadata, it’s helpful to check if they’re properly initialized. For example:
Copy code
if not appointment_scheduling_assistant:
    logger.warning("[on_track_subscribed] Appointment scheduling assistant is not initialized.")
    return

if not participant.metadata:
    logger.debug("[on_track_subscribed] No metadata found for participant.")
    return
1. Introduce Retry Logic: Sometimes the agent session might not be ready right away, so adding a retry with a short delay can make your code more robust. Here’s how you might do it:
Copy code
async def handle_track_subscription(track, participant):
    for attempt in range(3):
        if appointment_scheduling_assistant:
            # Process the track
            break
        else:
            logger.warning("Agent session not ready, retrying...")
            await asyncio.sleep(1)
1. Monitor Agent Session State: Adding logging to observe the agent session state can be really helpful. This way, you’ll know exactly when it’s active and ready to process events:
Copy code
@appointment_scheduling_assistant.on("agent_state_changed")
def on_agent_state_changed(event):
    logger.info(f"Agent state changed: {event.old_state} -> {event.new_state}")
Implementing these changes should make your agent session more reliable and reduce the chance of errors when handling events. If you have any questions or need further assistance, I’m here to help!
m
async def handle_track_subscription(track, participant): for attempt in range(3): if appointment_scheduling_assistant: # Process the track break else: logger.warning("Agent session not ready, retrying...") await asyncio.sleep(1) .where this function should be call ,or willl it be called automatically
t
I wanted to share a quick tip about the
handle_track_subscription
function—it doesn’t get called automatically, so you’ll need to call it yourself inside the
on_track_subscribed
event handler whenever a track is subscribed. Here’s a simple way to set that up:
Copy code
@ctx.room.on("track_subscribed")
def on_track_subscribed(
    track: rtc.Track,
    publication: rtc.RemoteTrackPublication,
    participant: rtc.RemoteParticipant,
):
    # Call the handle_track_subscription function asynchronously
    asyncio.create_task(handle_track_subscription(track, participant))
By doing this, you’ll make sure the function runs every time a track is subscribed, and it will also manage retries if the agent session isn’t quite ready yet. I hope this helps clarify things!
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!