I have `AvatarSession` with Hedra. Can I stop the ...
# ask-ai
r
I have
AvatarSession
with Hedra. Can I stop the video and continue audio-only conversation with RPC call?
t
Thanks for reaching out, Ivan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
The Hedra
AvatarSession
doesn’t currently support an RPC call to stop video while keeping the audio going. Right now, the video and audio streams are generated and published together by the remote avatar server, so there isn’t a built-in way to pause the video on its own. If you want to have this feature, you’d need to extend the Hedra avatar server to accept an RPC command (like
pause_video
) and adjust its logic to stop sending video frames while still streaming audio. This would involve some custom development beyond what the current API offers. If you’d like, I’m here to help guide you through implementing a custom RPC method in a LiveKit agent to make this happen. Just let me know, and I can share an example to get you started! Sources: Text and transcriptions | LiveKit docs | avatars/hedra/education_avatar/agent.py | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | packages/livekit-rtc/src/proto/ffi_pb.ts | livekit-agents/livekit/agents/voice/agent_activity.py
r
can I transfer between agents on RPC call?
t
Agent transfers in LiveKit are definitely supported, though they aren’t done directly through general-purpose RPC calls like
PerformRpc
. Instead, transfers happen through
@function_tool
-decorated methods within the agent framework. These special methods take care of the handoff process, keeping the conversation context intact and making sure the transition between agents feels smooth and natural. If you want to transfer a session to another agent, you’d set up a
@function_tool
method for the transfer path, and the framework will manage the routing and context preservation for you. Would you like me to walk you through a detailed example of how to build a multi-agent handoff system using this approach? I’m here to help! Sources: Remote method calls | LiveKit docs | livekit/livekit_room.twirp.go | Company directory phone assistant | LiveKit Docs | Tool definition and use | LiveKit docs | Realtime data | LiveKit Docs
r
can I close the session on rpc call?
t
Yes, you absolutely can close a session using an RPC call in LiveKit! The
WHIPParticipant.DeleteSession
RPC method is just the right tool for this—it lets you remove a participant from a room by providing the room name, participant identity, and participant ID. If you're working with the Agent SDK, you also have the option to close a session programmatically using the
session.aclose()
method. This will gracefully close the session and emit a
CloseEvent
once it's done. If you'd like, I’d be happy to walk you through some examples or provide more details on how to set this up. Just let me know! Sources: pkg/service/roommanager_service.go | Events and error handling | LiveKit docs | Job lifecycle | LiveKit Docs | rpc/whip_signal.psrpc.go
r
can I maybe restart the agent session on RPC call?
t
An agent can be restarted using the
RestartAgent
RPC call, which gently restarts the agent's worker pool at the infrastructure level. It’s great to know that this process doesn’t interrupt any active sessions—they’ll keep running smoothly during the restart. If you’re looking to restart a specific agent session, that’s something you’d handle within your agent’s application logic. For instance, you can programmatically close and restart a session using methods like
aclose()
and
start()
on the
AgentSession
object. I’m here to help—would you like some guidance on how to implement session-level restarts within your agent logic? Just let me know! Sources: Agent deployment CLI reference | LiveKit Docs | agent/main.py | livekit/livekit_cloud_agent.pb.go
r
I used Hedra agent from the example, but it does not stop the stream if I perform
_await_ session.aclose()
t
The
session.aclose()
method is here to help you gently stop all ongoing operations in the session, including pausing audio and video streams. It works by gracefully finishing up current tasks, freeing resources, and detaching input/output streams. If you’re finding that the stream isn’t stopping as expected in your Hedra agent example, don’t worry—we can figure this out together. Could you please let me know if there are any custom changes you’ve made to the example or share more details about what you’re seeing? That way, I can better understand the situation and help you get to the bottom of it. Sources: How to capture real-time agent transcriptions during conversations | Agent Session Management & Turn Detection | livekit/livekit_composite | Dee... | examples/voice_agents/session_close_callback.py | Events and error handling | LiveKit docs | examples/video-stream/audio_wave.py
r
I follow the Hedra avatar example
Copy code
async def entrypoint(ctx: agents.JobContext):
   session = AgentSession(
      # ... stt, llm, tts, etc.
   )

   avatar = hedra.AvatarSession(
      avatar_id="...",  # ID of the Hedra avatar to use. See "Avatar setup" for details.
   )

   # Start the avatar and wait for it to join
   await avatar.start(session, room=ctx.room)

   # Start your agent session with the user
   await session.start(
      # ... room, agent, room_input_options, etc....
   )
