"I have a FastAPI backend with a voice service tha...
# ask-ai
c
"I have a FastAPI backend with a voice service that processes audio chunks, but I want to integrate it properly with LiveKit Agents SDK. Currently, I'm just buffering audio chunks and calling an AI service, but I need to implement a proper LiveKit voice agent that: 1. Uses the full STT-LLM-TTS pipeline with Deepgram STT, OpenAI LLM, and ElevenLabs TTS 2. Connects to LiveKit rooms and handles real-time voice interactions 3. Implements proper turn detection using Silero VAD and LiveKit's turn detector 4. Follows the standard AgentSession pattern from the documentation 5. Can be deployed as a LiveKit agent that can be called from web/mobile frontends My current setup: • FastAPI backend with audio chunk processing • Frontend sending audio chunks via MediaRecorder • Basic AI service integration • LiveKit credentials configured What's the best approach to refactor my current audio chunk processing into a proper LiveKit voice agent that can handle real-time conversations while maintaining my existing FastAPI endpoints for other functionality?"
t
Thanks for reaching out, raj. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you're looking to refactor your FastAPI backend into a proper LiveKit voice agent, here’s a friendly step-by-step guide to help you out: 1. Set Up the Agent: Start by defining an agent that extends the
Agent
class. Then, configure it with plugins for STT (like Deepgram), LLM (such as OpenAI), TTS (ElevenLabs is a great choice), and turn detection (Silero VAD works well). 2. Configure the STT-LLM-TTS Pipeline: Use LiveKit plugins to smoothly connect your AI services into the pipeline. For instance, Deepgram handles STT, OpenAI takes care of LLM, and ElevenLabs manages TTS. 3. Enable Turn Detection: Make sure to use LiveKit's turn detection features like VAD or even a custom detector. This helps keep real-time conversations flowing naturally by managing when the user and agent speak. 4. Implement the AgentSession Pattern: Create an
AgentSession
to handle your voice agent’s lifecycle. This covers connecting to LiveKit rooms, managing media streams, and dealing with events like interruptions or gathering metrics. 5. Deploy as a LiveKit Agent: Finally, plug the
AgentSession
into your FastAPI backend so it can be accessed from your web or mobile frontends, all while keeping your existing endpoints intact. Following these steps will get you set up for real-time voice interactions with a solid STT-LLM-TTS pipeline and reliable turn detection. If you want me to dive deeper into any part, just let me know—I'm here to help! Sources: livekit-agents/livekit/agents/voice/agent.py | agent.py | agents/src/voice/agent_activity.ts
c
"I have a FastAPI backend that I want to refactor into a proper LiveKit voice agent. Currently, I'm manually processing audio chunks and calling AI services directly, but I want to use the LiveKit Agents SDK properly. My current setup: • FastAPI backend with manual audio chunk processing • Frontend sending audio chunks via MediaRecorder • Manual STT, LLM, and TTS calls • No proper LiveKit room connection I want to: 1. Convert my FastAPI backend to use the LiveKit Agents SDK with proper AgentSession 2. Set up the STT-LLM-TTS pipeline using LiveKit plugins (Deepgram, OpenAI, ElevenLabs) 3. Enable proper turn detection and voice activity detection 4. Connect to LiveKit rooms properly 5. Maintain my existing FastAPI endpoints while adding LiveKit functionality Can you provide a complete example of how to structure this? I have the Agent class code and AgentActivity code from the documentation, but I need help with: • How to integrate AgentSession with FastAPI • How to handle room connections and participant management • How to set up the proper voice pipeline • How to maintain both REST API and LiveKit functionality in the same service I'm using Python with FastAPI and want to keep my existing authentication and database logic while adding LiveKit voice capabilities."
t
Hey there! If you want to integrate LiveKit AgentSession with your FastAPI backend and still keep your REST API running smoothly, here’s a friendly step-by-step guide: 1. Initialize AgentSession: Set up an
AgentSession
instance when your FastAPI app starts. You’ll want to configure it with STT (like Deepgram), LLM (such as OpenAI), TTS (for example, ElevenLabs), and turn detection (like Silero VAD). 2. Manage Asynchronous Tasks: Use FastAPI’s background tasks or task groups to run the voice agent alongside your REST endpoints. This way, the agent works independently without blocking your API requests. 3. Connect to LiveKit Rooms: Utilize the
RoomIO
class to handle media streams between the agent and room participants. Starting the
AgentSession
with a room parameter lets you manage audio track publishing and subscribing seamlessly. 4. Handle Session Lifecycle: Adapt the
entrypoint
function from LiveKit examples to kick off and manage the agent session within FastAPI’s app context. Don’t forget to clean up properly when your app shuts down. 5. Maintain REST Endpoints: Keep your existing FastAPI routes for authentication and database stuff just as they are. The voice agent will run alongside without interfering. This way, you can add those awesome LiveKit voice features while keeping your backend structure intact. If you want, I’m happy to share some code snippets or explain anything in more detail—just let me know! Sources: Building voice agents | LiveKit Docs | examples/voice_agents/realtime_joke_teller.py
c
is this implementation fine
t
Could you tell me a bit more about how you’ve set things up so far? For example: • How are you initializing and configuring the
AgentSession
? • What’s your approach to managing the connection to LiveKit rooms? • Are you using FastAPI’s background tasks or something else to run the voice agent? • How are you handling turn detection and the STT-LLM-TTS pipeline? Knowing these details will really help me understand your setup better and offer more tailored advice.
c
Great questions! Let me break down the current implementation details for you: ## 1. AgentSession Initialization and Configuration Currently, I have two different approaches set up: ### Approach A: Standalone LiveKit Agent (Recommended)
Copy code
python
# In run_livekit_agent.py
async def entrypoint(ctx: JobContext):
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    participant = await ctx.wait_for_participant()

    # Create AgentSession with proper configuration
    session = AgentSession(
        vad=silero.VAD.load(),
        min_endpointing_delay=0.5,
        max_endpointing_delay=5.0,
    )

    # Create KAORI agent
    agent = KAORIVoiceAgent()
    agent.session_id = ctx.room.name
    agent.user_id = participant.identity
    agent.user_name = participant.name or "User"

    # Start the agent session
    await session.start(
        room=ctx.room,
        agent=agent,
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(),
        ),
        room_output_options=RoomOutputOptions(
            audio_enabled=True,
            audio_sample_rate=24000,
            audio_num_channels=1,
            transcription_enabled=True,
        ),
    )
