how to do that Make sure your agent subscribes to ...
# ask-ai
w
how to do that Make sure your agent subscribes to video tracks through
RoomIO
t
Thanks for reaching out, Atharva. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! To make sure your agent subscribes to video tracks through
RoomIO
, you’ll want to set up the
RoomInputOptions
when you initialize the
RoomIO
class by turning on
video_enabled: True
. By default, video input is off, so flipping this switch makes sure your agent gets those video tracks from participants. Here’s a quick example to help you out:
Copy code
from livekit.agents.voice.room_io import RoomIO, RoomInputOptions

# Turn on video input in RoomInputOptions
input_options = RoomInputOptions(
    video_enabled=True,
    # You can also configure audio and text here if you want
    audio_enabled=True,
    text_enabled=True,
)

# Initialize RoomIO with your options
room_io = RoomIO(
    agent_session=agent_session,
    room=room,
    input_options=input_options,
)
Also, just a few things to keep in mind: • The participant whose video you want to see needs to have published a video track. • Your agent should be connected to the room before you expect any video frames. • If you’re using automatic participant linking, make sure the right participant is identified using
participant_identity
in
RoomInputOptions
or by calling
set_participant()
. Once you’ve got video subscription enabled, you can listen for incoming video frames like this:
Copy code
async for frame in room_io.video_input:
    # Here’s where you can work with the video frame
    print(f"Received video frame: {frame.width}x{frame.height}")
Sources: livekit-agents/livekit/agents/voice/room_io/_input.py
w
is await session.start( room=ctx.room, agent=Assistant(), room_input_options=RoomInputOptions( # enable background voice & noise cancellation, powered by Krisp # included at no additional cost with LiveKit Cloud video_enabled=True, noise_cancellation=noise_cancellation.BVC(), ), ) and # Initialize RoomIO with your options room_io = RoomIO( agent_session=agent_session, room=room, input_options=input_options, ) same ?
t
Hey there! Just to clarify, using
session.start
with
RoomInputOptions
and explicitly initializing
RoomIO
with
input_options
are related but not exactly the same in LiveKit. Both help set up how input works, but they offer different levels of control and initialization: •
session.start(..., room_input_options=...)
is a bit more hands-off—it automatically creates a default
RoomIO
instance behind the scenes, using your
RoomInputOptions
to handle audio, video, and text inputs for the session. • On the other hand, explicitly initializing
RoomIO(..., input_options=...)
gives you more control. This is great if you want to manage multiple participants individually or tweak input settings more precisely. Here, you’ll call
await room_io.start()
yourself before kicking off the session. So, while both use
RoomInputOptions
, the first approach is managed automatically by
AgentSession
, and the second one is more hands-on, perfect for advanced setups or when you want to customize things per participant. Sources: Building voice agents | LiveKit Docs | examples/voice_agents/langgraph_agent.py
w
if intially i was in normal audio assistant where i had enabled video as true and when i switch to actual visionassistant i wanted this video to be true there also or rahter visionassistant to be subscribed to video track also ... for that what should await session.start( room=ctx.room, agent=Assistant(), room_input_options=RoomInputOptions( # enable background voice & noise cancellation, powered by Krisp # included at no additional cost with LiveKit Cloud video_enabled=True, noise_cancellation=noise_cancellation.BVC(), ), ) be should it be session.start of roomio. and how to update this code for the purpose of subcripng or letting the videoassistant also have access to video class VisionAssistant(Agent): def __init__(self) -> None: super().__init__( instructions=""" You are a helpful voice and video assistant. Your user is interacting with you via a smartphone app and may speak by using their microphone. """, llm=google.beta.realtime.RealtimeModel( voice="Puck", temperature=0.8 ), ) async def on_enter(self): global visionAsynsTask_varRef global curr_conversation_context print("WE ARE HERE") visionAsynsTask_varRef=asyncio.create_task(self.watch_activitytrack()) await self._activity.update_chat_ctx(curr_conversation_context)
t
Hey there! To make sure your video subscription works smoothly when switching from an audio assistant to a VisionAssistant, you just need to tweak the
auto_subscribe
parameter in the
ctx.connect()
method. By default, audio assistants use
AutoSubscribe.AUDIO_ONLY
, which means they only subscribe to audio tracks. To get video as well, simply update your code like this:
Copy code
await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL)
This way, your VisionAssistant will subscribe to both audio and video tracks from everyone in the room. And if you want video without audio, no worries—you can use
AutoSubscribe.VIDEO_ONLY
instead. Once you've got video subscription set up, you can start handling incoming video frames with
rtc.VideoStream
and weave them right into your vision-based workflows. Pretty neat, right? Sources: AutoSubscribe | LiveKit Agents | Vision Agent Quickstart | LiveKit Docs | Vision Agent Quickstart | LiveKit Docs | Audio and video | LiveKit Docs
w
await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL) where to add this code
t
Hey! You’ll want to add
await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL)
inside your
entrypoint
function in the LiveKit agent code. Just pop it in after you’ve set up any event listeners or participant entrypoints, but before you do anything that needs the agent to be connected to the room. Here’s a quick example to make it clearer:
Copy code
async def entrypoint(ctx: JobContext):
    logger.info("starting entrypoint")

    # You can set up event listeners or participant entrypoints here before connecting
    @ctx.room.on("track_subscribed")
    def on_track_subscribed(track: rtc.Track, publication: rtc.TrackPublication, participant: rtc.RemoteParticipant):
        # Handle subscribed tracks
        pass

    # Now, connect to the room with the subscription settings you want
    await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL)
    logger.info("connected to the room")

    # Then you can continue with the rest of your logic after connecting
