sync def entrypoint(ctx: JobContext): # Create...
# ask-ai
s
sync 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, layout="speaker-dark", file=api.EncodedFileOutput( file_type=api.EncodedFileType.MP4, 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})") if transcript.is_final: transcripts.append({ "role": "user", "timestamp": datetime.now().isoformat(), "text": transcript.transcript }) @session.on("agent_output_generated") def on_agent_transcript(output): print(f"Agent said: {output.text}") transcripts.append({ "role": "agent", "timestamp": datetime.now().isoformat(), "text": output.text }) 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() Failed to start recording: 'LiveKitAPI' object has no attribute 'room_composite_egress' resolve the issue im unable to get the agent transcript record transcript . is there any option that i can do in the diconnection or ending of the call i need to commit the data into the post gress
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 is happening because the method
room_composite_egress
isn’t directly available on the
LiveKitAPI
object. No worries—we can fix this by accessing the egress functionality through the dedicated egress service client. Let me walk you through how to do that: Correct Usage:
Copy code
from livekit import api
from livekit.protocol.egress import RoomCompositeEgressRequest

# Initialize LiveKit API
lkapi = api.LiveKitAPI(
    url=os.getenv("LIVEKIT_URL"),
    api_key=os.getenv("LIVEKIT_API_KEY"),
    api_secret=os.getenv("LIVEKIT_API_SECRET")
)

# Access the egress service
egress_service = lkapi.egress

# Create a recording request
recording_request = RoomCompositeEgressRequest(
    room_name=room_id,
    layout="speaker-dark",
    file=api.EncodedFileOutput(
        file_type=api.EncodedFileType.MP4,
        filepath=recording_path
    )
)

# Start the recording
try:
    egress_info = await egress_service.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}")
Also, just a quick reminder to make sure your SDK is up-to-date, since older versions might not support these method signatures. And don’t forget to check that your API keys have the
room_record
permission enabled—that’s essential for this to work smoothly. Regarding committing data to PostgreSQL at the end of the call, you’re on the right track! Using
ctx.add_shutdown_callback
to finalize the session and save transcripts is exactly how it should be done. Just double-check that your
finalize_session
function is being called properly during the shutdown process. Sources: cmd/lk/egress.go | livekit-protocol/livekit/protocol/egress.pyi | packages/livekit-server-sdk/src/EgressClient.ts | lib/livekit/egress_service_client.rb | Recording and export | LiveKit docs
s
how can i give permisions fpr the api key
t
I'm happy to help you with setting the permissions for your API key! These permissions are managed through access tokens, which include specific grants that define what actions a participant or service can perform. To enable recording permissions, you'll want to include the
roomRecord
grant in your access token. Let me walk you through how you can do this: Example in Python:
Copy code
from livekit import AccessToken, VideoGrant

# Create a video grant with recording permissions
grant = VideoGrant(room_record=True)

# Generate an access token
access_token = AccessToken(
    api_key="your-api-key",
    api_secret="your-api-secret",
    grants=grant
)

# Add additional details if needed
access_token.identity = "user-identity"
access_token.ttl = 3600  # Token validity in seconds

token = access_token.to_jwt()
print(f"Generated token: {token}")
Just be sure to replace
your-api-key
and
your-api-secret
with your actual API credentials. This token will then have the permissions needed to start and manage recordings smoothly. If you'd like, I’m here to help with more examples in other programming languages or any other questions you might have. Just let me know! Sources: packages/livekit-server-sdk/README.md | Managing participants | LiveKit docs | Authentication | LiveKit Docs | src/main/kotlin/io/livekit/server/VideoGrant.kt | Sources/LiveKit/Token/JWT.swift
s
token = ( api.AccessToken(settings.livekit_api_key, settings.livekit_api_secret) .with_identity(request.identity) .with_grants(api.VideoGrants(room_join=True, room=request.room_name)) .with_room_config( api.RoomConfiguration( agents=[api.RoomAgentDispatch(agent_name=request.agent_id)] ) ) ) logger.info(f"key: {settings.livekit_api_key}, secret: {settings.livekit_api_secret}") jwt_token = token.to_jwt() i want to use and add grants in this code
t
To help you add grants to your existing code, you can include the necessary permissions within the
VideoGrants
object. For instance, if you'd like to add recording permissions, you can update your code like this:
Copy code
token = (
    api.AccessToken(settings.livekit_api_key, settings.livekit_api_secret)
    .with_identity(request.identity)
    .with_grants(api.VideoGrants(
        room_join=True, 
        room=request.room_name,
        room_record=True  # Add recording permission here
    ))
    .with_room_config(
        api.RoomConfiguration(
            agents=[api.RoomAgentDispatch(agent_name=request.agent_id)]
        )
    )
)

logger.info(f"key: {settings.livekit_api_key}, secret: {settings.livekit_api_secret}")

jwt_token = token.to_jwt()
This way, the generated token will include the
room_record
grant, enabling it to start and manage recordings smoothly. Feel free to add any other grants you might need by including them in the
VideoGrants
object. If you have any questions or need more help, just let me know—I’m here to support you!
s
how can i access the agent transcripts or the final transcipt before ending the sessiojn
t
To help you access agent transcripts or the final transcript before ending the session, here are some friendly and effective approaches you can try: 1. Real-Time Access: • You can listen for the
user_input_transcribed
event to capture user transcripts as they happen. For example:
Copy code
@session.on("user_input_transcribed")
def on_transcript(transcript):
    if transcript.is_final:
        print(f"Final transcript: {transcript.transcript}")
• Also, the
session.history
property is super helpful for getting the entire conversation history, including all user and agent messages:
Copy code
history = session.history
for item in history:
    print(item.text_content)
2. Ensure Final Transcript Capture: • To make sure you’re capturing the final transcripts before ending the session, you can use
commit_user_turn()
to explicitly flush STT buffers like this:
Copy code
session.commit_user_turn(
    transcript_timeout=5.0,  # Wait up to 5 seconds for final transcript
    stt_flush_duration=2.0   # Duration of silence to flush STT buffer
)
• It’s also a great idea to implement a shutdown callback that captures the complete conversation state before the session closes, for example:
Copy code
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)
Using these methods will help you reliably capture both real-time and final transcripts before your session ends. If you have any questions or need a bit more guidance, please don’t hesitate to ask—I’m here to help! Sources: Session recording and transcripts | LiveKit Docs | livekit-agents/livekit/agents/tts/tts.py
s
will this record my audio agent and user : 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, layout="speaker-dark", file=api.EncodedFileOutput( file_type=api.EncodedFileType.MP4, 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}")
t
I'm happy to help clarify this for you! The
RoomCompositeEgressRequest
does indeed record both user and agent audio by default. It captures all participant audio tracks in the room, including those from users and AI agents, and blends them together in the recording. If you'd like to tailor how the audio is mixed, you can use the
audioMixing
option. For instance, setting
audioMixing
to
DUAL_CHANNEL_AGENT
will place the agent's audio in the left channel and all other participant audio (like the user's) in the right channel. Please feel free to reach out if you'd like any more help with setting up your recording—I’m here to support you! Sources: Custom recording templates | LiveKit docs | Composite and web recordings | LiveKit docs | livekit/livekit_egress.pb.go | livekit-protocol/src/livekit.rs | egress/recording_agent.py
s
give me code with integrated all required things
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
s
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, layout="speaker-dark", file=api.EncodedFileOutput( file_type=api.EncodedFileType.MP4, 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}")