### Approach B: FastAPI Integration (Current Implementation)
Copy code
python
# In livekit_voice_service.py
class LiveKitVoiceService:
    def __init__(self):
        self.sessions: Dict[str, VoiceSessionData] = {}
        self.agent_sessions: Dict[str, AgentSession] = {}
        # Note: AgentSessions are created but not properly connected to rooms
Issue: The FastAPI approach doesn't actually create proper LiveKit room connections - it's more of a session management layer. ## 2. LiveKit Room Connection Management Currently, I have a hybrid approach that's not ideal: ### What's Working: - The standalone agent (
run_livekit_agent.py
) properly connects to LiveKit rooms - Uses
ctx.connect()
and
ctx.wait_for_participant()
- Proper room lifecycle management ### What's Missing: - The FastAPI service doesn't actually connect to LiveKit rooms - It just manages session state and event queues - No real-time audio processing through LiveKit ## 3. Background Task Management Currently using FastAPI's startup/shutdown events:
Copy code
python
@app.on_event("startup")
async def startup_event():
    try:
        from app.core.livekit_voice_service import voice_service
        logger.info(":white_check_mark: LiveKit voice service initialized")
    except Exception as e:
        logger.warning(f":warning: LiveKit voice service failed to initialize: {e}")

@app.on_event("shutdown")
async def shutdown_event():
    # Cleanup code
