I am having an issue where I get 2 agents in one r...
# ask-ai
d
I am having an issue where I get 2 agents in one room when I disconnect then reconnect:
Copy code
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  LiveKitRoom,
  RoomAudioRenderer,
  VideoConference,
} from '@livekit/components-react';
// LiveKit component styles are imported globally in main.tsx
import '@livekit/components-styles';

// Backend base URL provided at build time
const API_URL = (import.meta as any).env?.VITE_API_URL as string | undefined;
const TOKEN_ENDPOINT = API_URL ? `${API_URL}/getToken` : '/getToken';
const DISPATCH_ENDPOINT = API_URL ? `${API_URL}/dispatchAgent` : undefined;
const LIVEKIT_URL = import.meta.env.VITE_LIVEKIT_URL as string | undefined;

// Accept any metadata shape; it is forwarded to the backend as-is
type PatientMetadata = unknown;

type LivekitRoomProps = {
  onCallEnd?: () => void;
  patientMetadata?: PatientMetadata;
};

function uuid() {
  if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
  return Math.random().toString(36).slice(2);
}

export default function LivekitRoom({ onCallEnd, patientMetadata }: LivekitRoomProps) {
  const [token, setToken] = useState<string>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const isJoiningRef = useRef(false);
  const agentDispatchedRef = useRef(false);
  // Generate unique room and patient names for each component mount
  const [roomName] = useState(() => `room-${uuid()}`);
  const [patientName] = useState(() => `patient-${uuid().slice(0, 8)}`);

  const joinRoom = useCallback(async () => {
    if (isJoiningRef.current) return;
    isJoiningRef.current = true;
    setLoading(true);
    setError(null);

    try {
      // Request a token for our generated room + identity
      const params = new URLSearchParams({ room: roomName, identity: patientName, name: patientName });
      const res = await fetch(`${TOKEN_ENDPOINT}?${params.toString()}`);
      const { token } = await res.json();

      if (!token) throw new Error('No token received');

      // Optionally dispatch an agent (only once)
      if (DISPATCH_ENDPOINT && !agentDispatchedRef.current) {
        agentDispatchedRef.current = true;
        await fetch(DISPATCH_ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            agent_name:"patient",
            room: roomName,
            patient_name: patientName,
            metadata: patientMetadata ?? [],
          }),
        });
      }

      setToken(token);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to join room');
    } finally {
      setLoading(false);
      isJoiningRef.current = false;
    }
  }, [roomName, patientName, patientMetadata]);

  const leaveRoom = useCallback(() => {
    setToken(undefined);
    onCallEnd?.();
  }, [onCallEnd]);

  // Auto-join immediately when this screen mounts
  useEffect(() => { void joinRoom(); }, [joinRoom]);

  if (!token) {
    return (
      <div className="app-shell">
        <div className="card">
          <h1>{loading ? 'Connecting…' : 'Connection'}</h1>
          {loading ? (
            <p>Setting up your LiveKit session.</p>
          ) : error ? (
            <>
              <p className="error">{error}</p>
              <div className="form-actions">
                <button className="primary" onClick={joinRoom} disabled={loading}>
                  Retry
                </button>
              </div>
            </>
          ) : null}
        </div>
      </div>
    );
  }

  return (
    <LiveKitRoom
      token={token}
      serverUrl={LIVEKIT_URL}
      onDisconnected={leaveRoom}
      data-lk-theme="default"
    >
      <CallLayout />
    </LiveKitRoom>
  );
}

function CallLayout() {
  return (
    <div className="room-container">
      <RoomAudioRenderer />
      <div className="room-stage">
        <VideoConference />
      </div>
    </div>
  );
}
t
Thanks for reaching out, W. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you please help me understand a bit better? Are the duplicate agents showing up as separate participants in the room, or are they duplicate connections from the same participant? Also, I’d love to know if you’re using any particular logic to manage reconnections in your setup. Thanks so much for sharing these details!
d
Yes they appear as separate participants with different names ( uuid ). that is the dispatch agent code:
Copy code
@router.post("/dispatchAgent")
async def dispatch_agent(payload: DispatchAgentPayload):
    room_name = payload.room
    agent_name = payload.agent_name
    # Serialize metadata to JSON for LiveKit API
    # Handle both dict (persona) and list (backward compatibility) formats
    if isinstance(payload.metadata, dict):
        metadata_json = json.dumps(payload.metadata)
    elif isinstance(payload.metadata, list):
        metadata_json = json.dumps([item.model_dump() if hasattr(item, 'model_dump') else item for item in payload.metadata])
    else:
        metadata_json = json.dumps(payload.metadata)
    logger.info(f"#### {metadata_json} ####")
    lkapi = api.LiveKitAPI(
        os.getenv("LIVEKIT_URL"),
        os.getenv("LIVEKIT_API_KEY"),
        os.getenv("LIVEKIT_API_SECRET"),
    )

    dispatch_req = CreateAgentDispatchRequest(
        agent_name=agent_name,
        room=room_name,
        metadata=metadata_json,
    )

    try:
        dispatch_resp = await lkapi.agent_dispatch.create_dispatch(dispatch_req)
    except Exception as e:  # noqa: BLE001
        raise HTTPException(
            status_code=500, detail=f"Failed to dispatch agent: {str(e)}"
        )
    finally:
        await lkapi.aclose()

    return {
        "status": "ok",
        "room": room_name,
        "agent_name": agent_name,
        "patient_name": payload.patient_name,
        "dispatch_id": getattr(dispatch_resp, "dispatch_id", None),
    }
