I provided a function tool to my agent that allows...
# ask-ai
b
I provided a function tool to my agent that allows to end the call:
Copy code
class Assistant(Agent):
    def __init__(self, instructions: str) -> None:
        super().__init__(instructions=instructions)
        self._closing_task: asyncio.Task[None] | None = None

    async def hang_up(self):
        await self.session.drain()
        await self.session.aclose()
        get_job_context().delete_room()

    @function_tool
    async def end_interview(self, context: RunContext) -> None:
        """
        Once all the questions have been asked and the user has answered them, call this function to end the call.
        """
        speech_handle = self.session.generate_reply(instructions="Thanks for joining our interview.")
        await speech_handle
        self._closing_task = asyncio.create_task(self.hang_up())
        return None
In the frontend (JS client), how can I capture this event to trigger a redirect?
t
Thanks for reaching out, Stefanos. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring how to capture the event triggered by your function tool and redirect the user in the frontend (JavaScript client). A great way to achieve this is by using Remote Procedure Calls (RPC). Let me walk you through how you can implement it: 1. Define a Function Tool in the Agent: You can use the
perform_rpc
method to send a structured payload, like a URL, to the frontend. Here's an example to guide you:
Copy code
@function_tool
async def send_url_to_frontend(self, context: RunContext, url: str):
    payload = {"url": url}
    room = context.room
    remote_participants = list(room.remote_participants.values())
    if remote_participants:
        client_participant = remote_participants[0]
        await room.local_participant.perform_rpc(
            destination_identity=client_participant.identity,
            method="client.navigate",
            payload=json.dumps(payload)
        )
    return "URL sent to frontend"
1. Handle the RPC in the Frontend: On the frontend side, you can register an RPC handler with the LiveKit JavaScript SDK to listen for this event and redirect the user. Here's how you might do it:
Copy code
room.localParticipant.registerRpcHandler("client.navigate", async (info) => {
  const { payload } = info;
  const data = JSON.parse(payload);
  if (data.url) {
    window.location.href = data.url; // Redirect the browser
  }
  return JSON.stringify({ success: true });
});
This approach helps ensure that when your agent sends the RPC, the frontend picks up the URL and smoothly redirects the user. If you have any questions or need more help along the way, please don’t hesitate to reach out—I’m here to support you! Sources: complex-agents/drive-thru/frontend/app/components/page.tsx | Tool definition and use | LiveKit Docs | Events and error handling | LiveKit Docs
b
How about a hook to capture a RoomEvent on the frontend?
t
To capture a
RoomEvent
on the frontend, you can use the LiveKit client SDK to listen for specific events via the
.on()
method. Here’s a simple example to help you get started with setting up an event listener:
Copy code
room.on(RoomEvent.ParticipantConnected, (participant) => {
  console.log("Participant connected:", participant.identity);
});
When it comes to transcription events, you can try this approach:
Copy code
room.on(RoomEvent.TranscriptionReceived, (segments, participant, publication) => {
  segments.forEach((segment) => {
    console.log("Transcription segment:", segment.text);
  });
});
Also, it’s a good idea to clean up the listeners using
.off()
in your component’s cleanup function to avoid any memory leaks. If you’d like, I’m here to help with more details or examples for any specific event types you’re working with! Sources: hooks/use-transcriber.ts | hooks/use-transcriber.ts | complex-agents/role-playing/role_playing_frontend/components/app.tsx | src/room/events.ts | Transcriptions | LiveKit Docs
b
What RoomEvent instances are emitted when these lines are executed in the voice agent:
Copy code
await self.session.drain()
        await self.session.aclose()
        get_job_context().delete_room()
t
When the following lines are executed in the voice agent:
Copy code
await self.session.drain()
await self.session.aclose()
get_job_context().delete_room()
the following
RoomEvent
instances are emitted: •
session.drain()
: This makes sure all ongoing audio and speech tasks are wrapped up smoothly, but it doesn’t emit any
RoomEvent
. •
session.aclose()
: This emits a
CloseEvent
, letting you know the agent session has closed. It also shares details like why the session was closed. •
delete_room()
: This triggers a
Disconnected
event for everyone in the room, with the reason
ROOM_DELETED
, meaning the room has been ended. If you have any questions or need me to walk you through this further, just let me know—I’m here to help! Sources: tests/test_agent_session.py | Docs::Agents | Inside a session | LiveKit Docs | Job lifecycle | LiveKit Docs | Events and error handling | LiveKit Docs
b
Provide the definition for the handleRoomDisconnected function that ideally will control logic based on the reason (if ROOM_DELETED redirect to /)
room.on(RoomEvent.Disconnected, handleRoomDisconnected);
t
Here's a helpful definition for the
handleRoomDisconnected
function that listens for the
RoomEvent.Disconnected
event and gently guides the user to the right place based on the reason:
Copy code
room.on(RoomEvent.Disconnected, (reason) => {
  console.log('Disconnected from room', reason);

  // Let's redirect or clean up depending on why the disconnection happened
  switch (reason) {
    case 'ROOM_DELETED':
      // The host deleted the room
      window.location.href = '/';
      break;
    case 'CLIENT_INITIATED':
      // The user chose to disconnect
      window.location.href = '/home';
      break;
    case 'DUPLICATE_IDENTITY':
      // Another device joined with the same identity
      alert('Another device has joined with the same identity.');
      window.location.href = '/login';
      break;
    case 'PARTICIPANT_REMOVED':
      // The host removed this participant
      window.location.href = '/removed';
      break;
    case 'ROOM_CLOSED':
      // The room was closed automatically
      window.location.href = '/room-ended';
      break;
    default:
      // Something unexpected happened, maybe network issues
      window.location.href = '/error';
  }
});
This function carefully listens for the
Disconnected
event, checks the reason behind it, and then redirects the user in a way that makes sense. If you have any questions or need a hand with anything else, please don’t hesitate to ask—I’m here to help! Sources: src/room/events.ts | packages/react/src/hooks/useLiveKitRoom.ts | Runtime/Scripts/Room/Room.cs | agent-console/lib/event-definitions.tsx | callback.go