Problem: This doesn't actually run the LiveKit agent - it just initializes the service class. ## 4. Turn Detection and STT-LLM-TTS Pipeline ### Turn Detection:
Copy code
python
class KAORIVoiceAgent(Agent):
    def __init__(self, user_context: Dict[str, Any] = None):
        super().__init__(
            # ... other config
            allow_interruptions=True,
            min_endpointing_delay=0.5,
            max_endpointing_delay=5.0,
        )
### STT-LLM-TTS Pipeline:
Copy code
python
class KAORIVoiceAgent(Agent):
    def __init__(self, user_context: Dict[str, Any] = None):
        super().__init__(
            instructions="You are KAORI, a helpful productivity assistant...",
            stt=deepgram.STT(model="nova-2", language="multi"),
            llm=openai.LLM(model="gpt-4o-mini", timeout=30),
            tts=elevenlabs.TTS(
                api_key=os.getenv("ELEVENLABS_TTS_API_KEY"),
                voice_id="21m00Tcm4TlvDq8ikWAM",
                model="eleven_monolingual_v1"
            ),
            # turn_detection=MultilingualModel(),  # Commented out due to import issues
        )
## Current Architecture Issues ### 1. Split Architecture Problem I have two separate systems: - Standalone Agent: Proper LiveKit integration but no REST API - FastAPI Service: REST API but no real LiveKit room connections ### 2. Missing Room Connection in FastAPI The FastAPI service doesn't actually connect to LiveKit rooms - it just manages session state. ### 3. No Background Task Integration The LiveKit agent isn't running as a background task in FastAPI. ## Recommended Architecture Fix Based on the LiveKit documentation you provided, here's what I should implement: ### Option 1: Hybrid Approach (Recommended)
Copy code
python
# Run both FastAPI and LiveKit agent separately
# FastAPI handles REST API and session management
# LiveKit agent handles real-time voice processing
# Use Redis or database for communication between them
### Option 2: Integrated Approach
Copy code
python
# Use FastAPI background tasks to run LiveKit agents
# Each voice session gets its own LiveKit room
# AgentSession runs in background task
### Option 3: Microservices Approach
Copy code
python
# Separate FastAPI service for REST API
# Separate LiveKit agent service for voice processing
# Use message queue for communication
## Questions for You 1. Which approach would you prefer? The hybrid approach (separate services) or integrated approach (everything in FastAPI)? 2. How do you want to handle room creation? Should each voice session get its own LiveKit room, or should there be a shared room? 3. What's your preferred communication pattern? Direct LiveKit room connections from frontend, or REST API + SSE for events? 4. Do you want to keep the current FastAPI endpoints for backward compatibility, or are you open to a complete rewrite? The current implementation works for testing but isn't production-ready. I'd love to hear your preferences so I can refactor it into a proper, scalable architecture!
t
Thanks so much for sharing the detailed breakdown of your current setup and the challenges you’re facing. Based on what you’ve described, here are some friendly recommendations and answers to your questions: 1. Preferred Approach: The hybrid approach (Option 1) sounds like a great fit for your needs. It lets you keep your existing FastAPI REST API while running the LiveKit agent as a separate service for real-time voice processing. Using Redis or a database for communication is a smart way to keep things scalable and well-organized. 2. Room Creation: If each voice session stands on its own, creating a separate LiveKit room for each session is the way to go. This keeps audio streams nicely isolated and makes managing participants easier. But if your sessions are more collaborative, a shared room might work better. 3. Communication Pattern: For real-time interactions, connecting directly to LiveKit rooms from the frontend is recommended. You can still use REST API + SSE for extra event handling or updating session states. 4. Backward Compatibility: Holding onto your current FastAPI endpoints for backward compatibility is a solid plan, especially if you have existing clients depending on them. This way, you can gradually introduce LiveKit features without shaking up what’s already working. To tackle your specific issues: • FastAPI Integration: Try using FastAPI’s background tasks to run the LiveKit agent. Each session can spin up a background task that sets up an
AgentSession
and connects to a LiveKit room. • Room Connections: Make sure your FastAPI service can create and manage LiveKit rooms by leveraging the LiveKit server API for room creation and participant management. • Session Management: Keep session state in Redis or a database so your FastAPI service and LiveKit agent can communicate smoothly. • Turn Detection and Voice Pipeline: Your setup for STT, LLM, and TTS looks solid! Just double-check that the
AgentSession
is properly initialized with these components and linked to the room. If you want, I’d be happy to share detailed code examples or chat more about the architecture. Just let me know!
c
I see the issue! The FastAPI server is failing to start because there's an import error. The
voice.py
endpoint is trying to import
livekit_voice_service
but I renamed it to
voice_service
in the refactored code. Let me fix this import error: [1 tool called] I need to fix the import in the voice.py endpoint file: [1 tool called] Now I need to update all references to
livekit_voice_service
in the voice.py file: [1 tool called] Now let me check if there are any other files with the old import: [1 tool called] I need to fix the demo file as well: [1 tool called] Now let me try starting the FastAPI server again: [1 tool called] Let me wait a moment and then test if the server is running: [1 tool called] Let me check if there are any other import issues by running a quick test: [1 tool called] I see the issue! The voice.py file is trying to import from
voice_service
instead of
livekit_voice_service
. Let me fix this: [1 tool called] Now let me test the import again: [1 tool called] Great! Now let me start the FastAPI server: [1 tool called] Let me wait a moment and test the server: [1 tool called] Perfect! Now let me test the voice service endpoints: [1 tool called] Excellent! Now let me answer your original questions about the current setup: ## Current Implementation Details ### 1. AgentSession Initialization and Configuration I have two separate approaches currently: #### Standalone LiveKit Agent (Proper Implementation):
Copy code
python
# In run_livekit_agent.py
async def entrypoint(ctx: JobContext):
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    participant = await ctx.wait_for_participant()

    # Create AgentSession with proper LiveKit configuration
    session = AgentSession(
        vad=silero.VAD.load(),
        min_endpointing_delay=0.5,
        max_endpointing_delay=5.0,
    )

    # Create KAORI agent with full STT-LLM-TTS pipeline
    agent = KAORIVoiceAgent()
    await session.start(
        room=ctx.room,
        agent=agent,
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(),
        ),
        room_output_options=RoomOutputOptions(
            audio_enabled=True,
            audio_sample_rate=24000,
            audio_num_channels=1,
            transcription_enabled=True,
        ),
    )