t
It looks like the issue might be coming from the dispatch logic creating new participants with unique identities each time. I’d love to understand a bit more—are you trying to make sure that only one agent gets dispatched per room, or are you hoping to prevent multiple agents with different identities from being created? Also, do you currently have any checks in place to see if an agent is already in the room before dispatching another? Let’s work through this together! Sources: pkg/rtc/room.go | Agent dispatch | LiveKit Docs
d
I want to: • Start conversation with one agent • Close conversation • Be able to restart conversation in a new room with a new agent dispatch ( same entrypoint )
t
To help you achieve your goal of starting a conversation with one agent, closing it, and then restarting in a new room with a new agent dispatch, here’s a friendly step-by-step guide: • Ensure Unique Agents Per Room: It’s important to use explicit agent dispatch by creating a dispatch for each room. This way, each room gets its own unique agent. For instance, you can use the
create_dispatch
method to assign an agent specifically to a room. • Restart Conversations: When you’re ready to close a conversation, simply delete the existing agent dispatch using its
dispatch_id
. This ends the agent’s session. Then, to start fresh, create a new dispatch for the new room. • Room Lifecycle Management: You can control how long rooms stay active after participants leave by setting room timeouts like
empty_timeout
and
departure_timeout
. This helps keep things tidy and efficient. • Pass Metadata: Don’t forget to use the
metadata
field in your dispatch requests! Passing contextual info like user details or session history helps the agent maintain continuity even after restarts. If you’d like, I’m here to provide detailed code examples or walk you through any of these steps. Just let me know! Sources: livekit-api/livekit/api/agent_dispatch_service.py | examples/agent-dispatch/index.ts | Web and mobile frontends | LiveKit Docs | Worker lifecycle | LiveKit Docs | Agent dispatch | LiveKit Docs
d
And yes I want to make sure that only one agent join the room
t
To make sure that only one agent joins a room, here are some helpful steps you can follow: • Check for Existing Agents: Before sending a new agent in, take a moment to see if there’s already an agent in the room. You can use the LiveKit API to list the participants and check for any existing agent identities. • Prevent Duplicate Dispatches: Keep track of active dispatches for each room. Before creating a new dispatch, double-check that there isn’t already one active for that room. • Use Unique Agent Identities: Give each agent a consistent identity for every room. LiveKit will then help prevent duplicate connections if an agent with the same identity is already present. • Handle Reconnection Logic: If an agent disconnects and reconnects, make sure the reconnection process reuses the existing agent instance instead of creating a new one. Following these steps will help you keep just one agent in each room. If you’d like, I’m here to help with any code examples or further guidance—just let me know!
e
Hey @damp-belgium-53878 Root Cause: /dispatchAgent is called again after reconnect, because the previous dispatch isn’t deleted and the agentDispatchedRef resets on remount. Each call spawns a new agent instance that remains alive. Frontend (React / TypeScript) — minimal replacement / additions Place these changes into your existing LivekitRoom component. They are drop-in: add the constants & refs, load persisted dispatch_id, update joinRoom to persist dispatch_id, and update leaveRoom to delete it. // --- top of file / constants --- const DISPATCH_DELETE_ENDPOINT = API_URL ?
${API_URL}/deleteDispatch
: '/deleteDispatch'; // --- inside LivekitRoom component (add these refs/state) --- const dispatchIdRef = useRef null(null); // load persisted dispatch id for this room on mount (prevents duplicate dispatch across remounts in same tab) useEffect(() => { try { const stored = sessionStorage.getItem(
dispatch:${roomName}
); if (stored) dispatchIdRef.current = stored; } catch (e) { console.warn('sessionStorage unavailable', e); } }, [roomName]); // --- replace your joinRoom with this version (or merge) --- const joinRoom = useCallback(async () => { if (isJoiningRef.current) return; isJoiningRef.current = true; setLoading(true); setError(null); try { const params = new URLSearchParams({ room: roomName, identity: patientName, name: patientName }); const res = await fetch(
${TOKEN_ENDPOINT}?${params.toString()}
); const { token } = await res.json(); if (!token) throw new Error('No token received'); // Only dispatch if we DON'T already have a dispatch id for this room if (DISPATCH_ENDPOINT && !dispatchIdRef.current) { agentDispatchedRef.current = true; // prevent concurrent double-dispatch in this instance const dispatchRes = await fetch(DISPATCH_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ agent_name: "patient", room: roomName, patient_name: patientName, metadata: patientMetadata ?? [], }), }); if (dispatchRes.ok) { const dispatchJson = await dispatchRes.json(); const dispatch_id = dispatchJson.dispatch_id; if (dispatch_id) { dispatchIdRef.current = dispatch_id; try { sessionStorage.setItem(
dispatch:${roomName}
, dispatch_id); } catch (e) {} } else { console.warn('Dispatch response missing dispatch_id', dispatchJson); } } else { console.warn('Dispatch failed:', await dispatchRes.text()); } } setToken(token); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to join room'); } finally { setLoading(false); isJoiningRef.current = false; } }, [roomName, patientName, patientMetadata]); // --- replace your leaveRoom with this (or merge) --- const leaveRoom = useCallback(async () => { // Best-effort: delete the dispatch if we created one const did = dispatchIdRef.current; if (did && DISPATCH_DELETE_ENDPOINT) { try { await fetch(DISPATCH_DELETE_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ room: roomName, dispatch_id: did }), }); } catch (err) { console.warn('Failed to delete dispatch', err); } finally { try { sessionStorage.removeItem(
dispatch:${roomName}
); } catch (e) {} dispatchIdRef.current = null; } } // reset local flags and leave agentDispatchedRef.current = false; setToken(undefined); onCallEnd?.(); }, [roomName, onCallEnd]); --- Backend (FastAPI) — minimal endpoints (drop-in to your router) This example uses a simple in-memory store for room -> dispatch_id. Replace with a persistent DB (Postgres / Redis) in production. from fastapi import APIRouter, HTTPException from pydantic import BaseModel import os, json router = APIRouter() # Naive in-memory mapping (use DB in prod) _dispatch_store: dict[str, str] = {} class DispatchAgentPayload(BaseModel): room: str agent_name: str patient_name: str | None = None metadata: dict | list | None = None class DeleteDispatchPayload(BaseModel): room: str dispatch_id: str @router.post("/dispatchAgent") async def dispatch_agent(payload: DispatchAgentPayload): room_name = payload.room # Idempotent: if we already dispatched for this room, return the same dispatch_id existing = _dispatch_store.get(room_name) if existing: return {"status": "ok", "room": room_name, "dispatch_id": existing, "note": "already_exists"} # Prepare metadata string for LiveKit metadata_json = json.dumps(payload.metadata or {}) lkapi = api.LiveKitAPI(os.getenv("LIVEKIT_URL"), os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET")) try: dispatch_req = CreateAgentDispatchRequest(agent_name=payload.agent_name, room=room_name, metadata=metadata_json) dispatch_resp = await lkapi.agent_dispatch.create_dispatch(dispatch_req) dispatch_id = getattr(dispatch_resp, "dispatch_id", None) if not dispatch_id: raise Exception("create_dispatch returned no dispatch_id") _dispatch_store[room_name] = dispatch_id except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to dispatch agent: {str(e)}") finally: await lkapi.aclose() return {"status": "ok", "room": room_name, "dispatch_id": dispatch_id} @router.post("/deleteDispatch") async def delete_dispatch(payload: DeleteDispatchPayload): lkapi = api.LiveKitAPI(os.getenv("LIVEKIT_URL"), os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET")) try: resp = await lkapi.agent_dispatch.delete_dispatch(payload.dispatch_id, payload.room) # Remove mapping if it matches if payload.room in _dispatch_store and _dispatch_store[payload.room] == payload.dispatch_id: del _dispatch_store[payload.room] except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to delete dispatch: {str(e)}") finally: await lkapi.aclose() return {"status": "ok", "deleted_dispatch_id": payload.dispatch_id} --- Short description / notes Frontend: persist dispatch_id to sessionStorage and avoid re-dispatch if present; delete on leave. Backend: make dispatchAgent idempotent by returning existing dispatch_id if present; add deleteDispatch which calls LiveKit delete_dispatch and removes mapping. Production: replace in-memory _dispatch_store with durable storage (DB/Redis) to survive restarts and multi-server deployments. Also ensure agent worker calls ctx.shutdown() when its job ends to avoid orphaned participants. If you want, I can now produce a tiny git-style diff for each file (or the DB-backed example). Which would be more useful?
t
The solution you've shared does a great job of making sure only one agent joins a room by: • Saving the
dispatch_id
in
sessionStorage
so we avoid duplicate dispatches when remounting. • Designing the
/dispatchAgent
endpoint to be idempotent, which means it returns the existing
dispatch_id
if there's already a dispatch for that room. • Introducing a
/deleteDispatch
endpoint to tidy up the dispatch when someone leaves the room. This method is really solid and scalable, especially with the helpful tip to switch from an in-memory store to a durable database for production. If you'd like, I’d be happy to provide a git-style diff of the changes or an example that uses a database—just let me know how I can support you!