can I terminate
hedra.AvatarSession
instance?
t
To gently end a
hedra.AvatarSession
instance, you can simply remove the avatar participant from the room by using the
api.room.remove_participant
method. This will gracefully stop both audio and video streaming from the avatar. Here’s a little example to guide you:
Copy code
await ctx.api.room.remove_participant(
    api.RoomParticipantIdentity(
        room=ctx.room.name,
        identity="hedra-avatar-agent"  # Just swap this with your avatar's identity
    )
)
Once you remove the participant, the session wraps up nicely and all resources are tidied away. If you’d like, I’m here to help with more details or examples—just let me know! Sources: avatars/hedra/dynamically_created_avatar/agent.py | livekit-plugins/livekit-plugins-tavus/livekit/plugins/tavus/avatar.py | pkg/service/roommanager_service.go
r
I want to remove "hedra-avatar-agent" but keep my agent (the one that has STT, LLM and TTS)
t
To gently remove the "hedra-avatar-agent" while keeping your main agent up and running, you can use the
api.room.remove_participant
method to specifically target and remove the avatar participant from the room. This way, the avatar's audio and video streams will stop, but your main agent will continue working smoothly. Here’s a little example to guide you:
Copy code
await ctx.api.room.remove_participant(
    api.RoomParticipantIdentity(
        room=ctx.room.name,
        identity="hedra-avatar-agent"  # Replace with the avatar's identity
    )
)
This method makes sure only the avatar participant is removed, while your main agent—with STT, LLM, and TTS—stays active in the session. If you have any questions or need help putting this into action, just let me know—I’m here to help!
r
the agent is connected but it is not responding to my messages
t
If your agent is connected but isn’t responding to messages, don’t worry—we can work through this together. Here are some friendly steps to help troubleshoot and get things back on track: 1. Monitor Agent State: Take a moment to see if the agent has moved into an active state like
listening
,
thinking
, or
speaking
. If it’s still stuck in
connecting
or
initializing
, it might not be quite ready to process input yet. 2. Set a Timeout: It’s a good idea to set a timeout (say, 10–20 seconds) to check if the agent stays unresponsive after connecting. If that happens, you can gently notify the user and, if needed, disconnect. 3. Use Built-in Wait Methods: If you’re working with React, the
useAgent()
hook has a handy
waitUntilAvailable()
method that ensures the agent is fully ready before you start interacting. 4. Verify Agent Dispatch: Double-check that your agent server is up and running, reachable, and has enough workers to handle requests. Also, make sure your token generation includes the right dispatch parameters. 5. Debugging: Turning on debug logging in the client SDK and keeping an eye on server-side logs can really help spot any errors during agent initialization. If you’re still facing issues after trying these, just let me know—I’m here to help with more specific debugging tips or configuration checks! Sources: Troubleshooting Guide | livekit/livekit_composite | DeepWiki | Sources/LiveKit/Agent/Session.swift | packages/react/src/hooks/useAgent.ts | hooks/useConnectionTimout.tsx | complex-agents/drive-thru/frontend/components/session-view.tsx
r
Documentation says
The virtual avatar plugins work with the
AgentSession
class automatically. The plugin adds a separate participant, the avatar worker, to the room. The agent session sends its audio output to the avatar worker instead of to the room, which the avatar worker uses to publish synchronized audio + video tracks to the room and the end user.
Can I enable and disable avatar worker with a RPC call?
t
There isn’t any direct evidence that the avatar worker in LiveKit can be turned on or off using an RPC call. The avatar worker acts as a participant in the room, receiving audio output from the agent session to create synchronized audio and video tracks. However, the documentation doesn’t mention a specific RPC method for toggling the avatar worker. If you’re looking to control the avatar worker, a good approach might be to programmatically start or stop the
AvatarSession
instance or remove the avatar participant from the room using the
api.room.remove_participant
method. Please feel free to reach out if you'd like me to walk you through how to implement this—I’m here to help! Sources: examples/avatar_agents/bey/README.md | Virtual avatar plugins | LiveKit Docs | avatars/hedra/education_avatar/agent.py
r
yes, let's modify the Hedra template example to add and remove the Hedra worker participant from a room
t
To help you modify the Hedra template example to add and remove the Hedra worker participant from a room, here’s a friendly step-by-step guide you can follow: 1. Adding the Hedra Worker: You can use the
hedra.AvatarSession
class to start the avatar worker and add it to the room. Here’s a simple example:
Copy code
async def add_avatar_worker(ctx, session):
    avatar = hedra.AvatarSession(
        avatar_id="your-avatar-id",  # Replace with your avatar ID
    )
    await avatar.start(session, room=ctx.room)
    return avatar
