can i configure my room events payload to contain ...
# ask-ai
c
can i configure my room events payload to contain a certain key so that I can map them to my conversations?
t
Thanks for reaching out, Subham. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Room event webhook payloads don’t support adding custom keys directly, but don’t worry—you can still link them to conversations using a few handy methods: • Room Metadata: You can add custom key-value data to a room by using the CreateRoom or UpdateRoomMetadata API. Later on, you can easily retrieve this metadata through the room name or ID that comes with the webhook payloads. • SIP Dispatch Rule Attributes: If you’re working with SIP integrations, you can include custom attributes right within participant attributes using dispatch rules. • Access Token roomConfig: Another great option is embedding metadata in access tokens, which helps trigger automated actions or metadata handling when the room starts. These options should help you connect room events with conversations smoothly. If you’d like, I’m here to walk you through the detailed steps for any of these methods—just let me know!
c
how to add room metadata? this is my current code,
Copy code
session_started = asyncio.create_task(
        session.start(
            agent=agent,
            room=ctx.room,
            room_input_options=RoomInputOptions(
                # LiveKit Cloud enhanced noise cancellation
                # - If self-hosting, omit this parameter
                # - For telephony applications, use `BVCTelephony` for best results
                noise_cancellation=noise_cancellation.BVCTelephony(),
            ),
        )
    )
    try:
        await ctx.api.sip.create_sip_participant(
            api.CreateSIPParticipantRequest(
                room_name=ctx.room.name,
                sip_trunk_id=os.getenv("SIP_OUTBOUND_TRUNK_ID"),
                sip_call_to=phone_number,
                participant_identity=participant_identity,
                wait_until_answered=True,
            )
        )

        await session_started
        participant = await ctx.wait_for_participant(identity=participant_identity)
        <http://logger.info|logger.info>(f"participant joined: {participant.identity}")

        agent.set_participant(participant)
        # await lkapi.aclose()
        
    except Exception as e:
        logger.error(f"Failed to create SIP participant: {e}")
        ctx.shutdown()
        # await lkapi.aclose()
        return
t
To add room metadata in LiveKit using Python, you have two friendly options: setting it right when you create a room or updating it later for an existing room. Let me walk you through both ways: • Set Metadata When Creating a Room:
Copy code
from livekit.api import LiveKitAPI, CreateRoomRequest

lkapi = LiveKitAPI()

# Create a room with metadata
room = await lkapi.room.create_room(
    CreateRoomRequest(
        name="my-room",
        metadata='{"room_type": "webinar", "host": "user123"}'  # JSON string or any string data
    )
)
Update Metadata for an Existing Room:
Copy code
from livekit.api import LiveKitAPI, UpdateRoomMetadataRequest

lkapi = LiveKitAPI()

# Update room metadata
updated_room = await lkapi.room.update_room_metadata(
    UpdateRoomMetadataRequest(
        room="my-room",
        metadata='{"status": "active", "phase": "started"}'
    )
)
If you’d like, I’m here to help you integrate this smoothly into your existing code—just let me know! Sources: livekit-protocol/livekit/protocol/room.pyi | Docs::Home | Docs::Home
To add room metadata in LiveKit using Python, you have two friendly options: either set it right when you create a room or update it later for an existing room. Here’s a simple guide to help you through it: • Set Metadata When Creating a Room:
Copy code
from livekit.api import LiveKitAPI, CreateRoomRequest

lkapi = LiveKitAPI()

# Create a room with metadata
room = await lkapi.room.create_room(
    CreateRoomRequest(
        name="my-room",
        metadata='{"room_type": "webinar", "host": "user123"}'  # JSON string or any string data
    )
)
Update Metadata for an Existing Room:
Copy code
from livekit.api import LiveKitAPI, UpdateRoomMetadataRequest

lkapi = LiveKitAPI()

# Update room metadata
updated_room = await lkapi.room.update_room_metadata(
    UpdateRoomMetadataRequest(
        room="my-room",
        metadata='{"status": "active", "phase": "started"}'
    )
)
If you’d like, I’m here to help you smoothly integrate this into your current code—just let me know!
c
I want it to say room name along with room id, that's all I want
t
To include both the room name and room ID in the metadata, you can easily set the metadata field to include these values as a JSON string when creating or updating the room. Here’s a helpful example tailored for your situation: • Set Metadata When Creating a Room:
Copy code
from livekit.api import LiveKitAPI, CreateRoomRequest

