Can you show me a sample code in Python on how to ...
# ask-ai
p
Can you show me a sample code in Python on how to connect to a livekit worker running locally on my machine?
t
Thanks for reaching out, Mario. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for reaching out! To help you better, could you please let me know if you're trying to connect to a LiveKit server to manage rooms and participants, or if you're aiming to interact with a specific LiveKit service? Also, if you already have the LiveKit server running locally, could you share its address and port? I'm here to assist you every step of the way!
p
I want to manage rooms and participants
t
I'd love to help you get started with connecting to a LiveKit server! Here's a friendly Python code example that shows how to manage rooms and participants:
Copy code
from livekit import api
import asyncio

async def main():
    # Initialize the LiveKit API client
    # Uses LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET from environment variables
    lkapi = api.LiveKitAPI()

    try:
        # Create a new room
        room_info = await lkapi.room.create_room(
            api.CreateRoomRequest(name="my-room"),
        )
        print(f"Created room: {room_info.name}")

        # List all active rooms
        rooms_response = await lkapi.room.list_rooms(api.ListRoomsRequest())
        print("Active rooms:")
        for room in rooms_response.rooms:
            print(f" - {room.name}")

        # List participants in a specific room
        participants_response = await lkapi.room.list_participants(
            api.ListParticipantsRequest(room="my-room")
        )
        print("Participants in 'my-room':")
        for participant in participants_response.participants:
            print(f" - Identity: {participant.identity}, State: {participant.state}")

        # Delete a room
        await lkapi.room.delete_room(api.DeleteRoomRequest(room="my-room"))
        print("Deleted room 'my-room'")

    finally:
        # Close the API client
        await lkapi.aclose()

if __name__ == "__main__":
    asyncio.run(main())
This example gently walks you through: • Initializing the LiveKit API client • Creating a room • Listing all rooms • Listing participants in a room • Deleting a room Just a quick note: make sure you have the environment variables
LIVEKIT_URL
,
LIVEKIT_API_KEY
, and
LIVEKIT_API_SECRET
set up before running this. If you have any questions or need a hand with anything else, please don’t hesitate to ask — I’m here to help! Sources: Managing rooms | LiveKit Docs | Managing participants | LiveKit Docs