#### FastAPI Integration (Session Management Only):
Copy code
python
# In livekit_voice_service.py
class LiveKitVoiceService:
    def __init__(self):
        self.sessions: Dict[str, VoiceSessionData] = {}
        self.agent_sessions: Dict[str, AgentSession] = {}  # Not actually used
        self.event_queues: Dict[str, asyncio.Queue] = {}
Issue: The FastAPI service doesn't actually create LiveKit room connections - it just manages session state. ### 2. LiveKit Room Connection Management #### What's Working: - Standalone agent properly connects to LiveKit rooms - Uses
ctx.connect()
and
ctx.wait_for_participant()
- Proper room lifecycle management #### What's Missing: - FastAPI service doesn't connect to actual LiveKit rooms - No real-time audio processing through LiveKit - Just manages session metadata and event queues ### 3. Background Task Management Currently using FastAPI startup/shutdown events:
Copy code
python
@app.on_event("startup")
async def startup_event():
    try:
        from app.core.livekit_voice_service import voice_service
        logger.info(":white_check_mark: LiveKit voice service initialized")
    except Exception as e:
        logger.warning(f":warning: LiveKit voice service failed to initialize: {e}")
Problem: This doesn't actually run the LiveKit agent - it just initializes the service class. ### 4. Turn Detection and STT-LLM-TTS Pipeline #### Turn Detection:
Copy code
python
class KAORIVoiceAgent(Agent):
    def __init__(self, user_context: Dict[str, Any] = None):
        super().__init__(
            allow_interruptions=True,
            min_endpointing_delay=0.5,
            max_endpointing_delay=5.0,
            # turn_detection=MultilingualModel(),  # Commented out due to import issues
        )