lkapi = LiveKitAPI()

# Create a room with metadata
room = await lkapi.room.create_room(
    CreateRoomRequest(
        name="my-room",
        metadata='{\"room_name\": \"my-room\", \"room_id\": \"12345\"}'
    )
)
Update Metadata for an Existing Room:
Copy code
from livekit.api import LiveKitAPI, UpdateRoomMetadataRequest

lkapi = LiveKitAPI()

# Update room metadata
updated_room = await lkapi.room.update_room_metadata(
    UpdateRoomMetadataRequest(
        room="my-room",
        metadata='{\"room_name\": \"my-room\", \"room_id\": \"12345\"}'
    )
)
This approach will make sure your metadata includes both the room name and room ID. If you have any questions or need a hand with anything else, please don’t hesitate to reach out—I’m here to help!
c
can i make any changes in the current code to implement it?
Copy code
session_started = asyncio.create_task(
        session.start(
            agent=agent,
            room=ctx.room,
            room_input_options=RoomInputOptions(
                # LiveKit Cloud enhanced noise cancellation
                # - If self-hosting, omit this parameter
                # - For telephony applications, use `BVCTelephony` for best results
                noise_cancellation=noise_cancellation.BVCTelephony(),
            ),
        )
    )
    try:
        await ctx.api.sip.create_sip_participant(
            api.CreateSIPParticipantRequest(
                room_name=ctx.room.name,
                sip_trunk_id=os.getenv("SIP_OUTBOUND_TRUNK_ID"),
                sip_call_to=phone_number,
                participant_identity=participant_identity,
                wait_until_answered=True,
            )
        )

        await session_started
        participant = await ctx.wait_for_participant(identity=participant_identity)
        <http://logger.info|logger.info>(f"participant joined: {participant.identity}")

        agent.set_participant(participant)
        # await lkapi.aclose()
        
    except Exception as e:
        logger.error(f"Failed to create SIP participant: {e}")
        ctx.shutdown()
        # await lkapi.aclose()
        return
t
To include the room name and room ID in the metadata, you’ll want to adjust the room creation process a bit. From what I see in your code, it looks like the room is being created elsewhere already. No worries though—you can update the metadata for the room after it’s created by using the LiveKit API. Here’s a simple example to help you with that:
Copy code
from livekit.api import LiveKitAPI, UpdateRoomMetadataRequest

lkapi = LiveKitAPI()

# Update room metadata
await lkapi.room.update_room_metadata(
    UpdateRoomMetadataRequest(
        room=ctx.room.name,  # Use the room name from your context
        metadata='{\"room_name\": \"' + ctx.room.name + '\", \"room_id\": \"' + ctx.room.id + '\"}'
    )
)
This example assumes you have access to the room name (
ctx.room.name
) and room ID (
ctx.room.id
) in your context. If you run into any questions or need a hand with anything else, just let me know—I’m here to help!
c
can I use an api instead at the end of the call to fetch all the room events instead of waiting for the webhook?
t
Yes, absolutely! You can use the LiveKit client SDKs to fetch all room events in real-time, which is a great alternative to relying solely on webhooks. When you connect to a room using the SDK, you’ll be able to subscribe to important events like participants joining, tracks being published, and much more. This method works really well if your application is part of the room session and needs to handle events directly. If you'd like, I’m here to help guide you through the implementation with any specific SDK or programming language you’re working with—just let me know! Sources: Docs::Home | examples/basic_room_dispatcher/src/main.rs | packages/livekit-rtc/src/proto/room_pb.ts | livekit-rtc/livekit/rtc/room.py | Webhooks | LiveKit Docs
c
i am using python, can you give me an example of the same?
t
Here’s a friendly example to help you fetch and handle room events in LiveKit using the Python SDK:
Copy code
from livekit import rtc
import asyncio
import logging