This way, your agent will be properly connected to the room and ready to start receiving media tracks according to the subscription settings you chose. If you have any questions or want to chat more about it, just let me know! Sources: livekit-agents/livekit/agents/job.py | python-agent-example-app/main.py | Vision Agent Quickstart | LiveKit Docs | Receiving and publishing tracks | LiveKit Docs
w
will adding await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL) in the entrypoint of assistant give the video access to visionassistant also when i switch my agent to it ?
t
Hey there! Just so you know, adding
await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL)
right at the start of your assistant will let the VisionAssistant access video when you switch agents—provided that participants in the room are sharing their video tracks. This setup makes sure your agent automatically subscribes to all the audio and video tracks as soon as it joins the room. Using
AutoSubscribe.SUBSCRIBE_ALL
is key because it enables the video features the VisionAssistant needs to process video frames and handle visual tasks smoothly. Sources: Vision Agent Quickstart | LiveKit Docs | Vision Agent Quickstart | LiveKit Docs | Vision Agent Quickstart | LiveKit Docs | Audio and video | LiveKit Docs | Receiving and publishing tracks | LiveKit Docs
w
<livekit.agents.llm.chat_context.ChatContext object at 0x1278dc750> how to print his
t
If you want to print out what's inside a
ChatContext
object in LiveKit, you’ve got a couple of easy options! You can either use the
to_dict()
method or just peek at its
items
property. Here’s how you can do it:
Copy code
# Convert the chat context to a dictionary and print it
print(chat_ctx.to_dict())

# Access and print the list of chat items directly
print(chat_ctx.items)
Here’s a quick example to show you what I mean:
Copy code
chat_ctx = ChatContext()
chat_ctx.add_message(role="user", content="Hello, world!")
chat_ctx.add_message(role="assistant", content="Hello, world!")

print(chat_ctx.to_dict())  # Prints the chat context as a dictionary
print(chat_ctx.items)      # Prints the list of chat items directly
Using these methods is a great way to peek inside and debug your
ChatContext
object while your program is running. Hope this helps! Sources: examples/voice_agents/realtime_joke_teller.py
w
when i went from normal assistant to visionassistant. i was able to go but unable to switch back from visionassistant to normal assisntant now using this self.session.update_agent(Assistant()). date_agent(VisionAssistant()) async def on_enter(self): global visionAsynsTask_varRef global curr_conversation_context print("WE ARE HERE") # await ctx.connect(auto_subscribe=AutoSubscribe.SUBSCRIBE_ALL) visionAsynsTask_varRef=asyncio.create_task(self.watch_activitytrack()) #TODO: # self._chat_ctx = # asyncio.create_task(self._delayed_agent_update()) # self.chat_ctx = curr_conversation_context await self._activity.update_chat_ctx(curr_conversation_context) print("_______ENTERING VISION MODE passing the CONTEXT____________") # print(curr_conversation_context.to_dict()) # self.session.generate_reply( # instructions="Based on the screen just j." # ) # print("Currently in VOICE NOW SWITCING TO INTERVIEW AGENT") # self.session.update_agent(Assistant()) async def watch_activitytrack(self): global visionAsynsTask_varRef global ref_switchingOutFromVision while True: value = ref_switchingOutFromVision.get() print("WATCHING ACTIVITY TRACK",value) if value: print("Switching out from vision mode, stopping watch_activitytrack") ref_switchingOutFromVision.set(0) self.session.update_agent(Assistant()) break else: await asyncio.sleep(1)
t
Hey there! Switching back from
VisionAssistant
to
Assistant
using
session.update_agent
should generally work, but if it’s giving you trouble, here are some common reasons and a few tips to help you troubleshoot: • Agent State or Initialization Issues: Make sure your session is fully started and running before you call
update_agent
. If the session is stuck in an error state, the switch might not go through. • Resource Conflicts with Video Handling: Double-check that any video resources (like
input.video
) from
VisionAssistant
are properly released or reset before you switch back. • LLM or Model Configuration Conflicts: If your agents use different LLM setups (like multimodal vs. text-only), confirm that the new agent’s model is initialized correctly. • Event Handler Overlaps: Sometimes event handlers (for example, those managing video streams) left over from
VisionAssistant
can interfere with the new agent — it’s worth checking on those. Here’s a quick checklist to help you troubleshoot: 1. Make sure your session is active and running before calling
update_agent
. 2. Release or unregister any video or byte stream handlers from
VisionAssistant
before you switch. 3. Double-check that both agents are properly defined and their configurations play nicely together. 4. Add some error handling around
update_agent
and keep an eye on the logs for any exceptions. If you’re still stuck, you might want to try using a single, unified agent class that can handle both vision and non-vision modes conditionally. This way, you can avoid those tricky state and resource conflicts that sometimes pop up when switching agent types. Sources: examples/voice_agents/error_callback.py | agent/main.py
w
can you do this Add some error handling around
update_agent
and keep an eye on the logs for any exceptions.
t
If you want to add some error handling around
update_agent
, a
try
-
except
block is a great way to catch and log any hiccups that might pop up during the agent update. Here’s a little example for you:
Copy code
try:
    self.session.update_agent(Assistant())
    print("Successfully switched to Assistant")