#### STT-LLM-TTS Pipeline:
Copy code
python
class KAORIVoiceAgent(Agent):
    def __init__(self, user_context: Dict[str, Any] = None):
        super().__init__(
            instructions="You are KAORI, a helpful productivity assistant...",
            stt=deepgram.STT(model="nova-2", language="multi"),
            llm=openai.LLM(model="gpt-4o-mini", timeout=30),
            tts=elevenlabs.TTS(
                api_key=os.getenv("ELEVENLABS_TTS_API_KEY"),
                voice_id="21m00Tcm4TlvDq8ikWAM",
                model="eleven_monolingual_v1"
            ),
        )
## Current Architecture Issues ### 1. Split Architecture Problem I have two separate systems that don't communicate: - Standalone Agent: Proper LiveKit integration but no REST API - FastAPI Service: REST API but no real LiveKit room connections ### 2. Missing Real-Time Processing The FastAPI service doesn't actually process audio through LiveKit - it just acknowledges receipt. ### 3. No Background Task Integration The LiveKit agent isn't running as a background task in FastAPI. ## Recommended Next Steps Based on the LiveKit documentation you provided, here are the options: ### Option 1: Hybrid Approach (Recommended) - Keep FastAPI for REST API and session management - Run LiveKit agent as separate service - Use Redis/database for communication between them ### Option 2: Integrated Approach - Use FastAPI background tasks to run LiveKit agents - Each voice session gets its own LiveKit room - AgentSession runs in background task ### Option 3: Microservices Approach - Separate FastAPI service for REST API - Separate LiveKit agent service for voice processing - Use message queue for communication Which approach would you prefer? The current implementation works for testing but needs to be refactored for production use.
t
Thanks so much for the detailed update and breakdown of your current setup! Based on what you’ve shared, here are a few recommendations and some clarifications that might help: 1. Hybrid Approach (Recommended): This seems like the best fit for your needs. It lets you keep your existing FastAPI REST API while running the LiveKit agent as a separate service for real-time voice processing. Using Redis or a database for communication is a great way to keep things scalable and nicely separated. 2. Room Connection: Make sure your FastAPI service can create and manage LiveKit rooms through the LiveKit server API. This way, you can handle room creation and participant management right from your backend. 3. Background Task Integration: You can use FastAPI’s background tasks to run the LiveKit agent. Each session could spin up a background task that initializes an
AgentSession
and connects to a LiveKit room. 4. Turn Detection and Voice Pipeline: Your setup for STT, LLM, and TTS looks solid! Just double-check that the
AgentSession
is properly initialized with these components and connected to the room. For turn detection, it might be worth sorting out the import issues with
MultilingualModel
or trying out a different detector if that’s easier. To help you move forward, could you let me know: • Are you leaning towards the hybrid approach, or would you like to explore the integrated or microservices options instead? • Do you want each voice session to have its own LiveKit room, or would a shared room setup work better for you? • Would you find detailed code examples helpful for any specific part of the implementation? Just let me know how you’d like to proceed, and I’m happy to guide you through the next steps or share some examples!
c
Thank you for the excellent feedback! I can see from the terminal output that the server is running successfully and the hybrid architecture is working - we're getting the expected 401 error for LiveKit credentials, which means the room creation API call is working correctly. Let me address your questions and provide some clarifications: ## Current Status & Recommendations ### ✅ Hybrid Approach Confirmed I've already implemented the hybrid approach you recommended, and it's working well! The architecture includes: 1. FastAPI Service: Handles REST API, session management, and event streaming 2. LiveKit Agent Manager: Runs agents as separate processes 3. LiveKit Room Manager: Manages rooms via LiveKit server API 4. Communication: Event queues for real-time communication ### ✅ Room Connection Strategy I've implemented per-session rooms as you suggested, which provides: - Isolation: Each voice session gets its own LiveKit room - Scalability: Sessions don't interfere with each other - Security: Better participant isolation - Management: Easier to track and clean up individual sessions ### ✅ Background Task Integration The system uses FastAPI background tasks to: - Start LiveKit agent processes for each session - Monitor agent health and status - Handle cleanup when sessions end - Manage process lifecycle ## Current Implementation Details ### Room Management
Copy code
python
# Each session gets its own room
room_name = f"room_{session_id}"
room_result = await room_manager.create_room(room_name)

