fast-ram-26210
10/31/2025, 11:58 AM"""
LiveKit Video + Voice Agent – (livekit-agents~=1.0)
"""
import asyncio
import logging
import os
from typing import Optional
from dotenv import load_dotenv
from livekit import agents, rtc
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import AgentSession
from livekit.plugins import deepgram, openai, silero
from livekit import api
# --------------------------------------------------------------------------- #
# Config & Logging
# --------------------------------------------------------------------------- #
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
)
log = logging.getLogger("video-voice-agent")
LIVEKIT_URL: Optional[str] = os.getenv("LIVEKIT_URL")
LIVEKIT_API_KEY: Optional[str] = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET: Optional[str] = os.getenv("LIVEKIT_API_SECRET")
OPENAI_API_KEY: Optional[str] = os.getenv("OPENAI_API_KEY")
def _check_env() -> None:
missing = [k for k, v in {
"LIVEKIT_URL": LIVEKIT_URL,
"LIVEKIT_API_KEY": LIVEKIT_API_KEY,
"LIVEKIT_API_SECRET": LIVEKIT_API_SECRET,
"OPENAI_API_KEY": OPENAI_API_KEY,
}.items() if not v]
if missing:
log.error("Missing env vars: %s", ", ".join(missing))
raise SystemExit(1)
# --------------------------------------------------------------------------- #
# Agent – Vision + Voice
# --------------------------------------------------------------------------- #
class VideoVoiceAgent(agents.voice.Agent):
def __init__(self) -> None:
super().__init__(
instructions=(
"You are a friendly AI in a video call. "
"You can SEE and HEAR the user. "
"Respond naturally in English, keep replies short. "
"Acknowledge what you see if relevant."
)
)
async def on_start(self, session: AgentSession) -> None:
await session.say(
"Hi! I can see and hear you. How can I help you today?",
allow_interruptions=True,
)
async def on_video_frame(self, frame: rtc.VideoFrame, session: AgentSession) -> None:
image = agents.llm.ImageContent(image=frame)
session._chat_ctx.add_message(
role="user",
content=[image]
)
await session.generate_reply()
async def start_recording(room_name: str) -> Optional[str]:
"""
Start recording the room using LiveKit Egress API.
Returns the egress_id if successful, None otherwise.
"""
try:
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET)
egress_client = lkapi.egress
# Room composite recording (records entire room with all participants)
room_composite = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="grid", # or "speaker" for speaker view
audio_only=False,
video_only=False,
custom_base_url="", # optional: custom template URL
file=api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{room_name}-{asyncio.get_event_loop().time()}.mp4",
)
)
egress = await egress_client.start_room_composite_egress(room_composite)
log.info("Recording started – egress_id: %s", egress.egress_id)
return egress.egress_id
except Exception as e:
log.error("Faileddddddddddddd to startttttttttttttt recordinggggggggggg--------------------------------: %s", e)
return None
async def stop_recording(egress_id: str) -> None:
"""Stop the recording."""
try:
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET)
egress_client = lkapi.egress
await egress_client.stop_egress(egress_id)
log.info("Recording stopped – egress_id: %s", egress_id)
except Exception as e:
log.error("Failed to stop recording: %s", e)
# --------------------------------------------------------------------------- #
# Entrypoint
# --------------------------------------------------------------------------- #
async def entrypoint(ctx: JobContext) -> None:
log.info("Job started – room: %s", ctx.room.name)
# 1. Connect
await ctx.connect()
log.info("Connected to room")
egress_id = await start_recording(ctx.room.name)
# 2. Wait for participant
participant = await ctx.wait_for_participant()
log.info("Participant joined: %s", participant.identity)
# 3. Create AgentSession – NO turn_detector, NO participant in start()
session = AgentSession(
vad=silero.VAD.load(),
stt=openai.STT(model="gpt-4o-transcribe"),
llm=openai.LLM(model="gpt-4o", temperature=0.7),
tts=openai.TTS(voice="alloy"),
)
# 4. Start agent – NO participant=
agent = VideoVoiceAgent()
await session.start(
agent=agent,
room=ctx.room,
# participant=participant, ← REMOVED
)
log.info("AgentSession started")
# 5. Wait for video track
video_stream: Optional[rtc.VideoStream] = None
async def handle_track(track, publication, participant):
nonlocal video_stream
if track.kind == rtc.TrackKind.KIND_VIDEO:
log.info("Video track subscribed: %s", track.sid)
video_stream = rtc.VideoStream(track)
async for event in video_stream:
await agent.on_video_frame(event.frame, session)
def on_track_subscribed(track, publication, participant):
asyncio.create_task(handle_track(track, publication, participant))
ctx.room.on("track_subscribed", on_track_subscribed)
# 6. Keep alive
try:
await ctx.room
except asyncio.CancelledError:
log.info("Job cancelled")
finally:
# Stop recording when room closes
if egress_id:
await stop_recording(egress_id)
log.info("Room closed.")
# --------------------------------------------------------------------------- #
# Run
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
_check_env()
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
ws_url=LIVEKIT_URL,
api_key=LIVEKIT_API_KEY,
api_secret=LIVEKIT_API_SECRET,
)
)tall-airline-16756
10/31/2025, 11:58 AMtall-airline-16756
10/31/2025, 11:59 AMRoomCompositeEgressRequest to specify your recording details, like the room name, layout, encoding options, and where you want the output saved.
• Choose Output Storage: You can save your recordings to cloud storage options such as Google Cloud, Amazon S3, or Azure Blob Storage. Just make sure you have the right credentials and bucket name ready.
• Start the Egress Recording: With LiveKitAPI, call start_room_composite_egress() using your request. This will kick off the recording as soon as the agent joins the room and will stop automatically when everyone leaves.
Since your script already has a start_recording function using RoomCompositeEgressRequest, here are a few friendly reminders to ensure everything runs smoothly:
1. Double-check that your LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET are all correctly set with valid credentials.
2. Make sure the file parameter in RoomCompositeEgressRequest points to the right file path or cloud storage configuration.
3. Don’t forget to handle exceptions carefully—this will help you catch and fix any hiccups during recording.
If you want to dive deeper, the LiveKit documentation on Egress and session recording examples are great resources to explore. Feel free to reach out if you have any questions along the way—I’m here to help!
Sources: livekit-api/livekit/api/egress_service.py | Session recording and transcripts | LiveKit Docs | docs/index.yaml | Custom recording templates | LiveKit docsfast-ram-26210
10/31/2025, 12:02 PMtall-airline-16756
10/31/2025, 12:02 PMimport asyncio
import logging
import os
from livekit import api
# Configure logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("local-recording")
# Environment variables for LiveKit API
LIVEKIT_URL = os.getenv("LIVEKIT_URL")
LIVEKIT_API_KEY = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.getenv("LIVEKIT_API_SECRET")
async def start_recording(room_name: str):
"""
Start recording the room and save it locally.
"""
try:
# Initialize LiveKit API client
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
# Configure RoomCompositeEgressRequest for local storage
room_composite = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="grid", # Options: "grid" or "speaker"
audio_only=False,
video_only=False,
file=api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{room_name}-{int(asyncio.get_event_loop().time())}.mp4"
)
)
# Start recording
egress = await lkapi.egress.start_room_composite_egress(room_composite)
log.info("Recording started – egress_id: %s", egress.egress_id)
return egress.egress_id
except Exception as e:
log.error("Failed to start recording: %s", e)
return None
async def stop_recording(egress_id: str):
"""
Stop the recording.
"""
try:
# Initialize LiveKit API client
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
# Stop the recording
await lkapi.egress.stop_egress(egress_id)
log.info("Recording stopped – egress_id: %s", egress_id)
except Exception as e:
log.error("Failed to stop recording: %s", e)
# Example usage
if __name__ == "__main__":
room_name = "example-room" # Replace with your room name
async def main():
egress_id = await start_recording(room_name)
if egress_id:
log.info("Recording in progress...")
await asyncio.sleep(10) # Simulate recording duration
await stop_recording(egress_id)
asyncio.run(main())
Just a couple of friendly reminders to ensure everything runs smoothly:
• Be sure to create a recordings directory in the same location as your script. This is where your MP4 files will be saved.
• Don’t forget to set your environment variables LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET with your LiveKit credentials.
This script will then save your recording as an MP4 file inside that recordings folder on your local system. If you have any questions or need further help, I’m here for you!fast-ram-26210
10/31/2025, 12:07 PM"""
LiveKit Video + Voice Agent – 100% Working (livekit-agents~=1.0)
- No participant= in start()
- No turn_detector
- No cartesia key
- gpt-4o vision
"""
import asyncio
import logging
import os
from typing import Optional
from dotenv import load_dotenv
from livekit import agents, rtc
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import AgentSession
from livekit.plugins import deepgram, openai, silero
from livekit import api
# --------------------------------------------------------------------------- #
# Config & Logging
# --------------------------------------------------------------------------- #
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
)
log = logging.getLogger("video-voice-agent")
LIVEKIT_URL: Optional[str] = os.getenv("LIVEKIT_URL")
LIVEKIT_API_KEY: Optional[str] = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET: Optional[str] = os.getenv("LIVEKIT_API_SECRET")
OPENAI_API_KEY: Optional[str] = os.getenv("OPENAI_API_KEY")
def _check_env() -> None:
missing = [k for k, v in {
"LIVEKIT_URL": LIVEKIT_URL,
"LIVEKIT_API_KEY": LIVEKIT_API_KEY,
"LIVEKIT_API_SECRET": LIVEKIT_API_SECRET,
"OPENAI_API_KEY": OPENAI_API_KEY,
}.items() if not v]
if missing:
log.error("Missing env vars: %s", ", ".join(missing))
raise SystemExit(1)
# --------------------------------------------------------------------------- #
# Agent – Vision + Voice
# --------------------------------------------------------------------------- #
class VideoVoiceAgent(agents.voice.Agent):
def __init__(self) -> None:
super().__init__(
instructions=(
"You are a friendly AI in a video call. "
"You can SEE and HEAR the user. "
"Respond naturally in English, keep replies short. "
"Acknowledge what you see if relevant."
)
)
async def on_start(self, session: AgentSession) -> None:
await session.say(
"Hi! I can see and hear you. How can I help you today?",
allow_interruptions=True,
)
async def on_video_frame(self, frame: rtc.VideoFrame, session: AgentSession) -> None:
image = agents.llm.ImageContent(image=frame)
session._chat_ctx.add_message(
role="user",
content=[image]
)
await session.generate_reply()
async def start_recording(room_name: str):
"""
Start recording the room and save it locally.
"""
try:
# Initialize LiveKit API client
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
# Configure RoomCompositeEgressRequest for local storage
room_composite = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="grid", # Options: "grid" or "speaker"
audio_only=False,
video_only=False,
file=api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{room_name}-{int(asyncio.get_event_loop().time())}.mp4"
)
)
# Start recording
egress = await lkapi.egress.start_room_composite_egress(room_composite)
log.info("Recording started – egress_id: %s", egress.egress_id)
return egress.egress_id
except Exception as e:
log.error("Failed to start recording: %s", e)
return None
async def stop_recording(egress_id: str):
"""
Stop the recording.
"""
try:
# Initialize LiveKit API client
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
# Stop the recording
await lkapi.egress.stop_egress(egress_id)
log.info("Recording stopped – egress_id: %s", egress_id)
except Exception as e:
log.error("Failed to stop recording: %s", e)
# --------------------------------------------------------------------------- #
# Entrypoint
# --------------------------------------------------------------------------- #
async def entrypoint(ctx: JobContext) -> None:
log.info("Job started – room: %s", ctx.room.name)
# 1. Connect
await ctx.connect()
log.info("Connected to room")
egress_id = await start_recording(ctx.room.name)
# 2. Wait for participant
participant = await ctx.wait_for_participant()
log.info("Participant joined: %s", participant.identity)
# 3. Create AgentSession – NO turn_detector, NO participant in start()
session = AgentSession(
vad=silero.VAD.load(),
stt=openai.STT(model="gpt-4o-transcribe"),
llm=openai.LLM(model="gpt-4o", temperature=0.7),
tts=openai.TTS(voice="alloy"),
)
# 4. Start agent – NO participant=
agent = VideoVoiceAgent()
await session.start(
agent=agent,
room=ctx.room,
# participant=participant, ← REMOVED
)
log.info("AgentSession started")
# 5. Wait for video track
video_stream: Optional[rtc.VideoStream] = None
async def handle_track(track, publication, participant):
nonlocal video_stream
if track.kind == rtc.TrackKind.KIND_VIDEO:
log.info("Video track subscribed: %s", track.sid)
video_stream = rtc.VideoStream(track)
async for event in video_stream:
await agent.on_video_frame(event.frame, session)
def on_track_subscribed(track, publication, participant):
asyncio.create_task(handle_track(track, publication, participant))
ctx.room.on("track_subscribed", on_track_subscribed)
# 6. Keep alive
try:
await ctx.room
except asyncio.CancelledError:
log.info("Job cancelled")
finally:
# Stop recording when room closes
if egress_id:
await asyncio.sleep(10)
await stop_recording(egress_id)
log.info("Room closed.")
# --------------------------------------------------------------------------- #
# Run
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
_check_env()
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
ws_url=LIVEKIT_URL,
api_key=LIVEKIT_API_KEY,
api_secret=LIVEKIT_API_SECRET,
)
)tall-airline-16756
10/31/2025, 12:08 PMawait ctx.room to keep the room alive might seem like a straightforward approach, but in the LiveKit Python SDK, this isn't quite the right pattern. The ctx.room object isn’t designed to be awaited directly since it doesn’t support coroutine behavior. No worries though — there are some effective asyncio patterns you can use to manage the room lifecycle smoothly.
Here are some friendly recommendations to guide you:
• Using `asyncio.wait()`: This lets you wait for specific events, like when a participant disconnects or when a shutdown signal happens. For example:
room_empty_future = asyncio.get_running_loop().create_future()
def _on_participant_disconnected(_: rtc.Participant, fut=room_empty_future):
if len(ctx.room.remote_participants) == 0 and not fut.done():
fut.set_result(None)
ctx.room.on("participant_disconnected", _on_participant_disconnected)
try:
await asyncio.wait([shutdown_future, room_empty_future], return_when=asyncio.FIRST_COMPLETED)
finally:
ctx.room.off("participant_disconnected", _on_participant_disconnected)
• Using `loop.run_forever()`: For applications that need to run continuously, it’s great to use the event loop to keep things alive and handle cleanup properly.
loop = asyncio.get_event_loop()
room = rtc.Room(loop=loop)
async def cleanup():
await room.disconnect()
loop.stop()
asyncio.ensure_future(main(room))
for signal in [SIGINT, SIGTERM]:
loop.add_signal_handler(signal, lambda: asyncio.ensure_future(cleanup()))
try:
loop.run_forever()
finally:
loop.close()
• Handling `asyncio.CancelledError`: It’s important to handle task cancellation gracefully during cleanup, like this:
player_task.cancel()
try:
await player_task
except asyncio.CancelledError:
pass
These approaches will help you manage the room and clean up resources effectively. If you’d like, I’m here to walk you through any part of this or provide more examples — just let me know!
Sources: livekit-agents/livekit/agents/voice/agent_session.py | examples/multiple_connections.py | How to detect and handle silence during callsfast-ram-26210
10/31/2025, 12:25 PMtall-airline-16756
10/31/2025, 12:26 PMimport asyncio
import logging
import os
from typing import Optional
from dotenv import load_dotenv
from livekit import agents, rtc, api
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import AgentSession
from livekit.plugins import openai, silero
# --------------------------------------------------------------------------- #
# Config & Logging
# --------------------------------------------------------------------------- #
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
)
log = logging.getLogger("video-ai-agent")
LIVEKIT_URL: Optional[str] = os.getenv("LIVEKIT_URL")
LIVEKIT_API_KEY: Optional[str] = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET: Optional[str] = os.getenv("LIVEKIT_API_SECRET")
# --------------------------------------------------------------------------- #
# Video AI Agent
# --------------------------------------------------------------------------- #
class VideoAIAgent(agents.voice.Agent):
def __init__(self) -> None:
super().__init__(
instructions=(
"You are a friendly AI in a video call. "
"You can SEE and HEAR the user. "
"Respond naturally in English, keep replies short. "
"Acknowledge what you see if relevant."
)
)
async def on_start(self, session: AgentSession) -> None:
await session.say(
"Hi! I can see and hear you. How can I help you today?",
allow_interruptions=True,
)
async def on_video_frame(self, frame: rtc.VideoFrame, session: AgentSession) -> None:
image = agents.llm.ImageContent(image=frame)
session._chat_ctx.add_message(
role="user",
content=[image]
)
await session.generate_reply()
# --------------------------------------------------------------------------- #
# Recording Functions
# --------------------------------------------------------------------------- #
async def start_recording(room_name: str) -> Optional[str]:
"""
Start recording the room and save it locally.
"""
try:
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
room_composite = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="grid", # Options: "grid" or "speaker"
audio_only=False,
video_only=False,
file=api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{room_name}-{int(asyncio.get_event_loop().time())}.mp4"
)
)
egress = await lkapi.egress.start_room_composite_egress(room_composite)
log.info("Recording started – egress_id: %s", egress.egress_id)
return egress.egress_id
except Exception as e:
log.error("Failed to start recording: %s", e)
return None
async def stop_recording(egress_id: str) -> None:
"""
Stop the recording.
"""
try:
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
await lkapi.egress.stop_egress(egress_id)
log.info("Recording stopped – egress_id: %s", egress_id)
except Exception as e:
log.error("Failed to stop recording: %s", e)
# --------------------------------------------------------------------------- #
# Entrypoint
# --------------------------------------------------------------------------- #
async def entrypoint(ctx: JobContext) -> None:
log.info("Job started – room: %s", ctx.room.name)
# 1. Connect
await ctx.connect()
log.info("Connected to room")
egress_id = await start_recording(ctx.room.name)
# 2. Wait for participant
participant = await ctx.wait_for_participant()
log.info("Participant joined: %s", participant.identity)
# 3. Create AgentSession
session = AgentSession(
vad=silero.VAD.load(),
stt=openai.STT(model="gpt-4o-transcribe"),
llm=openai.LLM(model="gpt-4o", temperature=0.7),
tts=openai.TTS(voice="alloy"),
)
# 4. Start agent
agent = VideoAIAgent()
await session.start(
agent=agent,
room=ctx.room,
)
log.info("AgentSession started")
# 5. Keep alive
try:
await asyncio.sleep(10) # Simulate session duration
except asyncio.CancelledError:
log.info("Job cancelled")
finally:
if egress_id:
await stop_recording(egress_id)
log.info("Room closed.")
# --------------------------------------------------------------------------- #
# Run
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
ws_url=LIVEKIT_URL,
api_key=LIVEKIT_API_KEY,
api_secret=LIVEKIT_API_SECRET,
)
)
Key Features:
• The agent can process video frames and respond intelligently using GPT-4.
• Session recording is implemented using the LiveKit Egress API, saving the video locally as an MP4 file.
• Just a quick note: please make sure you have a recordings directory in the same location as this script to store your recordings safely.
• Also, don’t forget to set the environment variables LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET with your LiveKit credentials.
If you have any questions or would like me to help with any modifications, please don’t hesitate to ask. I’m here to support you!fast-ram-26210
10/31/2025, 12:31 PMtall-airline-16756
10/31/2025, 12:31 PMstop_egress function as soon as the participant leaves.
• Or, you can delete the room after they leave, which will automatically end the recording.
Please feel free to reach out if you'd like some guidance on adding this to your script—I’m here to help!fast-ram-26210
10/31/2025, 12:32 PMtall-airline-16756
10/31/2025, 12:32 PMon("participant_disconnected") event to catch when someone leaves the room.
2. Stop the Recording: Once that event happens, call the stop_egress function with the egress ID to stop the recording.
Here’s a simple example to illustrate how this works:
async def entrypoint(ctx: JobContext) -> None:
log.info("Job started – room: %s", ctx.room.name)
# 1. Connect
await ctx.connect()
log.info("Connected to room")
egress_id = await start_recording(ctx.room.name)
# 2. Listen for participant disconnection
def on_participant_disconnected(participant):
log.info("Participant disconnected: %s", participant.identity)
if egress_id:
asyncio.create_task(stop_recording(egress_id))
ctx.room.on("participant_disconnected", on_participant_disconnected)
# 3. Keep the room alive
try:
await asyncio.sleep(10) # Simulate session duration
except asyncio.CancelledError:
log.info("Job cancelled")
finally:
if egress_id:
await stop_recording(egress_id)
log.info("Room closed.")
Just a few important things to keep in mind:
• Make sure to swap out start_recording and stop_recording with your own recording functions.
• The on("participant_disconnected") event is great for stopping the recording right when someone leaves.
• Don’t forget the cleanup in the finally block—it helps handle any unexpected errors or cancellations smoothly.
If you have any questions or want me to walk you through any part of this, just let me know—I’m here to help!fast-ram-26210
10/31/2025, 12:37 PMtall-airline-16756
10/31/2025, 12:38 PMfast-ram-26210
10/31/2025, 12:38 PMtall-airline-16756
10/31/2025, 12:39 PM{room_name}-{time}.mp4.
2. Use the LiveKit API: You can use the ListEgress API to find details about your completed recordings, including where they’re stored. Here’s an example:
list_egress_request = ListEgressRequest(room_name="your-room-name")
response = await egress_service.list_egress(list_egress_request)
for egress_info in response.egresses:
if egress_info.successful:
print("Recording URL:", egress_info.output_path)
1. Access Recordings Programmatically: From the EgressInfo response, you can get the file location and download it directly from your storage provider.
2. Check Local Recordings: If you’ve set up local storage in your script, your recordings will be saved in the folder you specified, like recordings/.
If you’d like, I’m here to guide you through setting up or accessing recordings from any specific storage provider. Just let me know how I can assist!
Sources: Session recording and transcripts | LiveKit Docs | livekit-api/livekit/api/egress_service.py | cmd/lk/replay.go | README.md | Composite and web recordings | LiveKit docsfast-ram-26210
10/31/2025, 12:42 PMimport asyncio
import logging
import os
from typing import Optional
from dotenv import load_dotenv
from livekit import agents, rtc, api
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import AgentSession
from livekit.plugins import openai, silero
# --------------------------------------------------------------------------- #
# Config & Logging
# --------------------------------------------------------------------------- #
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
)
log = logging.getLogger("video-ai-agent")
LIVEKIT_URL: Optional[str] = os.getenv("LIVEKIT_URL")
LIVEKIT_API_KEY: Optional[str] = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET: Optional[str] = os.getenv("LIVEKIT_API_SECRET")
# --------------------------------------------------------------------------- #
# Video AI Agent
# --------------------------------------------------------------------------- #
class VideoAIAgent(agents.voice.Agent):
def __init__(self) -> None:
super().__init__(
instructions=(
"You are a friendly AI in a video call. "
"You can SEE and HEAR the user. "
"Respond naturally in English, keep replies short. "
"Acknowledge what you see if relevant."
)
)
async def on_start(self, session: AgentSession) -> None:
await session.say(
"Hi! I can see and hear you. How can I help you today?",
allow_interruptions=True,
)
async def on_video_frame(self, frame: rtc.VideoFrame, session: AgentSession) -> None:
image = agents.llm.ImageContent(image=frame)
session._chat_ctx.add_message(
role="user",
content=[image]
)
await session.generate_reply()
# --------------------------------------------------------------------------- #
# Recording Functions
# --------------------------------------------------------------------------- #
async def start_recording(room_name: str) -> Optional[str]:
"""
Start recording the room and save it locally.
"""
try:
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
room_composite = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="grid", # Options: "grid" or "speaker"
audio_only=False,
video_only=False,
file=api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{room_name}-{int(asyncio.get_event_loop().time())}.mp4"
)
)
egress = await lkapi.egress.start_room_composite_egress(room_composite)
log.info("Recording started – egress_id: %s", egress.egress_id)
return egress.egress_id
except Exception as e:
log.error("Failed to start recording: %s", e)
return None
async def stop_recording(egress_id: str) -> None:
"""
Stop the recording.
"""
try:
lkapi = api.LiveKitAPI(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
)
await lkapi.egress.stop_egress(egress_id)
log.info("Recording stopped – egress_id: %s", egress_id)
except Exception as e:
log.error("Failed to stop recording: %s", e)
# --------------------------------------------------------------------------- #
# Entrypoint
# --------------------------------------------------------------------------- #
async def entrypoint(ctx: JobContext) -> None:
log.info("Job started – room: %s", ctx.room.name)
# 1. Connect
await ctx.connect()
log.info("Connected to room")
egress_id = await start_recording(ctx.room.name)
# 2. Wait for participant
participant = await ctx.wait_for_participant()
log.info("Participant joined: %s", participant.identity)
# 3. Create AgentSession
session = AgentSession(
vad=silero.VAD.load(),
stt=openai.STT(model="gpt-4o-transcribe"),
llm=openai.LLM(model="gpt-4o", temperature=0.7),
tts=openai.TTS(voice="alloy"),
)
# 4. Start agent
agent = VideoAIAgent()
await session.start(
agent=agent,
room=ctx.room,
)
log.info("AgentSession started")
# 5. Keep alive
try:
await asyncio.sleep(10) # Simulate session duration
except asyncio.CancelledError:
log.info("Job cancelled")
finally:
if egress_id:
await stop_recording(egress_id)
log.info("Room closed.")
# --------------------------------------------------------------------------- #
# Run
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
ws_url=LIVEKIT_URL,
api_key=LIVEKIT_API_KEY,
api_secret=LIVEKIT_API_SECRET,
)
)tall-airline-16756
10/31/2025, 12:43 PMstop_recording function using the egress ID. Here’s a friendly guide on how you can tweak your code:
1. Detect Manual Disconnect: Add a listener for the disconnect button or event in your application.
2. Stop Recording: Call the stop_recording function when the disconnect event is triggered.
Here’s an example modification to help you visualize it:
async def entrypoint(ctx: JobContext) -> None:
log.info("Job started – room: %s", ctx.room.name)
# 1. Connect
await ctx.connect()
log.info("Connected to room")
egress_id = await start_recording(ctx.room.name)
# 2. Wait for participant
participant = await ctx.wait_for_participant()
log.info("Participant joined: %s", participant.identity)
# 3. Create AgentSession
session = AgentSession(
vad=silero.VAD.load(),
stt=openai.STT(model="gpt-4o-transcribe"),
llm=openai.LLM(model="gpt-4o", temperature=0.7),
tts=openai.TTS(voice="alloy"),
)
# 4. Start agent
agent = VideoAIAgent()
await session.start(
agent=agent,
room=ctx.room,
)
log.info("AgentSession started")
# 5. Handle manual disconnect
def on_disconnect():
log.info("Manual disconnect triggered")
if egress_id:
asyncio.create_task(stop_recording(egress_id))
# Simulate disconnect button (replace with actual event listener in your app)
ctx.room.on("disconnect_button_clicked", on_disconnect)
# 6. Keep alive
try:
await asyncio.sleep(10) # Simulate session duration
except asyncio.CancelledError:
log.info("Job cancelled")
finally:
if egress_id:
await stop_recording(egress_id)
log.info("Room closed.")
Some helpful tips:
• Make sure to replace disconnect_button_clicked with the actual event or signal your app’s UI uses.
• Double-check that the on_disconnect function gets called when the disconnect button is pressed.
• Give it a test run to confirm the recording stops just as you expect.
If you have any questions or want to walk through this together, just let me know—I’m here to help!fast-ram-26210
10/31/2025, 12:51 PM2025-10-31 18:17:56,965 DEBUG openai._base_client | Sending HTTP Request: POST https://api.openai.com/v1/chat/completions
2025-10-31 18:17:56,966 DEBUG httpcore.http11 | send_request_headers.started request=<Request [b'POST']>
2025-10-31 18:17:56,967 DEBUG httpcore.http11 | send_request_headers.complete
2025-10-31 18:17:56,967 DEBUG httpcore.http11 | send_request_body.started request=<Request [b'POST']>
2025-10-31 18:17:56,967 DEBUG httpcore.http11 | send_request_body.complete
2025-10-31 18:17:56,967 DEBUG httpcore.http11 | receive_response_headers.started request=<Request [b'POST']>
2025-10-31 18:17:57,123 INFO livekit.agents | closing agent session due to participant disconnect (disable via `RoomInputOptions.close_on_disconnect=False`)
2025-10-31 18:17:57,123 DEBUG livekit.agents | stream closed
2025-10-31 18:17:57,123 INFO livekit.agents | closing agent session due to participant disconnect (disable via `RoomInputOptions.close_on_disconnect=False`)
2025-10-31 18:17:57,123 - INFO livekit.agents - closing agent session due to participant disconnect (disable via `RoomInputOptions.close_on_disconnect=False`) {"participant": "identity-5gXa", "reason": "CLIENT_INITIATED", "pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
2025-10-31 18:17:57,123 DEBUG livekit.agents | stream closed
2025-10-31 18:17:57,123 - DEBUG livekit.agents - stream closed {"participant": "identity-5gXa", "source": "SOURCE_MICROPHONE", "pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
2025-10-31 18:17:57,124 DEBUG httpcore.http11 | receive_response_headers.failed exception=CancelledError()
2025-10-31 18:17:57,124 DEBUG httpcore.http11 | response_closed.started
2025-10-31 18:17:57,125 DEBUG httpcore.http11 | response_closed.complete
2025-10-31 18:17:57,126 DEBUG livekit.agents | input stream detached
2025-10-31 18:17:57,126 DEBUG livekit.agents | input stream detached
2025-10-31 18:17:57,126 - DEBUG livekit.agents - input stream detached {"participant": "identity-5gXa", "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
2025-10-31 18:17:57,128 DEBUG livekit.agents | session closed
2025-10-31 18:17:57,128 DEBUG livekit.agents | session closed
2025-10-31 18:17:57,128 - DEBUG livekit.agents - session closed {"reason": "participant_disconnected", "error": null, "pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
2025-10-31 18:18:18,688 DEBUG livekit.agents | shutting down job task
2025-10-31 18:18:18,690 INFO livekit.agents | process exiting
2025-10-31 18:18:18,690 - INFO livekit.agents - process exiting {"reason": "", "pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
2025-10-31 18:18:18,690 DEBUG livekit | tungstenite::protocol:666:tungstenite::protocol - Received close frame: Some(CloseFrame { code: Normal, reason: "" })
2025-10-31 18:18:18,688 DEBUG livekit.agents | shutting down job task
2025-10-31 18:18:18,688 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false, "pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
2025-10-31 18:18:18,691 DEBUG livekit | tungstenite::protocol:683:tungstenite::protocol - Replying to close with Frame { header: FrameHeader { is_final: true, rsv1: false, rsv2: false, rsv3: false, opcode: Control(Close), mask: None }, payload: [3, 232] }
2025-10-31 18:18:18,692 DEBUG livekit.agents | http_session(): closing the httpclient ctx
2025-10-31 18:18:18,692 DEBUG livekit.agents | http_session(): creating a new httpclient ctx
2025-10-31 18:18:18,692 DEBUG livekit.agents | http_session(): closing the httpclient ctx
2025-10-31 18:18:18,692 - DEBUG livekit.agents - http_session(): closing the httpclient ctx {"pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
2025-10-31 18:18:18,692 DEBUG livekit.agents | http_session(): creating a new httpclient ctx
2025-10-31 18:18:18,692 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx {"pid": 32727, "job_id": "AJ_6uuWVz66qbej"}
^C2025-10-31 18:19:30,961 INFO livekit.agents | shutting down worker
2025-10-31 18:19:30,961 - INFO livekit.agents - shutting down worker {"id": "AW_R6eLtgXpPCPc"}tall-airline-16756
10/31/2025, 12:52 PMstop_egress function when you detect a participant has disconnected. For example:
@ctx.room.on("participant_disconnected")
def on_participant_disconnected(participant):
log.info(f"Participant {participant.identity} disconnected")
if egress_id:
asyncio.create_task(stop_recording(egress_id))
1. Handle Agent Session Cleanup: If you’re using an agent session, make sure to properly clean up by setting RoomInputOptions.close_on_disconnect=False. This helps avoid closing the session too soon.
2. Monitor Recording State: Keep an eye on the is_recording property to verify if the room is actively recording, so you can confirm the recording starts and stops as expected.
If you’d like, I’m here to help you implement these changes or troubleshoot further — just let me know!
Sources: lib/src/preconnect/pre_connect_audio_buffer.dart | examples/voice_agents/session_close_callback.py | template-default/src/Room.tsx | Recording participants | LiveKit docs | livekit-rtc/livekit/rtc/room.pyfast-ram-26210
10/31/2025, 12:53 PMtall-airline-16756
10/31/2025, 12:54 PMoutput field in your recording request might be missing or not set up quite right. No worries, I’m here to help you fix it! Here’s what you can do:
1. Make Sure Your Output is Properly Configured: When working with composite recordings, you’ll want to include at least one of these fields in your request:
• `file_outputs`: If you want to save the recording as an MP4 file.
• `stream_outputs`: To stream your recording using RTMP or SRT.
• `segment_outputs`: To create HLS segments.
1. Update Your Code: Instead of using the file field in your RoomCompositeEgressRequest, switch to file_outputs and make sure it’s an array. Here’s an example to guide you:
room_composite = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="grid", # Options: "grid" or "speaker"
audio_only=False,
video_only=False,
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{room_name}-{int(asyncio.get_event_loop().time())}.mp4"
)
]
)
1. Double-Check Your Cloud Storage Settings: If you’re using cloud storage like S3, GCP, or Azure, make sure your credentials and bucket details are correctly set up in the file_outputs configuration.
2. Give It a Try: Run your script again and see if the recording starts smoothly without any errors.
If you run into any other questions or want me to walk you through this step-by-step, just let me know—I’m happy to help!
Sources: livekit-protocol/src/livekit.rs | pkg/errors/errors.go | Egress output types | LiveKit docs | livekit-protocol/livekit/protocol/egress.pyi | livekit/livekit_egress.pb.gofast-ram-26210
10/31/2025, 12:59 PMtall-airline-16756
10/31/2025, 1:00 PMoutput field in your recording request isn’t set up quite right yet. No worries—let’s walk through some steps together to get this sorted out:
1. Use the Correct Output Field: For composite recordings, make sure you’re using file_outputs (instead of file) and that it’s formatted as an array. Here’s an example to guide you:
room_composite = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="grid", # Options: "grid" or "speaker"
audio_only=False,
video_only=False,
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{room_name}-{int(asyncio.get_event_loop().time())}.mp4"
)
]
)
1. Validate Storage Configuration: If you’re using cloud storage like S3, GCP, or Azure, double-check that your credentials and bucket details are correctly set within the file_outputs configuration. Here’s an example for clarity:
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath="my-recording.mp4",
s3=api.S3Upload(
access_key="your-access-key",
secret="your-secret-key",
region="your-region",
bucket="your-bucket-name"
)
)
]
1. Ensure Only One Output Type is Set: Remember, the API supports only one output per type (like one file_outputs or one stream_outputs). So, make sure you’re not setting multiple outputs of the same kind.
2. Check for Deprecated Fields: Avoid using outdated fields such as file, stream, or segments. Instead, stick with the plural forms like file_outputs and stream_outputs.
3. Test the Fix: After making these adjustments, try running your script again to see if the recording starts smoothly without errors.
If you run into any more questions or need a hand with this setup, please don’t hesitate to reach out—I’m here to help!
Sources: livekit-protocol/src/livekit.rs | protobufs/livekit_egress.proto | Egress API | LiveKit Docs | lib/livekit/egress_service_client.rbfast-ram-26210
10/31/2025, 1:15 PMI get this response using live kit api async def request(
self,
service: str,
method: str,
data: Message,
headers: Dict[str, str],
response_class: Type[T],
*,
timeout: Optional[aiohttp.ClientTimeout] = None,
) -> T:
url = f"{self.host}/{self.prefix}/{self.pkg}.{service}/{method}"
headers["Content-Type"] = "application/protobuf"
serialized_data = data.SerializeToString()
async with self._session.post(
url, headers=headers, data=serialized_data, timeout=timeout
) as resp:
if resp.status == 200:
return response_class.FromString(await resp.read())
else:
# when we have an error, Twirp always encode it in json
error_data = await resp.json()
raise TwirpError(
error_data.get("code", "unknown"),
error_data.get("msg", ""),
status=resp.status,
metadata=error_data.get("meta"),
)fast-ram-26210
10/31/2025, 1:15 PMclass TwirpClient:
def __init__(
self,
session: aiohttp.ClientSession,
host: str,
pkg: str,
prefix: str = DEFAULT_PREFIX,
) -> None:
parse_res = urlparse(host)
scheme = parse_res.scheme
if scheme.startswith("ws"):
scheme = scheme.replace("ws", "http")
host = f"{scheme}://{parse_res.netloc}/{parse_res.path}"
self.host = host.rstrip("/")
self.pkg = pkg
self.prefix = prefix
self._session = session
async def request(
self,
service: str,
method: str,
data: Message,
headers: Dict[str, str],
response_class: Type[T],
*,
timeout: Optional[aiohttp.ClientTimeout] = None,
) -> T:
url = f"{self.host}/{self.prefix}/{self.pkg}.{service}/{method}"
headers["Content-Type"] = "application/protobuf"
serialized_data = data.SerializeToString()
async with self._session.post(
url, headers=headers, data=serialized_data, timeout=timeout
) as resp:
if resp.status == 200:
return response_class.FromString(await resp.read())
else:
# when we have an error, Twirp always encode it in json
error_data = await resp.json()
raise TwirpError(
error_data.get("code", "unknown"),
error_data.get("msg", ""),
status=resp.status,
metadata=error_data.get("meta"),
)tall-airline-16756
10/31/2025, 1:16 PMTwirpError you're encountering with your LiveKit API request. Here’s a step-by-step approach to help you through it:
1. Catch the Exception: Start by wrapping your API call in a try-except block. This way, you can gracefully handle the TwirpError and see the details that might point us in the right direction:
from livekit.api import TwirpError
try:
response = await lkapi.egress.start_room_composite_egress(request)
except TwirpError as e:
print(f"TwirpError: code={e.code}, message={e.message}, status={e.status}")
if e.metadata:
print(f"Metadata: {e.metadata}")
1. Inspect the Error: The attributes code, message, and status can give us valuable clues. For example:
• `INVALID_ARGUMENT`: This usually means something in your request is missing or not quite right.
• `UNAUTHENTICATED`: This suggests your API keys might be missing or incorrect.
• `NOT_FOUND`: This indicates the resource you’re trying to access doesn’t exist.
1. Verify Your Request: Double-check that fields like file_outputs are set up correctly in your egress request. Here’s a quick example to guide you:
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath="recordings/my-room.mp4"
)
]
1. Check API Configuration: It’s important to make sure your LiveKitAPI instance is initialized with the right server URL, and that your LIVEKIT_API_KEY and LIVEKIT_API_SECRET are correctly set up.
2. Review Logs: If things still aren’t working, having full logs with timestamps and room IDs can be super helpful for digging deeper.
Please feel free to share your code or logs if you’d like me to help you review them or troubleshoot further. I’m here to help you get this sorted out!
Sources: README.md | SIP troubleshooting guide | LiveKit Docs | Still Have Questionsfast-ram-26210
10/31/2025, 1:20 PM--------url-----------------https://testing-law-1o5uf1sg.livekit.cloud/twirp/livekit.Egress/StartRoomCompositeEgress
input data --------------------------b'\n\x14playground-0gwU-uizf\x12\x04gridZ-\x08\x01\x12)recordings/playground-0gwU-uizf-29856.mp4'
2025-10-31 18:49:40,239 INFO video-ai-agent | Connected to room
2025-10-31 18:49:40,239 - INFO video-ai-agent - Connected to room {"pid": 34284, "job_id": "AJ_qEjyZ3ivtyoG"}
2025-10-31 18:49:40,239 INFO video-ai-agent | ----------------------room coposite start
2025-10-31 18:49:40,239 - INFO video-ai-agent - ----------------------room coposite start {"pid": 34284, "job_id": "AJ_qEjyZ3ivtyoG"}
2025-10-31 18:49:40,239 INFO video-ai-agent | ----------------------room coposite end
2025-10-31 18:49:40,239 - INFO video-ai-agent - ----------------------room coposite end {"pid": 34284, "job_id": "AJ_qEjyZ3ivtyoG"}
failed live kit api ---------------------------------------
2025-10-31 18:49:40,595 ERROR video-ai-agent | Failed to start recording---------------------------------------: TwirpError(code=invalid_argument, message=request has missing or invalid field: output, status=400)tall-airline-16756
10/31/2025, 1:20 PMoutput field in your request isn’t quite set up correctly yet. From what you’ve shared, it seems the file_outputs field might be missing or not formatted quite right. No worries though—here’s a simple way to fix it:
1. Update the Request: Make sure you’re using the file_outputs field as an array and include all the necessary parameters. For example:
room_composite = api.RoomCompositeEgressRequest(
room_name="playground-0gwU-uizf",
layout="grid",
audio_only=False,
video_only=False,
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath="recordings/playground-0gwU-uizf-29856.mp4"
)
]
)
1. Validate the File Path: Double-check that the filepath is valid and writable. If you’re saving locally, make sure the folder exists and you have the right permissions.
2. Check for Deprecated Fields: Try to avoid using the singular file field and stick with file_outputs instead.
3. Test the Fix: Give your script another run and see if the recording starts smoothly.
If you’re still running into trouble, feel free to share the exact code snippet of your RoomCompositeEgressRequest setup—I’m here to help you get it sorted!fast-ram-26210
10/31/2025, 1:24 PMtall-airline-16756
10/31/2025, 1:25 PMoutput field in your request isn’t quite set up correctly yet. From what I can see, the file_outputs field might be missing or not formatted quite right. No worries though, here’s a step-by-step guide to help you fix this:
1. Make Sure It’s Configured Properly: Update your RoomCompositeEgressRequest to include the file_outputs field as an array. Here’s an example you can follow:
room_composite = api.RoomCompositeEgressRequest(
room_name="playground-mrCb-UAET",
layout="grid",
audio_only=False,
video_only=False,
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath="recordings/playground-mrCb-UAET-30128.mp4"
)
]
)
1. Double-Check the File Path: Please make sure the recordings/ directory exists and that you have the right write permissions. If it’s not there, just create it before running your script.
2. Avoid Deprecated Fields: It’s important to use file_outputs instead of the older file field, which is deprecated.
3. Close Any Unused Sessions: Your log shows there might be an unclosed client session. To keep things tidy, be sure to properly close the aiohttp.ClientSession after your API call, like this:
async with aiohttp.ClientSession() as session:
lkapi = api.LiveKitAPI(session, LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
await lkapi.egress.start_room_composite_egress(room_composite)
If you have any questions or if the problem continues after trying these steps, please don’t hesitate to reach out. I’m here to help!fast-ram-26210
10/31/2025, 1:27 PMtall-airline-16756
10/31/2025, 1:28 PM<YOUR_LIVEKIT_SERVER_URL>/twirp/livekit.Egress/StartRoomCompositeEgress
1. Set the HTTP Method: Choose POST.
2. Set Headers: Make sure to add these headers:
• Content-Type: application/json
• Authorization: Bearer <your-access-token> (if your setup requires it)
1. Set the Request Body: Use JSON to specify your recording details. Here’s an example:
{
"room_name": "playground-mrCb-UAET",
"layout": "grid",
"file_outputs": [
{
"file_type": "MP4",
"filepath": "recordings/playground-mrCb-UAET-30128.mp4"
}
]
}
1. Send the Request: Just hit "Send" in Postman to make the call.
2. Check the Response: If everything goes well, you’ll get a response with your recording details. If something’s off, the response will include an error code and message to help you figure it out.
If you’d like, I’m here to help you set up the request or troubleshoot any hiccups along the way—just let me know!fast-ram-26210
10/31/2025, 1:30 PMtall-airline-16756
10/31/2025, 1:30 PMfilepath field in the recording request is where you specify the location and name of your output file. By default, it uses the format {track_id}-{time}, but feel free to customize it to suit your needs. For example:
"filepath": "recordings/playground-mrCb-UAET-30128.mp4"
Just a couple of things to keep in mind:
• Make sure the directory (like recordings/) exists and has the right permissions for writing files.
• Try to use a unique file name so you don’t accidentally overwrite any existing recordings.
If you’re working with cloud storage (like S3, GCP, or Azure), double-check that the filepath fits with what your storage provider expects.
I'm here to help if you have any questions or need a hand with this!fast-ram-26210
10/31/2025, 1:36 PMtall-airline-16756
10/31/2025, 1:37 PMlk token create \
--api-key <your-api-key> \
--api-secret <your-api-secret> \
--join \
--room my-first-room \
--identity user1 \
--valid-for 24h
1. Using the Python SDK: Here’s a simple example to guide you:
from livekit import api
import os
token = (
api.AccessToken(
api_key=os.getenv("LIVEKIT_API_KEY"),
api_secret=os.getenv("LIVEKIT_API_SECRET")
)
.with_identity("user1")
.with_grants(
api.VideoGrants(
room_join=True,
room="my-first-room"
)
)
.to_jwt()
)
print(token)
1. Using the LiveKit Cloud Dashboard: You can also go to your project’s settings in the LiveKit Cloud dashboard and generate a token there with ease.
Just a quick tip: tokens are JWT-based and need your API key and secret, so it’s best to generate them on the server side to keep everything safe and sound. If you have any questions or want me to walk you through any step, I’m here to help!
Sources: LiveKit CLI Setup | LiveKit Docs | rover/auth.py | README.md | livekit/livekit_composite | DeepWiki | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWikifast-ram-26210
10/31/2025, 1:44 PMits my live kit version livekit 1.0.17
livekit-agents 1.2.17
livekit-api 1.0.7
livekit-blingfire 1.0.1
livekit-plugins-cartesia 1.2.17
livekit-plugins-deepgram 1.2.17
livekit-plugins-openai 1.2.17
livekit-plugins-silero 1.2.17
livekit-plugins-turn-detector 1.2.17
livekit-protocol 1.0.8tall-airline-16756
10/31/2025, 1:45 PMlivekit-api version (1.0.7) matches up with the server version you’re using.
• Confirm that all the necessary environment variables, like LIVEKIT_API_KEY and LIVEKIT_API_SECRET, are properly set.
• Verify you’re using the right methods for your version when configuring and sending requests (for example, file_outputs for recordings).
If you’d like, I’m here to help you troubleshoot your specific setup—just let me know!fast-ram-26210
10/31/2025, 1:51 PMtall-airline-16756
10/31/2025, 1:51 PMlivekit-protocol) needs to align with your server and SDK versions to keep message communication seamless.
• To get more insight when troubleshooting, try enabling debug logging. For example, in Python, setting the logging level to DEBUG can capture detailed information that might help pinpoint any issues.
• Lastly, taking a quick look at the release notes can be really useful—they often highlight any breaking changes between versions that could impact your setup.
If you’re running into any specific problems, please don’t hesitate to share details like exact error messages, logs, or the steps you took before the issue appeared. I’m here to help and happy to guide you through any challenges!
Sources: .github/ISSUE_TEMPLATE/bug_report.yaml | CHANGELOG.md | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | Protocol & WebRTC Stack | livekit/livekit_composite | DeepWiki | client/web/.github/ISSUE_TEMPLATE/bug_report.yaml