how can i get the room name on the agent class?
# ask-ai
o
how can i get the room name on the agent class?
t
Thanks for reaching out, fernando. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to get the room name from inside an Agent class — you can access it via the session's room object once the session is started/connected. Python:
Copy code
class MyAgent(Agent):
    async def on_enter(self):
        room_name = self.session.room.name
        print(f"Room name: {room_name}")
        await self.session.generate_reply(instructions="Hello, I've accessed the room name.")
Node.js / TypeScript:
Copy code
class MyAgent extends Agent {
    async onEnter(): Promise<void> {
        const roomName = this.session.room.name;
        console.log(`Room name: ${roomName}`);
        this.session.generateReply({ instructions: "Hello, I've accessed the room name." });
    }
}
If
this.session.room
is undefined, confirm the agent session has started/connected before accessing it. Would you like a snippet showing a connection check? Sources: Agents and handoffs | LiveKit docs | Agent session | LiveKit docs
o
AttributeError: 'AgentSession' object has no attribute 'room'
t
You're seeing that AttributeError because
AgentSession
does not have a
room
attribute. Responding to your question about how to get the room name inside an Agent class: • Access the room from the job entrypoint's
JobContext
(
ctx.room.name
) when the session is started. • Pass the room (or just the room name) into the Agent via
session.start(...)
and
userdata
so agent methods can read it. Python example:
Copy code
@server.rtc_session()
async def my_agent(ctx: JobContext):
    session = AgentSession(
        userdata={"room_name": ctx.room.name},
        # ...
    )
    await session.start(room=ctx.room, agent=MyAgent())

class MyAgent(Agent):
    async def on_enter(self):
        room_name = self.run_context.userdata["room_name"]
        print(room_name)
Node/TypeScript outline: • Read
ctx.room.name
in your entrypoint. • Put it into
userdata
when starting the session. • Inside the agent, read
context.userdata.room_name
. Do you want a version that passes the full
ctx.room
object into the agent instead of just the name, or can I tailor the snippet to where you're encountering the error? Sources: Job lifecycle | LiveKit docs | Agents and handoffs | LiveKit docs | Agent session | LiveKit docs
o
how can i greet the user when he answers the phone call?
t
You're asking how to greet the caller when they answer a phone call. Below are the two straightforward ways to do this and short examples—pick Python or Node.js depending on your codebase. Options • Let the agent LLM generate a natural greeting: call
session.generate_reply(instructions="...")
after the call is answered or after
session.start()
. • Play a fixed message via TTS: call
session.say("Hello...")
(requires a TTS plugin or pre-synthesized audio). Python (inbound or outbound after answer)
Copy code
# inside your rtc_session entrypoint, after session.start(...) and the call is answered
await session.generate_reply(instructions="Hello! Thanks for answering — how can I help you today?")
# or for a fixed phrase using TTS:
await session.say("Hello! Thanks for answering — how can I help you today?", allow_interruptions=False)
Notes: • For outbound calls, use
wait_until_answered=True
when creating the SIP participant so you only greet after pickup. • Ensure you call these after the session is started and the call is connected; otherwise the message may play too early. Would you like a complete example for your platform (Python or Node.js) or help adding conditional logic (e.g., different greetings for inbound vs outbound)? Sources: Agents telephony integration | LiveKit Docs | Agent speech and audio | LiveKit docs
o
im using python
t
Below is a concise, complete Python example showing how to greet the caller when the phone call is answered. It demonstrates reading the JobContext
ctx.room
, starting an
AgentSession
, and sending a greeting after the session starts (and after the call is answered). Use
generate_reply()
for an LLM-generated greeting or
say()
for a fixed TTS message.
Copy code
from livekit_server import server, JobContext
from livekit_agents import AgentSession, Agent

class MyAgent(Agent):
    async def on_enter(self):
        # optional: run when the agent's conversation starts
        pass