# Room is automatically deleted when session ends
await room_manager.delete_room(room_name)
### Agent Management
Copy code
python
# Each session gets its own agent process
agent_result = await agent_manager.start_agent(
    session_id=session_id,
    room_name=room_name,
    user_id=user_id,
    user_name=user_name
)
### Session Lifecycle 1. Start: Create room → Start agent → Initialize session 2. Active: Handle audio chunks and events 3. End: Stop agent → Delete room → Clean up resources ## Next Steps & Configuration ### 1. LiveKit Credentials Setup The 401 error indicates we need to configure LiveKit credentials. You'll need:
Copy code
bash
# In your .env file or environment
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
### 2. Turn Detection Fix I can help fix the
MultilingualModel
import issue or implement an alternative turn detection method. ### 3. Testing the Complete Flow Once credentials are configured, we can test: - Room creation and management - Agent process startup - Real-time voice processing - Session cleanup ## Questions for You 1. LiveKit Server: Do you have a LiveKit server set up, or would you like me to help you configure one for testing? 2. Turn Detection: Would you prefer to: - Fix the
MultilingualModel
import issue - Use a different turn detection method (like VAD-based) - Implement a custom turn detection solution 3. Testing Approach: Would you like to: - Test with a local LiveKit server first - Use LiveKit Cloud for testing - Set up a mock implementation for development 4. Frontend Integration: Are you planning to: - Connect directly to LiveKit rooms from the frontend - Use the REST API + SSE approach - Implement both for different use cases ## Code Examples Available I can provide detailed code examples for: - LiveKit server setup and configuration - Turn detection implementation alternatives - Frontend integration patterns - Error handling and recovery - Production deployment considerations The hybrid architecture is fully implemented and ready for testing! The main blocker right now is the LiveKit credentials configuration. Once that's set up, you'll have a complete, scalable voice assistant system. What would you like to focus on next? I'm happy to help with any of these areas!
t
It’s awesome to hear that the hybrid architecture is working smoothly and that you’ve successfully set up per-session rooms, background task integration, and session lifecycle management! Here’s how we can move forward based on where you’re at and the questions you have: 1. LiveKit Server: If you already have a LiveKit server up and running, you can add the credentials to your environment file like this: `LIVEKIT_URL=wss://your-livekit-server.com LIVEKIT_API_KEY=your-api-key LIVEKIT_API_SECRET=your-api-secret`If you’d like a hand setting up a LiveKit server or testing with LiveKit Cloud, just say the word—I’m happy to walk you through it. 2. Turn Detection: About the
MultilingualModel
import issue, you’ve got a few options:Let me know which sounds best to you, and I can share detailed tips or code snippets. ◦ Fix the import so you can use
MultilingualModel
for turn detection. ◦ Go with a VAD-based turn detection method, which is simpler and works well in many cases. ◦ Create a custom turn detection solution tailored just for your needs. 1. Testing Approach: When it comes to testing, you might:Tell me what you prefer, and I’ll help you get it set up. ◦ Use a local LiveKit server for development and debugging. ◦ Try out LiveKit Cloud to mimic a production environment. ◦ Set up a mock implementation for early development and testing. 1. Frontend Integration: Depending on what you’re aiming for, you can:Let me know which integration style you’re leaning toward, and I can offer examples or recommendations. ◦ Connect directly to LiveKit rooms from the frontend for real-time interactions. ◦ Use the REST API + SSE method for event handling and session updates. ◦ Combine both approaches to cover different scenarios. Once your LiveKit credentials are in place, you’ll be all set to test the full flow—from creating rooms and starting agent processes to real-time voice processing and cleaning up sessions. Just let me know how you want to proceed or if there’s any specific part you’d like help with—I’m here for you!
c
## �� Summary of Current Issues & Questions for LiveKit AI Bot ### �� Current Status: - ✅ FastAPI Backend: Working perfectly (port 8000) - ✅ Room Creation: LiveKit rooms created successfully via API - ✅ Session Management: Voice sessions start and return proper responses - ✅ JWT Token Generation: Working for room creation - ❌ Agent Connection: Agents fail to connect to existing rooms ### 🚨 Main Problem: The LiveKit agent is trying to create a new room instead of joining an existing room that was already created by the FastAPI backend. This causes a 401 authentication error because the agent's JWT token doesn't have room creation permissions. ### ❓ Questions for LiveKit AI Bot: 1. Agent Connection Pattern: How do I configure a LiveKit agent to connect to an existing room instead of trying to create a new one? The agent should join a room that was already created by the FastAPI backend. 2. JWT Token Permissions: What are the correct JWT token permissions for an agent to join an existing room? Currently using:
Copy code
python
   grants = VideoGrants(
       room_join=True,
       room=room_name,
       can_publish=True,
       can_subscribe=True,
       can_publish_data=True
   )
