question, In my livekit room i use explict dispatc...
# ask-ai
f
question, In my livekit room i use explict dispatch for my agent into the room. that works well but now i want to enable conferences between two humans as well with the same code with no agent in the room. how can i support this as well?
t
Thanks for reaching out, Gad. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to help you set up conferences between two participants without needing an agent in the room! Here's a simple way to do it: 1. First, create a room using the LiveKit SDK or server API. 2. Next, generate access tokens for each participant, making sure they have permissions to join, publish, and subscribe to the room. 3. Then, connect both participants to the same room using the LiveKit client SDKs, like JavaScript, Flutter, or Swift. 4. Make sure each participant publishes their audio and video tracks. 5. By default, the LiveKit SFU will take care of track subscriptions between participants as long as the
autoSubscribe
option is enabled (which it is by default). This way, your participants can communicate smoothly without any special agent setup. If you have any questions or need a hand with any step, just let me know—I’m here to help! Sources: examples/rpc/README.md | lib/src/options.dart | test/agent_test.go | How to Enable Agent-to-Agent Speech Detection in LiveKit
f
all my code is already setup and working. if name == "__main__": agents.cli.run_app( agents.WorkerOptions(entrypoint_fnc=entrypoint, agent_name="interview-agent") ) but when its a regular conference the agent should just not join the conversation. how can i do it with the same code
t
To help you conditionally exclude the agent from joining a LiveKit room while using the same code, you can gently adjust the logic so the agent only joins when certain conditions are truly met. Here are two friendly approaches you might find useful: 1. Token-Based Conditional Dispatch: When you're generating access tokens, consider including the agent in the
RoomConfiguration
only if the situation calls for it. For instance, you could check the user role or room metadata before deciding to add the agent to the configuration. 2. Explicit Dispatch via API: Another way is to turn off automatic agent dispatch in your worker setup by setting
auto_register=False
. Then, you can use the
CreateAgentDispatchRequest
API to dispatch the agent programmatically, based on what's happening in real time—like participant behavior or other triggers. With either method, the agent will only join the room when you want them to. If you'd like, I’m here to help with code examples or to clarify anything further—just let me know! Sources: SIP dispatch rule | LiveKit Docs | Sources/LiveKit/Types/RoomConfiguration.swift | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | pkg/loadtester/agentloadtester.go | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik...
f
give me a sample code for option one, where i add an interview type in the metadata of the token and use it in main
t
Thank you for sharing your request! Here's a sample implementation for option one, where you add an interview type in the metadata of the token and use it in the main function:
Copy code
from livekit import AccessToken, VideoGrant
import os

def generate_token(identity, room_name, interview_type):
    # Create an access token with the necessary permissions
    token = AccessToken(
        os.getenv("LIVEKIT_API_KEY"),
        os.getenv("LIVEKIT_API_SECRET")
    )

    # Add identity and room permissions
    token.identity = identity
    token.add_grant(VideoGrant(room=room_name))

    # Add metadata to include the interview type
    token.metadata = f"{{'interview_type': '{interview_type}'}}"

    return token.to_jwt()

if __name__ == "__main__":
    # Example usage
    room_name = "example-room"
    identity = "participant-1"
    interview_type = "technical"  # Set the interview type here

    # Generate the token with metadata
    token = generate_token(identity, room_name, interview_type)

    # Use the token in your application logic
    print(f"Generated token: {token}")

    # Example: Pass the token to your agent logic
    if interview_type == "technical":
        agents.cli.run_app(
            agents.WorkerOptions(entrypoint_fnc=entrypoint, agent_name="interview-agent")
        )
    else:
        print("No agent required for this type of session.")
I hope this helps clarify how to include the interview type in the token metadata! The main function then uses this information to decide whether to dispatch the agent. If you have any questions or want to explore this further, please don’t hesitate to ask—I’m here to help!
f
but if i have a livekit service running. how can i get the token from the backend in the service main code?
t
I'd love to help you retrieve a LiveKit token from your backend! You can create a backend endpoint that generates the token using the LiveKit Server SDK. Here's a friendly example in Python to get you started:
Copy code
from livekit import AccessToken, VideoGrant
from flask import Flask, request, jsonify
import os