@server.rtc_session()
async def my_agent_entry(ctx: JobContext):
    # Create the session and pass any userdata if needed
    session = AgentSession(
        userdata={"room_name": ctx.room.name},
        # configure STT/LLM/TTS as needed
    )

    # Start the session connected to the incoming room (ctx.room)
    await session.start(room=ctx.room, agent=MyAgent())

    # --- Option A: LLM-generated natural greeting ---
    # This asks the agent/LLM to generate a greeting and speak it.
    await session.generate_reply(instructions="Greet the caller briefly and ask how you can help.")

    # --- Option B: Fixed TTS greeting ---
    # Use session.say to play a predetermined message (requires TTS plugin or pre-synth audio).
    # await session.say("Hello! Thanks for answering. How can I help you today?", allow_interruptions=False)

    # Keep the session running until finished/ended by your logic
    await session.wait_until_finished()
Key points: • Place the greeting after
session.start(...)
so it runs once the session is active and the participant has answered. • For outbound calls, create the SIP participant with
wait_until_answered=True
so you only proceed to greeting after pickup. • Use
generate_reply()
for dynamic, LLM-driven greetings or
say()
for fixed phrases via TTS. Would you like this example adapted to include conditional greetings (inbound vs outbound) or to wait for a specific participant join event before greeting?
o
i want to execute a function when the user joins the room, however, if i call the function after sesion.start(...), the function is called before the user joins the room
t
You're right — calling your function right after
session.start(...)
can run before a user actually joins. To run code exactly when a participant joins, listen for the room join event or wait for a participant. Two safe options in Python: 1) Event listener (recommended if you want to react to every join)
Copy code
@server.rtc_session()
async def my_agent(ctx: JobContext):
    session = AgentSession(...)

    @ctx.room.on("participant_connected")
    def _on_join(participant):
        # run async work without blocking the event loop
        asyncio.create_task(your_custom_function(participant))

    await session.start(room=ctx.room, agent=MyAgent())
    await session.wait_until_finished()
2) Wait for first participant (useful if you want to block until someone joins)
Copy code
@server.rtc_session()
async def my_agent(ctx: JobContext):
    session = AgentSession(...)
    await session.start(room=ctx.room, agent=MyAgent())

    first_participant = await ctx.wait_for_participant()
    await your_custom_function(first_participant)

    await session.wait_until_finished()
Pick the event listener if you need to handle multiple joins or react immediately; use
wait_for_participant()
if you want to pause until the first participant arrives. Want the snippet tailored to your existing code (e.g., where you start the session or what
your_custom_function
does)? Sources: Job lifecycle | LiveKit docs | Building an Automated IVR Menu Caller | LiveKit Docs
o
i want to run the function when the user answers the phone, not when their phone starts ringing
t
To run your function when the user actually answers (call is connected), detect when the remote participant becomes connected with active media rather than just when ringing or when a participant object appears. Two reliable approaches in Python: 1) Listen for participant connection + check their published audio track (react when media appears)
Copy code
@server.rtc_session()
async def my_agent(ctx: JobContext):
    session = AgentSession(...)

    @ctx.room.on("participant_connected")
    def _on_join(participant):
        # subscribe to track published events for this participant
        @participant.on("track_published")
        def _on_track_published(track_publication):
            if track_publication.kind == "audio":
                asyncio.create_task(your_custom_function(participant))

    await session.start(room=ctx.room, agent=MyAgent())
    await session.wait_until_finished()
2) Wait for the participant to be connected AND have an active subscribed audio track (blocking style)
Copy code
@server.rtc_session()
async def my_agent(ctx: JobContext):
    session = AgentSession(...)
    await session.start(room=ctx.room, agent=MyAgent())

    # wait for first participant
    participant = await ctx.wait_for_participant()

    # wait until participant publishes an audio track (call answered / audio active)
    while True:
        for pub in participant.tracks:
            if pub.kind == "audio" and pub.is_subscribed:
                await your_custom_function(participant)
                return
        await asyncio.sleep(0.2)  # short poll
Notes: • A participant object can exist while the phone is ringing; the presence of an active audio track (or
track_published
with audio) is the practical indicator the call was answered. • Use the event listener approach to avoid polling and to handle multiple joins. • If you use SIP outbound with
wait_until_answered=True
when creating the SIP participant, the session will only proceed after answer — you can then run your greeting immediately after
session.start()
. Would you like a version tailored to your SIP flow or to integrate with `session.generate_reply()`/`session.say()` for the greeting?