async def main():
    logging.basicConfig(level=<http://logging.INFO|logging.INFO>)
    room = rtc.Room()

    # Event: A new participant joins the room
    @room.on("participant_connected")
    def on_participant_connected(participant: rtc.RemoteParticipant):
        <http://logging.info|logging.info>(f"Participant connected: {participant.identity}")

    # Event: A participant leaves the room
    @room.on("participant_disconnected")
    def on_participant_disconnected(participant: rtc.RemoteParticipant):
        <http://logging.info|logging.info>(f"Participant disconnected: {participant.identity}")

    # Event: A remote participant publishes a track
    @room.on("track_published")
    def on_track_published(publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant):
        <http://logging.info|logging.info>(f"Track published: {publication.sid} by {participant.identity}")

    # Event: Room metadata is updated
    @room.on("room_metadata_changed")
    def on_room_metadata_changed(old_metadata: str, new_metadata: str):
        <http://logging.info|logging.info>(f"Room metadata changed: {old_metadata} -> {new_metadata}")

    # Finally, connect to the room using a URL and token
    await room.connect("<wss://your-livekit-server>", "your-access-token")
    <http://logging.info|logging.info>(f"Connected to room: {room.name}")

    # Keep the application running to listen for events
    await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())
This example walks you through listening for important events like participant connections, track publications, and metadata updates. Just swap out
"<wss://your-livekit-server>"
and
"your-access-token"
with your own LiveKit server URL and access token. If you'd like, I’m here to help you tailor this example to fit your specific needs—just let me know! Sources: examples/rpc.py
Here’s a friendly example to help you fetch and handle room events in LiveKit using the Python SDK:
Copy code
from livekit import rtc
import asyncio
import logging

async def main():
    logging.basicConfig(level=<http://logging.INFO|logging.INFO>)
    room = rtc.Room()

    # Event: A new participant joins the room
    @room.on("participant_connected")
    def on_participant_connected(participant: rtc.RemoteParticipant):
        <http://logging.info|logging.info>(f"Participant connected: {participant.identity}")

    # Event: A participant leaves the room
    @room.on("participant_disconnected")
    def on_participant_disconnected(participant: rtc.RemoteParticipant):
        <http://logging.info|logging.info>(f"Participant disconnected: {participant.identity}")

    # Event: A remote participant publishes a track
    @room.on("track_published")
    def on_track_published(publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant):
        <http://logging.info|logging.info>(f"Track published: {publication.sid} by {participant.identity}")

    # Event: Room metadata is updated
    @room.on("room_metadata_changed")
    def on_room_metadata_changed(old_metadata: str, new_metadata: str):
        <http://logging.info|logging.info>(f"Room metadata changed: {old_metadata} -> {new_metadata}")

    # Finally, connect to the room using a URL and token
    await room.connect("<wss://your-livekit-server>", "your-access-token")
    <http://logging.info|logging.info>(f"Connected to room: {room.name}")

    # Keep the application running to listen for events
    await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())
This example shows you how to listen for important events like participants joining or leaving, track publications, and changes to room metadata. Just remember to swap out
"<wss://your-livekit-server>"
and
"your-access-token"
with your actual LiveKit server URL and access token. If you’d like any help tailoring this example to fit your needs, feel free to ask — I’m here to help!
c
I don't need the sdk, i just want an api that can help me fetch all the room details after the room is complete?
t
LiveKit doesn’t currently offer an API to fetch room details once a room has ended. The APIs available, like
ListRooms
and
ListParticipants
, focus on active rooms only. To keep track of room details after the session is complete, it’s a good idea to save the important data externally during or before the room is in use. If you’d like, I’m here to help guide you through setting this up—just let me know! Sources: packages/livekit-server-sdk/src/RoomServiceClient.ts | protobufs/livekit_room.proto
LiveKit doesn’t offer an API to fetch room details once a room has ended. The APIs available, like
ListRooms
and
ListParticipants
, only show information about rooms that are currently active. To keep track of room details after the session is over, it’s best to save the important data externally while the room is still active or even before it starts. If you’d like, I’m here to help guide you through setting that up—just let me know!
c
Copy code
"room": ctx.room.name,
can i also get the room_id for the same?
t
You can easily retrieve the room ID (SID) in LiveKit by using one of these helpful methods: • Client-Side (Real-Time): If you're working with the Python SDK and already connected to the room, you can get the room ID asynchronously through the
sid
property like this:
Copy code
from livekit import rtc