app = Flask(__name__)

@app.route('/token', methods=['POST'])
def generate_token():
    data = request.json
    identity = data.get('identity')
    room_name = data.get('roomName')

    # Create an access token
    token = AccessToken(
        api_key=os.getenv('LIVEKIT_API_KEY'),
        api_secret=os.getenv('LIVEKIT_API_SECRET'),
        identity=identity
    )

    # Add room permissions and metadata
    token.add_grant(VideoGrant(room=room_name, room_join=True, can_publish=True, can_subscribe=True))
    token.metadata = f"{{'interview_type': '{data.get('interviewType', 'default')}'}}"

    return jsonify({'token': token.to_jwt()})

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)
Here’s a quick overview: • Your backend offers a
/token
endpoint that takes in
identity
,
roomName
, and
interviewType
. • The token we generate includes some handy metadata like
interview_type
, and it's sent back to your client. On the client side, you just call this endpoint to get your token and connect to the LiveKit room smoothly. If you hit any bumps or want to dive deeper, just let me know—I’m here to help! Sources: Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | README.md | lib/services/token_service.dart | Generating tokens | LiveKit docs | app/src/main/java/io/livekit/android/example/voiceassistant/TokenExt.kt
f
thats good lets assume i have this logic implemented on my backend. what code should i have on the livekit side to use this token to conditionally dispatch the agent to the room?
t
I'm happy to guide you through how to use the token's metadata to conditionally dispatch an agent to a room. You can do this by embedding the dispatch configuration directly in the token's
RoomConfiguration
. Here's a friendly example to help you get started:
Copy code
from livekit import AccessToken, VideoGrant, RoomConfiguration, RoomAgentDispatch
import os
import json

def generate_token_with_agent(identity, room_name, interview_type):
    # Create an access token
    token = AccessToken(
        api_key=os.getenv('LIVEKIT_API_KEY'),
        api_secret=os.getenv('LIVEKIT_API_SECRET'),
        identity=identity
    )

    # Add room permissions
    token.add_grant(VideoGrant(room=room_name, room_join=True, can_publish=True, can_subscribe=True))

    # Conditionally add agent dispatch based on interview type
    if interview_type == "technical":
        token.with_room_config(
            RoomConfiguration(
                agents=[
                    RoomAgentDispatch(
                        agent_name="interview-agent",
                        metadata=json.dumps({"interview_type": interview_type})
                    )
                ]
            )
        )

    return token.to_jwt()

if __name__ == "__main__":
    # Example usage
    room_name = "example-room"
    identity = "participant-1"
    interview_type = "technical"  # Set the interview type here

    # Generate the token with conditional agent dispatch
    token = generate_token_with_agent(identity, room_name, interview_type)
    print(f"Generated token: {token}")
Here’s what’s happening in this example: • The
RoomConfiguration
includes an agent dispatch only when the
interview_type
matches the condition (like "technical"). • The
metadata
field carries structured JSON data that the agent can use to tailor its behavior during execution. On the agent side, you can easily access this metadata inside the
entrypoint
function to customize how the agent responds:
Copy code
def entrypoint(job):
    metadata = json.loads(job.metadata or "{}")
    interview_type = metadata.get("interview_type")
    if interview_type == "technical":
        # Initialize technical interview logic
        pass
    else:
        # Handle other cases
        pass
This approach ensures your agent is dispatched only when the conditions you set in the token generation are met. If anything feels unclear or if you want to dive deeper into any part, please don’t hesitate to ask—I’m here to help! Sources: packages/livekit-server-sdk/src/AgentDispatchClient.ts | examples/agent_dispatch.py | Agent dispatch | LiveKit Docs | Authentication | LiveKit Docs | Job lifecycle | LiveKit Docs
f
okay i removed the agent name from the main function in my livekit code, and added the dispatch as part of the token. but when i connect to a room with no dispatch options the agent still autoconnects to the room. how can i cancel auto dispatch and only dispatch if its part of the token config
t
Hi there! I’m happy to help you with disabling auto dispatch of agents so they only connect based on your token configuration. Here’s a simple way to set that up by assigning a specific
agent_name
in your worker setup. This way, your agent won’t auto-connect to any room unless you explicitly dispatch it. Let’s walk through the steps together: 1. Disable Auto Dispatch by Naming the Agent In your LiveKit worker code, you can set the
agent_name
within the
WorkerOptions
like this:
Copy code
from livekit.agents import Worker