2. Removing the Hedra Worker: When you want to remove the avatar worker from the room, the
api.room.remove_participant
method is your friend. Check out this snippet:
Copy code
async def remove_avatar_worker(ctx):
    await ctx.api.room.remove_participant(
        api.RoomParticipantIdentity(
            room=ctx.room.name,
            identity="hedra-avatar-agent"  # Replace with the avatar's identity
        )
    )
3. Integrating into the Template: To bring it all together, you can modify the
entrypoint
function to include calls to both
add_avatar_worker
and
remove_avatar_worker
whenever you need. For example:
Copy code
async def entrypoint(ctx: agents.JobContext):
    session = AgentSession(
        # ... stt, llm, tts, etc.
    )

    # Add the avatar worker
    avatar = await add_avatar_worker(ctx, session)

    # Start your agent session with the user
    await session.start(
        # ... room, agent, room_input_options, etc.
    )

    # Example: Remove the avatar worker after some condition
    await remove_avatar_worker(ctx)
This way, you can easily manage adding and removing the Hedra worker participant dynamically in your room. If you have any questions or want me to walk you through any part of this, just let me know—I’m here to help!
r
will this stop Hedra video generation on the backend? The last thing I need here is to leave Hedra working somewhere in the background and charge me credits 🙂
Copy code
await ctx.api.room.remove_participant(
                api.RoomParticipantIdentity(
                    room=ctx.room.name,
                    identity=avatar_identity,
                )
            )
t
Yes, removing the Hedra avatar participant from the room using ctx.api.room.remove_participant will kindly stop the video generation on the backend. When you remove the participant, LiveKit gracefully ends the associated agent job, which includes stopping the video generation process. This way, you can be confident that no unnecessary resources are being used, and you won’t be charged for services you’re not using. If you have any questions or need a hand with this, please don’t hesitate to reach out—I’m here to help! Sources: Hedra Realtime Avatar integration guide | LiveKit Docs | avatars/hedra/README.md | pkg/rtc/room.go
r
what if I want to switch between audio and text-only chats using RPC calls?
t
You can easily switch between audio and text-only chats using RPC calls in LiveKit. Let me walk you through it: 1. Control Audio Input: You can use the
toggle_input
RPC method to turn audio input on or off:
Copy code
await localParticipant.performRpc({
  method: 'toggle_input',
  payload: 'audio_off',  // Use 'audio_on' to enable
  destinationIdentity: 'agent-bot'
});
2. Control Audio Output: Similarly, the
toggle_output
RPC method lets you manage audio output or transcription:
Copy code
await localParticipant.performRpc({
  method: 'toggle_output',
  payload: 'transcription_on',  // Use 'audio_on' or 'audio_off' for audio
  destinationIdentity: 'agent-bot'
});
3. Receive Text Responses: When audio output is off, the agent sends responses through the
lk.transcription
text stream topic. Just make sure your client listens to this topic so you can see the text responses:
Copy code
room.on('data', (data, participant) => {
  if (data.topic === 'lk.transcription') {
    console.log('Agent says:', data.payload);
  }
});
This way, you can smoothly switch between audio and text-only modes whenever you need. If you have any questions or want more examples, feel free to ask—I’m here to help! Sources: Text and transcriptions | LiveKit docs | README.md | How to Set Up Speech-to-Text Input with Text-Only Output in LiveKit Agents | README.md
r
how to implement hard limit on session duration? can I close session from the agent side after 5 minutes of conversation?
t
To help you set a hard limit on session duration and close the session from the agent side after 5 minutes, here’s a friendly approach you can try: 1. Schedule Session Closure: You can use an asynchronous task to close the session after 5 minutes like this:
Copy code
async def on_enter(self):
    # Schedule session closure after 5 minutes
    asyncio.create_task(self._close_after_duration(300))