except Exception as e:
    print(f"Error while switching to Assistant: {e}")
This approach will make it easier to spot any issues or exceptions that could be getting in the way of switching agents. Just keep an eye on your logs for any error messages or stack traces—they’ll give you more clues about what’s going on.
w
i am not just sure if self is pointint to correct things how to see
t
If you want to check whether
self
is pointing to the right object while your code is running, here are some friendly tips to help you out: 1. Print the object: Try using
print(self)
to see what object
self
is referring to. This will show you the memory address and the class name, giving you a quick peek. 2. Check the type: You can also do
print(type(self))
to double-check the class of the object
self
is linked to. 3. Inspect attributes: Give
print(dir(self))
a shot to list out all the attributes and methods the object has. This helps you see if it has what you expect. 4. Debugging: If you want to dig deeper, use a debugger like
pdb
in Python. Just pop in
import pdb; pdb.set_trace()
where you want to pause, and you can interactively inspect
self
at runtime. Following these steps should make it easier to confirm that
self
is pointing to the right object and help you spot any issues with the object context. Hope this helps!
w
when i went from normal assistant to visionassistant. i was able to go but unable to switch back from visionassistant to normal assisntant now using........but it actually switches to Assistant. but then switches back to VisionAssistant .
t
It looks like the issue might be coming from the logic in the lifecycle methods (
on_enter
,
on_exit
) of one of the agents, which could be calling
update_agent
again. Are you using any custom logic in these methods that might be making the VisionAssistant take back control after switching to Assistant? Just want to make sure we're on the same page! Sources: tests/test_agent_session.py | agent/main.py
w
so when i switch back from here this is in llm_node. if((curr_question_api_response.get("question_type")=="Frontend_QA")): # content_based_on_code= if(ref_frontendDesignCompare): print("FRONTEND PERVIEW") chat_ctx.add_message( role="system", content=( "You are a software interviewer. Your role is to quietly verify frontend code. " f"The complete code to review is:\n{full_code}\n\n" "See the design and compare with what was asked in question \n{current_question} " ) ) curr_conversation_context= chat_ctx.copy() ref_frontendDesignCompare.set(0) # Reset the flag after processing self.session.update_agent(VisionAssistant()) when from visionassistant i came back i again enter
t
Hey there! From what you’ve described, it looks like your code is explicitly calling
self.session.update_agent(VisionAssistant())
when certain conditions are met, like when
curr_question_api_response.get("question_type") == "Frontend_QA"
. This might be why the agent switches back to
VisionAssistant
even after you’ve already changed it to
Assistant
. To avoid this hiccup, you could add a simple state check or a flag to make sure
update_agent
only runs when it really needs to. Here’s a quick example:
Copy code
# Add a flag to track the current agent
if not isinstance(self.session.current_agent, VisionAssistant):
    self.session.update_agent(VisionAssistant())
This way,
update_agent
only triggers if the current agent isn’t already
VisionAssistant
. You can do something similar when switching back to
Assistant
. If you want, I’m here to help you set this up or dig into any other issues you might be facing!
w
but i the code did switch back to Assistant after visionassistant. but again entered visionassistant back
t
Hey there! If you notice the code switches back to
Assistant
but then jumps right back into
VisionAssistant
, it usually means the condition that triggers
self.session.update_agent(VisionAssistant())
is still being met after the switch. This can happen if the logic for switching to
VisionAssistant
isn’t properly controlled or reset. To fix this, try making sure the condition for switching to
VisionAssistant
only runs when it really needs to. One way is to use a flag to keep track of the current agent and avoid switching unnecessarily:
Copy code
# Example: Prevent redundant switches to VisionAssistant
if not isinstance(self.session.current_agent, VisionAssistant):
    self.session.update_agent(VisionAssistant())
Also, double-check that any flags or conditions (like
ref_frontendDesignCompare
) get reset properly after the switch, so they don’t keep triggering the same logic over and over. If you want, I’m here to help you dig into this further—just let me know!