how do I create a livekit agent with an agent name...
# ask-ai
v
how do I create a livekit agent with an agent name so I can dispatch from a Ruby on Rails application. When I do lk agent create I can’t figure out how to add an agent name
t
Thanks for reaching out, Michael. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand it can be a bit confusing, so let me help clarify! The
lk agent create
command doesn’t let you specify an agent name directly—it automatically generates an agent ID for you. If you’d like to assign a name for dispatch purposes, you’ll do that within your agent application code when you define
WorkerOptions
, rather than during the creation step. Now, if your goal is to start a new agent project with a specific name, the
lk agent init
command is the way to go, as it accepts an
[AGENT-NAME]
argument. Please feel free to reach out if you want me to walk you through this or if you have any other questions—I’m here to help! Sources: CLI Tools & Token Management | livekit/livekit_composite | DeepWiki | Agent deployment CLI reference | LiveKit Docs | autocomplete/fish_autocomplete | examples/agent_dispatch.py
v
can you explain this? when I create a token using the livekit-server-sdk gem in ruby on rails I need to provide agent_name otherwise the room is created but there is no agent there. Is this correct?
t
When creating a token using the
livekit-server-sdk
gem in Ruby on Rails, you have the option to specify an
agent_name
to make sure the right agent is sent to the room. This is done by setting the
room_config
property on the access token. Here’s a simple example to guide you:
Copy code
require 'livekit'

token = LiveKit::AccessToken.new(api_key: 'yourkey', api_secret: 'yoursecret')
token.identity = 'participant-identity'
token.name = 'participant-name'
token.video_grant = LiveKit::VideoGrant.new(roomJoin: true, room: 'room-name')

# Configure agent dispatch
token.room_config = LiveKit::Proto::RoomConfiguration.new(
  agents: [LiveKit::Proto::RoomAgentDispatch.new(
    agent_name: "test-agent",
    metadata: "test-metadata",
  )]
)