worker = Worker(
    worker_name="my-named-agent",  # Assign a specific name to the agent
    auto_register=False  # Optional: Prevent auto-registration
)
By giving your agent a unique
agent_name
, it won’t auto-connect to any rooms and will only join when you dispatch it explicitly. 2. Dispatch Agent via Token Configuration When you generate the participant’s access token, you can include the agent dispatch details inside the
RoomConfiguration
. Here’s an example:
Copy code
from livekit import AccessToken, VideoGrant, RoomConfiguration, RoomAgentDispatch
import os
import json

def generate_token_with_agent(identity, room_name, interview_type):
    token = AccessToken(
        api_key=os.getenv('LIVEKIT_API_KEY'),
        api_secret=os.getenv('LIVEKIT_API_SECRET'),
        identity=identity
    )

    token.add_grant(VideoGrant(room=room_name, room_join=True, can_publish=True, can_subscribe=True))

    if interview_type == "technical":
        token.with_room_config(
            RoomConfiguration(
                agents=[
                    RoomAgentDispatch(
                        agent_name="my-named-agent",
                        metadata=json.dumps({"interview_type": interview_type})
                    )
                ]
            )
        )

    return token.to_jwt()
In this snippet, the agent will only be dispatched if the
interview_type
matches your condition, like "technical". This gives you great control over when agents join. 3. Verify Agent Dispatch Lastly, make sure your agent service is up and running with the same
agent_name
. If you want, you can also use the LiveKit API to list or debug dispatches to confirm everything is working smoothly. If you have any questions or need a hand with any of these steps, please don’t hesitate to reach out. I’m here to help! Sources: livekit-api/livekit/api/agent_dispatch_service.py | SIP dispatch rule | LiveKit Docs | Agent dispatch | LiveKit Docs | Agents telephony integration | LiveKit Docs | Authentication | LiveKit Docs
f
you dont understand me, if the agent dispatch is not part of the room config i want no agents dispatched the auto_register param does not exist.
t
I'm here to help you make sure no agents are dispatched unless you explicitly include them in your room configuration. Let's walk through the steps together: 1. Disable Automatic Dispatch by Setting
agent_name
In your agent worker setup, you’ll want to assign a specific
agent_name
in the
WorkerOptions
. This simple step disables automatic dispatch for that agent:
Copy code
from livekit.agents import Worker

worker = Worker(
    opts=WorkerOptions(
        agent_name="my-agent",  # Disables automatic dispatch
        entrypoint_fnc=agent_entrypoint
    )
)
Just a heads-up: agents without an
agent_name
are automatically dispatched, so this part is really important. 2. Avoid Including
agents
in Room Configuration
When you generate access tokens, make sure the
roomConfig
doesn’t include any
agents
unless you actually want them dispatched:
Copy code
from livekit import AccessToken, VideoGrant

def generate_token(identity, room_name):
    token = AccessToken(
        api_key="your_api_key",
        api_secret="your_api_secret",
        identity=identity
    )
    token.add_grant(VideoGrant(room=room_name, room_join=True, can_publish=True, can_subscribe=True))
    return token.to_jwt()
3. Do Not Use the Agent Dispatch API Also, please double-check that there are no explicit dispatch calls made via the
AgentDispatchService
API. For example, avoid doing this:
Copy code
# Example of dispatch API call to avoid
agentDispatchClient.createDispatch("room-name", "agent-name", metadata={})
4. Verify No Active Dispatches Finally, you can use the
listDispatch
method to confirm that no agents are currently dispatched to a room:
Copy code
dispatches = agentDispatchClient.listDispatch("room-name")
if dispatches:
    print("Agents are dispatched:", dispatches)