async def main():
    room = rtc.Room()
    await room.connect(URL, TOKEN)
    room_sid = await room.sid  # Retrieve the room ID
    print(f"Room SID: {room_sid}")

asyncio.run(main())
Server-Side (Management API): If you want to fetch room details from the server, the
list_rooms
method will do the trick:
Copy code
from livekit import api
import asyncio

async def main():
    lkapi = api.LiveKitAPI("<https://my-project.livekit.cloud>")
    rooms = await lkapi.room.list_rooms(api.ListRoomsRequest())
    for room in rooms.rooms:
        print(f"Room SID: {room.sid}")
        print(f"Room name: {room.name}")
    await lkapi.aclose()

asyncio.run(main())
If you have any questions or need a hand with implementing this, just let me know—I’m here to help! Sources: livekit-rtc/livekit/rtc/_proto/room_pb2.pyi
You can easily find the room ID (SID) in LiveKit by using one of these friendly methods: • Client-side (real-time): If you're working with the Python SDK and are already connected to the room, you can simply get the room's SID using the
sid
property like this:
Copy code
room_sid = await room.sid
print(f"Room SID: {room_sid}")
Server-side (management API): If you want to fetch room details from the server, just use the
list_rooms
method:
Copy code
rooms = await lkapi.room.list_rooms(api.ListRoomsRequest())
for room in rooms.rooms:
    print(f"Room SID: {room.sid}")
If you’d like, I’m here to help you walk through setting up either of these methods—just let me know!
c
what is the output of await lkapi.agent_dispatch.create_dispatch( api.CreateAgentDispatchRequest(_agent_name_=agent_name, room=room_name, metadata=metadata_json) ) can it provide me the room_id?
t
The output of CreateAgentDispatchRequest doesn’t include a room_id, but that’s totally okay! Instead, it gives you an AgentDispatch object which includes: • id: A unique identifier for the dispatch • agent_name: The name of the dispatched agent • room: The room name (just like you provided in the request) • metadata: Optional metadata passed to the agent • state: The current state of the dispatch So, the room field you see in the response is the room name itself, not a room_id. If anything feels unclear or if you want to dive deeper, please don’t hesitate to reach out—I’m here to help! Sources: rpc/agent_dispatch.pb.go | packages/livekit-server-sdk/src/AgentDispatchClient.ts | Dispatching agents | LiveKit Docs
The output of CreateAgentDispatchRequest doesn’t include a room_id, but no worries! Instead, it gives you an AgentDispatch object that includes: • id: A unique identifier for the dispatch • agent_name: The name of the dispatched agent • room: The room name (just like you provided in the request) • metadata: Any optional metadata you passed to the agent • state: The current state of the dispatch Just to clarify, the room field in the response contains the room name, not a room_id. If you have any questions or want me to walk you through this further, I’m here to help!
c
can i map room_id to room_name or room_name to room_id?
t
Absolutely, you can map room_id (also called sid) to room_name and vice versa in LiveKit. Both of these are part of the same room object and come together whenever you retrieve room details through the APIs or SDKs. For instance, using the ListRooms API, you’ll get a list of rooms where each room object includes both sid and name. This makes it easy to look up either room_id or room_name in both directions. If you’d like, I’m here to help you with the implementation—just let me know! Sources: Flutter SDK | livekit/livekit_composite | DeepWiki | livekit/livekit_room.pb.go | Sources/LiveKit/Core/Room.swift | src/room/Room.ts
Absolutely, you can definitely map room_id (also known as sid) to room_name and the other way around in LiveKit. Both of these fields are part of the same room object, and you'll always find them together when you fetch room details using the APIs or SDKs. For instance, using the ListRooms API, you can get a list of rooms where each room object includes both sid and name. This makes it easy to look up information in either direction between room_id and room_name. If you'd like, I’m here to help you with implementing this—just let me know!
c
yes give me the implemenation
t
Here’s a friendly example to help you map room_id (sid) to room_name and the other way around using the LiveKit API in Python: