Failed to start recording: 'LiveKitAPI' object has...
# ask-ai
s
Failed to start recording: 'LiveKitAPI' object has no attribute 'room_composite_egress' {"message": "unhandled exception while running the job task\nTraceback (most recent call last):\n File \"/root/agents/.venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/root/agents/.venv/lib/python3.13/site-packages/livekit/agents/ipc/job_proc_lazy_main.py\", line 240, in _traceable_entrypoint\n await self._job_entrypoint_fnc(job_ctx)\n File \"/root/agents/agent2.py\", line 429, in entrypoint\n session.add_shutdown_callback(capture_final_state)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAttributeError: 'AgentSession' object has no attribute 'add_shutdown_callback'", "level": "ERROR", "name": "livekit.agents", "pid": 1131190, "job_id": "AJ_ArR69qrd9voB", "timestamp": "2025-11-01T171734.789273+00:00"}
t
Thanks for reaching out, ABHIRAM. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
It looks like the error happens because the method
room_composite_egress
isn’t directly available on the
LiveKitAPI
object. No worries though! To fix this, you’ll want to access the egress service and use the method
start_room_composite_egress
instead. Here’s a friendly example to help you get started with room composite egress:
Copy code
from livekit import api

# Create the egress request
req = api.RoomCompositeEgressRequest(
    room_name="my-room",
    layout="speaker",
    preset=api.EncodingOptionsPreset.H264_720P_30,
    audio_only=False,
    segment_outputs=[api.SegmentedFileOutput(
        filename_prefix="my-output",
        playlist_name="my-playlist.m3u8",
        live_playlist_name="my-live-playlist.m3u8",
        segment_duration=5,
        gcp=api.GCPUpload(
            credentials=file_contents,
            bucket="<my-bucket>",
        ),
    )],
)

# Create LiveKitAPI instance and start egress
lkapi = api.LiveKitAPI()
res = await lkapi.egress.start_room_composite_egress(req)

# Don’t forget to close the API client
await lkapi.aclose()
Just make sure you’re calling the egress service (
lkapi.egress
) and the right method name (
start_room_composite_egress
). If you run into any more questions or need a hand, I’m here to help! Sources: livekit-api/livekit/api/egress_service.py | egress/recording_agent.py
s
integrate me teh recording in my entry point : async def entrypoint(ctx: JobContext): # Create UserData with JobContext # Let it try all transports automatically session_id = ctx.job.id room_id = ctx.room.name user_id = None for participant in ctx.room.remote_participants.values(): user_id = participant.identity break # Connect to PostgreSQL database using URI db_uri = os.getenv("DATABASE_URL") db_pool = await asyncpg.create_pool(dsn=db_uri) # Ensure the table exists async with db_pool.acquire() as conn: await conn.execute(''' CREATE TABLE IF NOT EXISTS session_transcripts ( id SERIAL PRIMARY KEY, session_id TEXT, room_id TEXT, user_id TEXT, transcripts JSONB, recording_path TEXT ) ''') # Initialize transcript storage transcripts = [] # Start local recording using Egress egress_client = api.LiveKitAPI( url=os.getenv("LIVEKIT_URL"), api_key=os.getenv("LIVEKIT_API_KEY"), api_secret=os.getenv("LIVEKIT_API_SECRET") ) recording_path = f"recordings/{session_id}_{room_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4" recording_request = api.RoomCompositeEgressRequest( room_name=room_id, file=api.EncodedFileOutput( file_type=api.EncodedFileType.MP3, filepath=recording_path ) ) try: egress_info = await egress_client.room_composite_egress.start_room_composite_egress(recording_request) print(f"Started recording with ID: {egress_info.egress_id}") except Exception as e: print(f"Failed to start recording: {e}") userdata = UserData(ctx=ctx) session = AgentSession[UserData](userdata=userdata) userdata.session = session @session.on("user_input_transcribed") def on_user_transcript(transcript): print(f"User said: {transcript.transcript} (final: {transcript.is_final})") print(f"User raw data final: {session.final_history}") print(f"history: {session.history}") print(f"session: {session}") if transcript.is_final: transcripts.append({ "role": "user", "timestamp": datetime.now().isoformat(), "text": transcript.transcript }) def capture_final_state(): final_history = session.history current_transcript = session.current_transcript if hasattr(session, 'current_transcript') else "" # Save to file or database with open("final_session_data.json", "w") as f: json.dump({ "conversation_history": final_history, "final_transcript": current_transcript, "timestamp": time.time() }, f) session.add_shutdown_callback(capture_final_state) async def finalize_session(): # Save transcripts and recording path to PostgreSQL async with db_pool.acquire() as conn: print("Saving session transcripts to database...") await conn.execute(''' INSERT INTO session_transcripts (session_id, room_id, user_id, transcripts, recording_path) VALUES ($1, $2, $3, $4, $5) ''', session_id, room_id, user_id, transcripts, recording_path) # Stop Egress recording try: await egress_client.room_composite_egress.stop_egress(egress_info.egress_id) print(f"Stopped recording with ID: {egress_info.egress_id}") except Exception as e: print(f"Failed to stop recording: {e}") await db_pool.close() ctx.add_shutdown_callback(finalize_session) await session.start( agent=VoiceAssistant(), room=ctx.room ) await ctx.connect()
t
I'd love to help you integrate LiveKit recording into your
entrypoint
function! To make sure everything runs smoothly, it's important to handle egress properly and manage any potential errors. Here's an improved version of your function that uses the egress service correctly and includes solid error handling:
Copy code
async def entrypoint(ctx: JobContext):
    lkapi = api.LiveKitAPI(
        url=os.getenv("LIVEKIT_URL"),
        api_key=os.getenv("LIVEKIT_API_KEY"),
        api_secret=os.getenv("LIVEKIT_API_SECRET")
    )
    egress_info = None
    try:
        # Define the recording request
        recording_request = api.RoomCompositeEgressRequest(
            room_name=ctx.room.name,
            file=api.EncodedFileOutput(
                file_type=api.EncodedFileType.MP4,
                filepath=f"recordings/{ctx.job.id}_{ctx.room.name}.mp4"
            )
        )

        # Start the recording
        egress_info = await lkapi.egress.start_room_composite_egress(recording_request)
        print(f"Started recording with ID: {egress_info.egress_id}")

        # Connect agent to room
        await ctx.connect()

        # Agent session continues...

    except Exception as e:
        print(f"Failed to start recording: {e}")
        if egress_info:
            print(f"Egress ID: {egress_info.egress_id}")
        raise
    finally:
        # Ensure the API client is closed
        await lkapi.aclose()

    async def finalize_session():
        # Stop the recording
        try:
            if egress_info:
                await lkapi.egress.stop_egress(egress_info.egress_id)
                print(f"Stopped recording with ID: {egress_info.egress_id}")
        except Exception as e:
            print(f"Failed to stop recording: {e}")

    # Add shutdown callback to finalize the session
    ctx.add_shutdown_callback(finalize_session)
Here are some key improvements we've made: • Using
lkapi.egress.start_room_composite_egress
properly to kick off the recording. • Wrapping egress operations in
try-except
blocks to catch and handle errors gracefully. • Making sure the
LiveKitAPI
client is always closed with a
finally
block, so resources are cleaned up. • Adding a shutdown callback that stops the recording and tidies up when the session ends. If you have any questions or want to customize this further, just let me know—I'm here to help! Sources: Universal Egress | docs/index.yaml | Custom recording templates | LiveKit docs | livekit-protocol/livekit/protocol/egress.py