By following these steps, you’ll have full control so agents only join rooms when you explicitly want them to. If anything feels unclear or you want to dive deeper into any part, just let me know—I’m here to help! Sources: Agents telephony integration | LiveKit Docs | Agent dispatch | LiveKit Docs | livekit-agents/livekit/agents/worker.py | packages/livekit-server-sdk/src/AgentDispatchClient.ts | livekit-api/livekit/api/agent_dispatch_service.py
f
so i just need to set a name of an agent that does not exist in the agent name to avoid any dispatch to the room? now if i will have an agent dispatch in room config it will overwrite the agent_name and dispatch the relevant agent?
t
I'm glad you asked! Setting an
agent_name
in the worker configuration is a great way to make sure the agent won't auto-dispatch to any room unless it's specifically requested. So, if the
agent_name
doesn’t match any dispatch request (like through room configuration or API), the agent simply won’t join the room. Also, when you include an agent dispatch in the
roomConfig
of the access token, it explicitly sends that particular agent to the room, which overrides the usual behavior. This way, only the agent you want will be dispatched based on what’s set in the token. If you’d like, I’m here to help with any other questions or to walk you through the implementation—just let me know!
f
I am going to explain myself again. i want to have two modes for my session to run. one that will be a conversation with a voice agent. and the other one is a video conference. they both should have the following capabilites: egress saving to supabase transcription and duration tracking an backend update at the end of the call. i already have all of this for my agent conversation, how do i implement the video conference with the capabilites above without the agent connecting to the room?
t
Hi there! I’m happy to guide you through setting up a video conference with egress saving, transcription, and duration tracking—all without needing an agent connected to the room. Let’s take it step by step: 1. Egress Saving (Room Recording) You can use the Room Composite Egress feature to record your session. This is something you can easily trigger from your backend using the LiveKit server SDK:
Copy code
req = api.RoomCompositeEgressRequest(
    room_name="my-room",
    layout="speaker",
    gcp=api.GCPUpload(bucket="my-bucket", credentials="...")
)
egress_info = await lkapi.egress.start_room_composite_egress(req)
This will record all the shared audio and video in the room and save it directly to your cloud storage. Pretty handy, right? 2. Transcription While LiveKit doesn’t provide built-in transcription without an agent, you can still achieve this by forwarding audio to an external WebSocket server using Track Egress:
Copy code
track_req = api.TrackEgressRequest(
    room_name="my-room",
    track_id="audio-track-id",
    websocket_url="wss://your-stt-service/ws"
)
await lkapi.egress.start_track_egress(track_req)
Your WebSocket server will then receive the raw audio and can process it with an external speech-to-text service like Whisper or Google STT. This way, you keep things flexible and powerful! 3. Duration Tracking To keep track of how long your session lasts, you can use the Egress API to get the start and end times:
Copy code
response = await lkapi.egress.list_egress(ListEgressRequest(room_name="my-room"))
duration = response.egress_info[0].ended_at - response.egress_info[0].started_at
This will give you the session duration based on the egress lifecycle, so you always know exactly how long things ran. Summary: • Egress Saving: Fully supported without needing an agent. • Transcription: Can be done externally via Track Egress and an STT service. • Duration Tracking: Easily handled through the Egress API. If you’d like, I’d be more than happy to help you with a complete example that ties all these steps together. Just let me know! Sources: Session recording and transcripts | LiveKit Docs | egress/recording_agent.py | Universal Egress | livekit-agents/livekit/agents/inference/stt.py | livekit-api/livekit/api/egress_service.py
f
can i connect a hidden agent to the room that will take care of all of this? i already have all of it setup for the agent so i want to be able to run a conversation without the agent participating
t
Absolutely, you can connect a hidden agent to the room to manage egress, transcription, and duration tracking without actually participating in the conversation. Let me walk you through how you can set this up: 1. Egress as a Hidden Participant You can use the Room Composite Egress feature to start recording. This service connects to the room as a hidden participant, so it won’t interact with anyone else:
Copy code
req = api.RoomCompositeEgressRequest(
    room_name="my-room",
    layout="speaker",
    output=api.S3Upload(bucket="my-bucket", region="us-east-1")
)
res = await lkapi.egress.start_room_composite_egress(req)
This way, all shared audio and video in the room is recorded and saved directly to your cloud storage. 2. Transcription via Agent You can deploy a LiveKit agent with transcription enabled but without publishing audio. This means the agent listens and transcribes without joining the conversation:
Copy code
await session.start(
    agent=Transcriber(),
    room=ctx.room,
    room_output_options=RoomOutputOptions(
        transcription_enabled=True,
        audio_enabled=False,
    ),
)
The transcriptions are available in real time or can be forwarded to other services as needed. 3. Duration Tracking The agent can keep track of session duration by noting when participants join and leave. Alternatively, you can use the Egress API to get the start and end times like this:
Copy code
response = await lkapi.egress.list_egress(ListEgressRequest(room_name="my-room"))
duration = response.egress_info[0].ended_at - response.egress_info[0].started_at
4. Room Cleanup Don’t forget to delete the room once the session ends to stop recording and tidy up resources. This setup lets your agent handle all the backend work quietly in the background, without joining the chat. If you have any questions or want help with the implementation, just let me know—I’m here to help! Sources: Universal Egress | CreateRoom() is Taking Too Long | examples/other/transcription/transcriber.py | Session recording and transcripts | LiveKit Docs
f
can you show me an implementation of the transcriber agent?
t
I'd love to share an example implementation of a transcriber agent that connects to a LiveKit room, listens for audio, and performs transcription—all without participating in the conversation. Here it is:
Copy code
from livekit.agents import Worker, WorkerOptions, Job
from livekit import RoomOutputOptions
import json