3. Agent CLI Usage: When using
livekit.agents.cli.run_app()
with the
connect
command, how do I ensure the agent connects to an existing room rather than creating a new one? 4. Worker Configuration: Is there a way to configure the LiveKit worker to join existing rooms instead of creating them? The current error shows it's calling
CreateRoom
API. 5. Environment Variables: Should I be using different environment variables or configuration to make the agent join existing rooms? ### 🔧 Current Implementation: - Using
livekit.agents.cli.run_app()
with
WorkerOptions
- Agent entrypoint connects with
await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
- JWT token generated with room join permissions - Agent started with
--room
,
--url
,
--api-key
,
--api-secret
,
--participant-identity
parameters The core issue is that the agent framework is automatically trying to create rooms instead of joining existing ones.
t
Hey there! If you want to set up a LiveKit agent so it joins an existing room instead of creating a new one, here’s a simple way to do it: 1. Explicit Agent Dispatch: Make sure you explicitly dispatch the agent to the room. Usually, agents auto-join new rooms, but once you set
agent_name
in the
WorkerOptions
, they won’t auto-join anymore and need to be dispatched manually. 2. Dispatch via API: You can use the
AgentDispatchService
to send the agent to a specific room programmatically. Here’s an example:
Copy code
# Python Example
lkapi = api.LiveKitAPI()
await lkapi.agent_dispatch.create_dispatch(
    api.CreateAgentDispatchRequest(
        agent_name="test-agent", 
        room="my-room", 
        metadata="my_metadata"
    )
)
3. Dispatch on Participant Connection: Another neat trick is to have the agent join automatically when a participant connects. You do this by adding a
RoomConfiguration
with the agent dispatch info in the participant’s access token. Check this out:
Copy code
# Python Example
token = (
    api.AccessToken()
    .with_identity("my_participant")
    .with_grants(api.VideoGrants(room_join=True, room="my-room"))
    .with_room_config(
        api.RoomConfiguration(
            agents=[api.RoomAgentDispatch(agent_name="test-agent", metadata="my_metadata")]
        )
    )
    .to_jwt()
)
Just double-check that your agent worker has
agent_name
set in its
WorkerOptions
. That way, the agent will join the existing room without trying to create a new one. If anything’s unclear or you want a hand with this, just let me know—I’m here to help! Sources: examples/agent-dispatch/index.ts | examples/agent_dispatch.py | Dispatching agents | LiveKit Docs