jwt = token.to_jwt
puts jwt
To clarify: •
agent_name
is where you specify the agent you want to dispatch. •
metadata
lets you include any extra details you want the agent to have. If anything feels unclear or you’d like a hand implementing this in your Rails app, just let me know—I’m here to help! Sources: README.md | packages/livekit-server-sdk/README.md | Voice Assistant Applications | livekit/livekit_composite | DeepWiki
v
Perfect, so where do I define this agent_name on the livekit side?
t
Hi there! To set the
agent_name
on the LiveKit side, you’ll want to include it in the
WorkerOptions
when you create your agent worker. Here’s a quick example to guide you: Python:
Copy code
# When creating your agent worker
worker_options = WorkerOptions(agent_name="test-agent")
Node.js:
Copy code
// When creating your agent worker
const workerOptions = {
  agentName: "test-agent"
}
Once you’ve set this
agent_name
, make sure it matches the name used in: • API dispatch requests • Room configurations in access tokens • SIP dispatch rules (if you’re using them) If you have any questions or need a hand with this setup, just let me know—I’m here to help! Sources: Agent dispatch | LiveKit Docs | Agents telephony integration | LiveKit Docs | livekit-api/livekit/api/agent_dispatch_service.py | SIP troubleshooting guide | LiveKit Docs
v
here is my agent.py with the agent_name defined at the bottom. is this code ok - import logging from dotenv import load_dotenv from livekit.agents import ( Agent, AgentSession, JobContext, JobProcess, MetricsCollectedEvent, RoomInputOptions, WorkerOptions, cli, metrics, ) from livekit.plugins import noise_cancellation, silero from livekit.plugins.turn_detector.multilingual import MultilingualModel logger = logging.getLogger(“agent”) load_dotenv(“.env.local”) class Assistant(Agent): def __init__(self) -> None: super().__init__( instructions=“”"You are a dating coach and you help users improve their dating lives. Provide thoughtful, empathetic, and practical advice to help users navigate their dating challenges.“”", ) def prewarm(proc: JobProcess): proc.userdata[“vad”] = silero.VAD.load() async def entrypoint(ctx: JobContext): # Logging setup # Add any other context you want in all log entries here ctx.log_context_fields = { “room”: ctx.room.name, } # Set up a voice AI pipeline using OpenAI, Cartesia, AssemblyAI, and the LiveKit turn detector session = AgentSession( # Speech-to-text (STT) is your agent’s ears, turning the user’s speech into text that the LLM can understand # See all available models at https://docs.livekit.io/agents/models/stt/ stt=“assemblyai/universal-streaming:en”, # A Large Language Model (LLM) is your agent’s brain, processing user input and generating a response # See all available models at https://docs.livekit.io/agents/models/llm/ llm=“openai/gpt-4.1-mini”, # Text-to-speech (TTS) is your agent’s voice, turning the LLM’s text into speech that the user can hear # See all available models as well as voice selections at https://docs.livekit.io/agents/models/tts/ tts=“cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc”, # VAD and turn detection are used to determine when the user is speaking and when the agent should respond # See more at https://docs.livekit.io/agents/build/turns turn_detection=MultilingualModel(), vad=ctx.proc.userdata[“vad”], # allow the LLM to generate a response while waiting for the end of turn # See more at https://docs.livekit.io/agents/build/audio/#preemptive-generation preemptive_generation=True, ) # Metrics collection, to measure pipeline performance # For more information, see https://docs.livekit.io/agents/build/metrics/ usage_collector = metrics.UsageCollector() @session.on(“metrics_collected”) def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() logger.info(f”Usage: {summary}“) ctx.add_shutdown_callback(log_usage) # Start the session, which initializes the voice pipeline and warms up the models await session.start( agent=Assistant(), room=ctx.room, room_input_options=RoomInputOptions( # For telephony applications, use
BVCTelephony
for best results noise_cancellation=noise_cancellation.BVC(), ), ) # Join the room and connect to the user await ctx.connect() if name == “__main__“: cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name=“kora_agent”, prewarm_fnc=prewarm))
t
Thank you for sharing your code! You've done a great job defining
agent_name
in
WorkerOptions
. This setup allows you to have explicit control over agent dispatch, which means you decide exactly when and how the agent joins rooms. Let me walk you through it: • By setting
agent_name
, automatic dispatch is turned off, so the agent will join rooms only when you explicitly dispatch it using the
AgentDispatchService
API. • This method works wonderfully for situations like telephony integrations or when you want to manage agent behavior very precisely. Looking at your code:
Copy code
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="kora_agent", prewarm_fnc=prewarm))
Everything looks spot on for explicit dispatch! If you have any questions or want to explore this further, please feel free to ask—I'm here to help! Sources: Agent dispatch | LiveKit Docs | metrics/metrics_stt.py | Agents telephony integration | LiveKit Docs | Worker options | LiveKit Docs
v
so when I run all this code, it connects to a room but I don’t think it brings in the agent - here is my console - livekit_controller-64004d78.js:182 Subscribed to agent-AJ_24GFNKgefCY7 livekit-client-f7595138.js:208 publishing track {room: ‘kora_room’, roomID: ‘’, participant: ‘22’, pID: ‘PA_Jv7NNLx7vsGg’, trackID: undefined, …}
t
I'm here to help you troubleshoot if your agent connects to a room but doesn't appear. Let's go through some friendly steps together: • Verify Agent Name: Please double-check that the
agent_name
in
WorkerOptions
exactly matches the name used in your dispatch rule or token configuration. This little detail can make a big difference! • Check Worker Availability: Make sure you have enough agent workers running to handle dispatch requests. The workers need to be available and ready to accept jobs for things to run smoothly. • Monitor Connection Events: Try using event callbacks like
OnParticipantConnected
to see if the agent is actually joining the room. It’s a helpful way to keep track. • Diagnostic Commands: Running
lk agent status --id <agent-id>
and
lk agent logs --id <agent-id> --log-type=deploy
can give you valuable insights into the agent’s status and logs. • Explicit Dispatch: If you’re using explicit dispatch, please check that the dispatch request is properly configured and sent to the agent. This ensures everything reaches the right place. If you’d like, I’m more than happy to walk you through any of these steps in detail or offer further assistance. Just let me know! Sources: Community & Support | livekit/livekit_composite | DeepWiki | Worker lifecycle | LiveKit Docs | README.md | pkg/loadtester/agentloadtester.go | Agent dispatch | LiveKit Docs
v
take a look at my rails token creation and tell me if that is correct - require “livekit” class Api:V1:LivekitController < ApplicationController # Security note: In a real app, you would add authentication checks here skip_before_action :verify_authenticity_token, only: [ :token ] # Endpoint to generate the LiveKit JWT token def token # 1. Get member details from the request payload member_id = params[:member_id].to_s member_name = params[:member_name].to_s # Ensure we have a unique ID for the LiveKit participant unless member_id.present? return render json: { error: “member_id is missing and is required to create the LiveKit token.” }, status: :bad_request end # --- 2. Get Environment Variables --- api_key = Rails.application.credentials.livekit[:api_key] api_secret = Rails.application.credentials.livekit[:api_secret] room_name = “kora_room” agent_name = “kora_agent” # --- 3. Define Participant Identity --- # Use the member_id for the LiveKit identity (must be unique) participant_identity = member_id # Use the member_name for the LiveKit display name participant_name = member_name.present? ? member_name : “Member #{member_id}” # --- 4. Define Video Grant (Permissions) --- grant = LiveKit::VideoGrant.new( roomJoin: true, room: room_name, canPublish: true, # Can publish their microphone canSubscribe: true # Can hear the agent ) # --- 5. Define Room Configuration (Agent Dispatch) --- # This tells LiveKit to send the agent into the room when this participant joins. agent_dispatch = LiveKit:Proto:RoomAgentDispatch.new( agent_name: agent_name, metadata: { greeting: “Welcome to Kora, let’s chat.” }.to_json ) room_config = LiveKit:Proto:RoomConfiguration.new( agents: [ agent_dispatch ] ) # --- 6. Create the Access Token --- token = LiveKit::AccessToken.new(api_key: api_key, api_secret: api_secret) token.identity = participant_identity token.name = participant_name token.video_grant = grant token.room_config = room_config # Attach the agent dispatch configuration jwt_token = token.to_jwt # Send the token and the server URL back to the client render json: { token: jwt_token, livekit_url: Rails.application.credentials.livekit[:url] } end end
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!