# Define the transcriber agent class
class Transcriber:
    async def entrypoint(self, job: Job):
        # Parse metadata if needed
        metadata = json.loads(job.metadata or "{}")
        room_name = metadata.get("room_name", "default-room")

        # Start the session with transcription enabled but no audio publishing
        await job.start(
            room=room_name,
            room_output_options=RoomOutputOptions(
                transcription_enabled=True,  # Enable transcription
                audio_enabled=False          # Disable audio publishing
            )
        )

        # Listen for transcription events
        async for event in job.events():
            if event.type == "user_input_transcribed":
                transcription = event.data.get("text")
                print(f"Transcription: {transcription}")

            elif event.type == "conversation_item_added":
                item = event.data
                print(f"Conversation item: {item}")

        # Perform cleanup when the session ends
        print("Session ended.")

# Configure the worker to run the transcriber agent
if __name__ == "__main__":
    worker = Worker(
        opts=WorkerOptions(
            agent_name="transcriber-agent",  # Name of the agent
            entrypoint_fnc=Transcriber().entrypoint
        )
    )
    worker.run()
Key Features: • Transcription: The agent listens for transcription events like
user_input_transcribed
and logs the transcribed text. • Non-Participatory: The
audio_enabled=False
option ensures the agent does not publish audio or participate in the conversation. • Metadata Handling: The agent can use metadata passed during dispatch to customize its behavior (e.g., room name). I hope this helps you get started! If you have any questions or need further assistance setting up your LiveKit backend or connecting the agent to the right room, please don’t hesitate to reach out. I’m here to help!
f
will the agent be visibly in the room?
t
Absolutely! By default, a LiveKit agent shows up in the room as a participant. You can easily spot the agent because its
kind
field is set to
AGENT
, which helps everyone tell it apart from regular users. Plus, other participants can identify the agent using the
isAgent
property, and if you want to, you can filter agents using the
agentParticipants
property. If you have any questions or need a hand with managing agent visibility or filtering participants, just let me know—I’m here to help! Sources: Rooms, participants, and tracks | LiveKit docs | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | Sources/LiveKit/Agent/Room+Agent.swift | src/components/playground/Playground.tsx
f
can i hide the agent from showing in the room? while still having him transcribe in the background?
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
f
I have a video conference with multiagent transcribers. why do i still get an agent dispatched into the room as a participant? is there any way to make the agent not join as a participant in video conferences?