async def _close_after_duration(self, delay: float):
    await asyncio.sleep(delay)
    await self.session.generate_reply(instructions="Time's up. Closing the session now.")
    await self.session.aclose()
2. Use Built-in Timeout (if available): If your realtime model supports a
max_session_duration
parameter, you can easily set it like this:
Copy code
realtime_model = openai.RealtimeModel(
    max_session_duration=300.0  # 5 minutes in seconds
)
3. Notify Users: It’s always a great idea to notify users before closing the session to make their experience smoother. 4. Room-Level Management: If you want to end the session for all participants, simply delete the room with:
Copy code
await room_service.delete_room(room_name)
Please feel free to reach out if you’d like me to walk you through a more detailed example or if you have any other questions—I’m here to help! Sources: livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | base-frontend-template/components/session-view.tsx | Job lifecycle | LiveKit Docs
r
await
_self_.session.aclose()
in my agent class does not close the session, it simply restarts the agent
t
The
session.aclose()
method is meant to gently close the session, shutting down the agent and freeing up all resources. It doesn’t actually restart the agent on its own. That said, sometimes a new session might be created right after closing the old one, which can look like a restart. If you’re noticing unexpected restarts, it could be because: • You’re explicitly calling
session.start()
again after
aclose()
. • There might be configuration changes or callbacks in your code that trigger a new session. I’m here to help! If you’d like, we can go over your agent logic together to pinpoint what’s causing this. Just let me know! Sources: Events and error handling | LiveKit docs | agent/main.py | examples/voice_agents/session_close_callback.py
r
maybe I can configure shutdown on RoomInputOptions?
t
Yes,
RoomInputOptions
can definitely be configured to help you control session shutdown behavior. Let me walk you through the key options: 1. Automatic Session Closure: You can use the
close_on_disconnect
option to have the session automatically close whenever a participant disconnects. This is set to
True
by default, which makes things pretty seamless.
Copy code
await session.start(
    agent=MyAgent(),
    room=ctx.room,
    room_input_options=RoomInputOptions(
        close_on_disconnect=True
    ),
)
2. Room Deletion on Close: If you'd like the room to be deleted automatically when the session ends, the
delete_room_on_close
option is perfect.
Copy code
await session.start(
    agent=MyAgent(),
    room=ctx.room,
    room_input_options=RoomInputOptions(
        delete_room_on_close=True
    ),
)
3. Manual Shutdown: For more hands-on control, you can always call
session.shutdown()
or
session.aclose()
directly within your agent’s logic. These options give you great flexibility to manage your session and room lifecycle smoothly. If you have any questions or want help with the implementation, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | Knowledge Base Collection & Management | livekit/livekit_composite | DeepWi... | Job lifecycle | LiveKit Docs | agents/src/voice/room_io/room_io.ts
r
or in
Copy code
agents.WorkerOptions
?