Hi, how do I redispatch the agent when the user re...
# ask-ai
a
Hi, how do I redispatch the agent when the user reconnects?? This is my python entrypoint async def entrypoint(_ctx_: JobContext): # Setup Observability setup_langfuse() await ctx.connect() participant = await ctx.wait_for_participant() user_token = participant.attributes.get("userId") user_name = participant.name # Initialize user data with context userdata = UserData(_user_token_=user_token, _user_name_=user_name, ctx=ctx) # vad=ctx.proc.userdata["vad"] # Create agent instances master_agent = MasterAgent() product_discovery_agent = ProductDiscoveryAgent() faq_agent = FAQAgent() orders_agent = OrdersAgent() # Register all agents in the userdata userdata.personas.update( { "master": master_agent, "product_discovery": product_discovery_agent, "faq": faq_agent, "orders": orders_agent, } ) # Create session with userdata session = AgentSession[UserData](userdata=userdata) @session.on("metrics_collected") def _on_metrics_collected(_ev_: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) # RoomIO room_io = RoomIO(session, room=ctx.room) await room_io.start() # Start with the Master agent as the primary agent await session.start( agent=master_agent, # room=ctx.room, _room_input_options_=RoomInputOptions( _close_on_disconnect_=True, _text_enabled_=True, # audio_enabled=False, _noise_cancellation_=noise_cancellation.BVC(), # noise_cancellation=noise_cancellation.NC(), ), _room_output_options_=RoomOutputOptions( _transcription_enabled_=True, # audio_enabled=False ), ) # 👇 Default: text-only session.input.set_audio_enabled(False) session.output.set_audio_enabled(False) @_ctx_.room.local_participant.register_rpc_method("set_participant") async def on_set_participant(_data_: rtc.RpcInvocationData) -> None: target_identity = data.payload or data.caller_identity logger.info( "set participant called", extra={ "caller_identity": data.caller_identity, "payload": data.payload, "target_identity": target_identity, }, ) room_io.set_participant(target_identity) @_ctx_.room.local_participant.register_rpc_method("unset_participant") async def on_unset_participant(_data_: rtc.RpcInvocationData) -> None: logger.info( "unset participant called", extra={"caller_identity": data.caller_identity, "payload": data.payload}, ) room_io.unset_participant() @_ctx_.room.local_participant.register_rpc_method("toggle_input") async def on_toggle_input(_data_: rtc.RpcInvocationData) -> None: logger.info( "toggle input called", extra={"caller_identity": data.caller_identity, "payload": data.payload}, ) if data.payload == "audio_on": session.input.set_audio_enabled(True) elif data.payload == "audio_off": session.input.set_audio_enabled(False) @_ctx_.room.local_participant.register_rpc_method("toggle_output") async def on_toggle_output(_data_: rtc.RpcInvocationData) -> None: logger.info( "toggle output called", extra={"caller_identity": data.caller_identity, "payload": data.payload}, ) if data.payload == "audio_on": session.output.set_audio_enabled(True) elif data.payload == "audio_off": session.output.set_audio_enabled(False) elif data.payload == "transcription_on": session.output.set_transcription_enabled(True) elif data.payload == "transcription_off": session.output.set_transcription_enabled(False)
t
Thanks for reaching out, Satvik. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! When a user reconnects and you want to redispatch the agent, here are a few ways you can go about it: 1. Explicit Agent Dispatch: You can use the
AgentDispatchService
to explicitly redispatch an agent. Just make sure to set an
agent_name
in the
WorkerOptions
to turn off automatic dispatch. 2. Session Replacement Pattern: Another option is to replace the session during reconnections. This means ending the current session and starting a new one with the same agent and context. 3. Participant Connection Event Handling: Keep an eye on participant connection events and handle reconnections by reinitializing the agent or session when needed. 4. Token-Based Agent Dispatch: You can also set up agent dispatch when generating the token to make sure an agent is ready as soon as the user reconnects. Each method works best depending on things like whether you want to keep the conversation history, how fast the agent should be ready, and if you prefer automatic or explicit dispatch. Just let me know if you'd like me to walk you through the steps for any of these options—I’m here to help!
a
with explicit agent dispatch, how to accomodate this in the frontend (react). Reply with a code example.
t
Hey there! To help you set up explicit agent dispatch in your React frontend, here are a couple of friendly approaches you can try out: Approach 1: Dispatch via Token Generation This one lets you configure agent dispatch right when you generate the token. That way, the agent gets dispatched automatically as soon as a participant joins the room.
Copy code
// In your token generation endpoint or function
import { AccessToken, RoomConfiguration, RoomAgentDispatch } from 'livekit-server-sdk';

async function createTokenWithAgentDispatch(roomName, agentName, participantName) {
  const at = new AccessToken();
  at.identity = participantName;
  at.addGrant({ roomJoin: true, room: roomName });

  // Configure agent dispatch in the room configuration
  at.roomConfig = new RoomConfiguration({
    agents: [
      new RoomAgentDispatch({
        agentName: agentName,
        metadata: '{"mydata": "myvalue"}', // Optional metadata
      }),
    ],
  });

  return await at.toJwt();
}
Approach 2: Explicit API-Based Dispatch If you prefer, you can also create explicit dispatches using the
AgentDispatchClient
directly from your React app’s backend.
Copy code
import { AgentDispatchClient } from 'livekit-server-sdk';

async function createExplicitDispatch(roomName, agentName) {
  const agentDispatchClient = new AgentDispatchClient(process.env.LIVEKIT_URL);

  // Create a dispatch for the specific agent to join the room
  const dispatch = await agentDispatchClient.createDispatch(roomName, agentName, {
    metadata: '{"mydata": "myvalue"}',
  });

  console.log('created dispatch', dispatch);
  return dispatch;
}
If you want me to walk you through any part of this or if you have more questions, just give me a shout. I’m here to help!