straight-jelly-92105
11/01/2025, 4:02 AMtall-airline-16756
11/01/2025, 4:02 AMtall-airline-16756
11/01/2025, 4:02 AMuser_input_transcribed or grab the full conversation history using session.history once the session ends. From there, storing this data in your database is straightforward with your usual database drivers.
For tracking call duration, here are a couple of friendly tips:
• You can use RECOGNITION_USAGE events from STT plugins such as Deepgram or FireworksAI to monitor how long the audio was transcribed.
• Another way is to track the session duration by noting when participants connect and disconnect.
If you'd like, I’m here to guide you through setting up database integration or event listeners—just let me know!
Sources: Session recording and transcripts | LiveKit Docs | docs/index.yaml | livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt_v2.pystraight-jelly-92105
11/01/2025, 4:03 AMtall-airline-16756
11/01/2025, 4:04 AMfrom pathlib import Path
import datetime
import logging
from dotenv import load_dotenv
from livekit import api
from livekit.agents import JobContext, WorkerOptions, cli, metrics
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram, silero
load_dotenv(dotenv_path=Path(__file__).parent / '.env')
logger = logging.getLogger("combined-recording-agent")
logger.setLevel(logging.INFO)
async def entrypoint(ctx: JobContext):
start_time = datetime.datetime.now()
lkapi = api.LiveKitAPI()
egress_req = api.RoomCompositeEgressRequest(
room_name=ctx.room.name,
preset=api.EncodingOptionsPreset.H264_720P_30,
audio_only=False,
file_outputs=[api.EncodedFileOutput(
filename=f"recording_{ctx.room.name}_{start_time.strftime('%Y%m%d_%H%M%S')}.mp4"
)],
)
egress_info = await lkapi.egress.start_room_composite_egress(egress_req)
transcripts = []
session = AgentSession(vad=silero.VAD.load())
@session.on("user_input_transcribed")
def on_transcript(transcript):
if transcript.is_final:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
transcript_entry = f"[{timestamp}] {transcript.transcript}"
transcripts.append(transcript_entry)
with open(f"transcripts_{ctx.room.name}.txt", "a") as f:
f.write(f"{transcript_entry}\n")
async def finalize_session():
end_time = datetime.datetime.now()
duration = end_time - start_time
with open(f"session_summary_{ctx.room.name}.txt", "w") as f:
f.write(f"Session started: {start_time}\n")
f.write(f"Session ended: {end_time}\n")
f.write(f"Total duration: {duration}\n")
await lkapi.egress.stop_egress(egress_info.egress_id)
await lkapi.aclose()
ctx.add_shutdown_callback(finalize_session)
await session.start(
agent=Agent(
instructions="You are a helpful assistant that transcribes user speech and records the full session.",
stt=deepgram.STT(),
vad=silero.VAD.load()
),
room=ctx.room
)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here's a quick summary of what this code does:
• It starts Egress recording for both audio and video.
• Logs real-time transcripts with timestamps, so nothing important gets missed.
• Saves a session history and calculates the call duration neatly when the session ends.
If you'd like any further customization or have questions, please don't hesitate to reach out—I'm here to help!
Sources: Session recording and transcripts | LiveKit Docs | complex-agents/note-taking-assistant/agent.pystraight-jelly-92105
11/01/2025, 4:05 AMtall-airline-16756
11/01/2025, 4:05 AMstraight-jelly-92105
11/01/2025, 4:07 AMtall-airline-16756
11/01/2025, 4:09 AMimport asyncio
import datetime
import json
import os
from pathlib import Path
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram, openai
from livekit import api
load_dotenv()
async def entrypoint(ctx: JobContext):
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
ctx.log_context_fields.update({
"session_id": session_id,
"room_id": room_id,
"user_id": user_id,
"worker_id": "custom-worker-001"
})
egress_client = api.LiveKitAPI(
url=os.getenv("LIVEKIT_URL"),
api_key=os.getenv("LIVEKIT_API_KEY"),
api_secret=os.getenv("LIVEKIT_API_SECRET")
)
recording_request = api.RoomCompositeEgressRequest(
room_name=room_id,
layout="speaker-dark",
file=api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{session_id}_{room_id}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4",
s3=api.S3Upload(
access_key=os.getenv("AWS_ACCESS_KEY_ID"),
secret=os.getenv("AWS_SECRET_ACCESS_KEY"),
region=os.getenv("AWS_REGION"),
bucket=os.getenv("S3_BUCKET")
)
)
)
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}")
session = AgentSession()
@session.on("user_input_transcribed")
def on_transcript(transcript):
if transcript.is_final:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
transcript_data = {
"session_id": session_id,
"room_id": room_id,
"user_id": user_id,
"timestamp": timestamp,
"transcript": transcript.transcript,
"is_final": transcript.is_final
}
transcript_file = f"transcripts/{session_id}_{room_id}_transcripts.jsonl"
os.makedirs(os.path.dirname(transcript_file), exist_ok=True)
with open(transcript_file, "a") as f:
f.write(json.dumps(transcript_data) + "\n")
def save_session_data():
session_data = {
"session_id": session_id,
"room_id": room_id,
"user_id": user_id,
"start_time": datetime.datetime.now().isoformat(),
"conversation_history": []
}
if hasattr(session, 'history'):
for item in session.history:
session_data["conversation_history"].append({
"role": item.role if hasattr(item, 'role') else "unknown",
"content": item.text_content if hasattr(item, 'text_content') else str(item),
"timestamp": datetime.datetime.now().isoformat()
})
session_file = f"sessions/{session_id}_{room_id}_session.json"
os.makedirs(os.path.dirname(session_file), exist_ok=True)
with open(session_file, "w") as f:
json.dump(session_data, f, indent=2)
print(f"Session data saved to {session_file}")
ctx.add_shutdown_callback(save_session_data)
await session.start(
agent=Agent(
instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
stt=deepgram.STT(),
llm=openai.LLM(),
tts=openai.TTS()
),
room=ctx.room
)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s what this code does for you:
• It saves the session ID, room ID, user ID, and transcripts neatly in JSON format.
• It kicks off audio/video recording using Egress and safely stores the files in S3 or your local directory.
• It thoughtfully preserves the full session history when the session shuts down.
If you’d like me to walk you through any part of this or need it adjusted to fit your needs better, just let me know — I’m here to help!
Sources: Job lifecycle | LiveKit Docs | Session recording and transcripts | LiveKit Docs | pipeline-stt/transcriber/transcriber.pystraight-jelly-92105
11/01/2025, 4:11 AMtall-airline-16756
11/01/2025, 4:11 AMstraight-jelly-92105
11/01/2025, 4:12 AMtall-airline-16756
11/01/2025, 4:12 AMasyncpg library for asynchronous database operations. Here’s an updated example that shows how to save transcripts directly to PostgreSQL:
import asyncio
import datetime
import os
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram
import asyncpg
load_dotenv()
async def entrypoint(ctx: JobContext):
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
db_pool = await asyncpg.create_pool(
user=os.getenv("POSTGRES_USER"),
password=os.getenv("POSTGRES_PASSWORD"),
database=os.getenv("POSTGRES_DB"),
host=os.getenv("POSTGRES_HOST"),
port=os.getenv("POSTGRES_PORT")
)
# Ensure the table exists
async with db_pool.acquire() as conn:
await conn.execute('''
CREATE TABLE IF NOT EXISTS transcripts (
id SERIAL PRIMARY KEY,
session_id TEXT,
room_id TEXT,
user_id TEXT,
timestamp TIMESTAMP,
transcript TEXT
)
''')
session = AgentSession()
@session.on("user_input_transcribed")
async def on_transcript(transcript):
if transcript.is_final:
timestamp = datetime.datetime.now()
async with db_pool.acquire() as conn:
await conn.execute('''
INSERT INTO transcripts (session_id, room_id, user_id, timestamp, transcript)
VALUES ($1, $2, $3, $4, $5)
''', session_id, room_id, user_id, timestamp, transcript.transcript)
async def finalize_session():
await db_pool.close()
ctx.add_shutdown_callback(finalize_session)
await session.start(
agent=Agent(
instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
stt=deepgram.STT()
),
room=ctx.room
)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s what this code does for you:
• It connects to your PostgreSQL database using asyncpg, making things efficient and asynchronous.
• It creates a transcripts table if it’s not already there, so you don’t have to worry about setup.
• Whenever a final transcript is ready, it inserts it into the database along with session ID, room ID, user ID, timestamp, and the transcript text.
Just make sure you have these environment variables set up properly:
POSTGRES_USER=your_db_user
POSTGRES_PASSWORD=your_db_password
POSTGRES_DB=your_db_name
POSTGRES_HOST=your_db_host
POSTGRES_PORT=your_db_port
If you run into any issues or want me to help tweak this further, please don’t hesitate to reach out. I’m here to support you every step of the way!straight-jelly-92105
11/01/2025, 4:14 AMtall-airline-16756
11/01/2025, 4:14 AMimport asyncio
import datetime
import os
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram
from livekit import api
import asyncpg
load_dotenv()
async def entrypoint(ctx: JobContext):
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
db_pool = await asyncpg.create_pool(
user=os.getenv("POSTGRES_USER"),
password=os.getenv("POSTGRES_PASSWORD"),
database=os.getenv("POSTGRES_DB"),
host=os.getenv("POSTGRES_HOST"),
port=os.getenv("POSTGRES_PORT")
)
# 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.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}")
session = AgentSession()
@session.on("user_input_transcribed")
def on_user_transcript(transcript):
if transcript.is_final:
transcripts.append({
"role": "user",
"timestamp": datetime.datetime.now().isoformat(),
"text": transcript.transcript
})
@session.on("agent_output_generated")
def on_agent_transcript(output):
transcripts.append({
"role": "agent",
"timestamp": datetime.datetime.now().isoformat(),
"text": output.text
})
async def finalize_session():
# Save transcripts and recording path to PostgreSQL
async with db_pool.acquire() as conn:
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=Agent(
instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
stt=deepgram.STT()
),
room=ctx.room
)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s a quick summary of what this code does:
• Gathers user and agent transcripts in a list as the session goes on.
• At the end of the session, it saves those transcripts along with the recording path into a PostgreSQL database.
• Keeps a local copy of the recording in the recordings folder.
Just a gentle reminder to make sure you’ve set these environment variables before running the code:
POSTGRES_USER=your_db_user
POSTGRES_PASSWORD=your_db_password
POSTGRES_DB=your_db_name
POSTGRES_HOST=your_db_host
POSTGRES_PORT=your_db_port
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
If you have any questions or need me to walk you through any part of this, please don’t hesitate to ask. I’m here to help!straight-jelly-92105
11/01/2025, 4:53 AMtall-airline-16756
11/01/2025, 4:54 AMimport asyncio
import datetime
import os
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import deepgram
from livekit import api
import asyncpg
load_dotenv()
async def entrypoint(ctx: JobContext):
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("POSTGRES_URI")
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.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}")
session = AgentSession()
@session.on("user_input_transcribed")
def on_user_transcript(transcript):
if transcript.is_final:
transcripts.append({
"role": "user",
"timestamp": datetime.datetime.now().isoformat(),
"text": transcript.transcript
})
@session.on("agent_output_generated")
def on_agent_transcript(output):
transcripts.append({
"role": "agent",
"timestamp": datetime.datetime.now().isoformat(),
"text": output.text
})
async def finalize_session():
# Save transcripts and recording path to PostgreSQL
async with db_pool.acquire() as conn:
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=Agent(
instructions="You are a helpful assistant. All conversations are being recorded and transcribed.",
stt=deepgram.STT()
),
room=ctx.room
)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Here’s a quick summary of what this code does:
• It uses the POSTGRES_URI environment variable to connect to your PostgreSQL database, making the setup cleaner.
• It keeps the functionality to save transcripts and the recording path to your database when the session ends.
• The recordings are saved locally in the recordings folder for easy access.
Just a gentle reminder to make sure you have these environment variables set up correctly:
POSTGRES_URI=postgresql://user:password@host:port/database
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
If you have any questions or need me to walk you through any part of this, please don’t hesitate to ask. I’m here to help!rapid-judge-7554
11/03/2025, 8:35 AMtall-airline-16756
11/03/2025, 8:35 AMVideoFileRenderer along with MediaCodec and MediaMuxer to save local audio and video tracks directly into an MP4 file. This approach is nicely showcased in LiveKit's Android sample app.
• Web: The LocalTrackRecorder class in the LiveKit JS SDK is a great tool here. It wraps the browser's MediaRecorder API, allowing you to record local tracks into MP4 or WebM files with ease.
• iOS/Desktop: For iOS and macOS, you might want to explore native media APIs like AVAssetWriter and AVCaptureSession. On desktop platforms, FFmpeg-based solutions can be very effective.
These options let you record the local participant’s audio and video right on your device. If you let me know which platform you’re working with, I’d be delighted to share some specific code examples or guide you further!
Sources: README.md | Recording and export | LiveKit docs | sample-app-record-local/README.md | src/room/track/record.tsrapid-judge-7554
11/03/2025, 8:48 AMtall-airline-16756
11/03/2025, 8:48 AMMediaRecorder API to capture local audio and video tracks. This way, the recording can be saved directly to the user's device as an MP4 or WebM file.
• Android: Using VideoFileRenderer along with MediaCodec and MediaMuxer allows you to record local tracks into an MP4 file.
• iOS/Desktop: Native media APIs like AVAssetWriter and AVCaptureSession are great tools to capture and save local tracks.
Keep in mind, these methods record only the local participant's audio and video. If you'd like to include remote participants, you can subscribe to their tracks and mix them locally before recording. Feel free to share your target platform with me—I’d love to provide you with specific code examples or any further guidance you might need!rapid-judge-7554
11/03/2025, 8:55 AMtall-airline-16756
11/03/2025, 8:56 AM`import React, { useState, useCallback, useRef } from 'react';
import { useLocalParticipant, useRoomContext } from '@livekit/components-react';
import { LocalVideoTrack, isRecordingSupported } from 'livekit-client';
const LocalRecorder: React.FC = () => {
const [isRecording, setIsRecording] = useState(false);
const [recordedBlob, setRecordedBlob] = useState<blob |="" null="">(null);
const [mimeType, setMimeType] = useState<string>('');
const { localParticipant } = useLocalParticipant();
const room = useRoomContext();
const recordingTrackRef = useRef<localvideotrack |="" null="">(null);
const startRecording = useCallback(async () => {
if (!isRecordingSupported()) {
console.error('MediaRecorder is not supported in this browser');
return;
}
const videoTrack = localParticipant.getTrackPublication('camera')?.track as LocalVideoTrack;
if (!videoTrack) {
console.error('No local video track found');
return;
}
recordingTrackRef.current = videoTrack;
videoTrack.startPreConnectBuffer(100);
setIsRecording(true);
const recordingMimeType = videoTrack.getPreConnectBufferMimeType();
setMimeType(recordingMimeType || 'video/mp4');
console.log(`Recording started with MIME type: ${recordingMimeType}`);
}, [localParticipant]);
const stopRecording = useCallback(async () => {
const videoTrack = recordingTrackRef.current;
if (!videoTrack) return;
const stream = videoTrack.getPreConnectBuffer();
const finalMimeType = videoTrack.getPreConnectBufferMimeType() || 'video/mp4';
videoTrack.stopPreConnectBuffer();
setIsRecording(false);
if (stream) {
const chunks: Uint8Array[] = [];
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
const recordedBlob = new Blob(chunks, { type: finalMimeType });
setRecordedBlob(recordedBlob);
console.log(`Recording completed. Size: ${recordedBlob.size} bytes, Type: ${finalMimeType}`);
} catch (error) {
console.error('Error reading recorded stream:', error);
} finally {
reader.releaseLock();
}
}
recordingTrackRef.current = null;
}, []);
const downloadRecording = useCallback(() => {
if (!recordedBlob) return;
const url = URL.createObjectURL(recordedBlob);
const a = document.createElement('a');
a.href = url;
a.download = `recording-${Date.now()}.${mimeType.includes('mp4') ? 'mp4' : 'webm'}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, [recordedBlob, mimeType]);
return (
<div>
<div>
<button onclick="{startRecording}" disabled="{isRecording" ||="" !isrecordingsupported()}="">
{isRecording ? 'Recording...' : 'Start Recording'}
</button>
<button onclick="{stopRecording}" disabled="{!isRecording}">
Stop Recording
</button>
</div>
{mimeType && <p>Recording format: {mimeType}</p>}
{recordedBlob && (
<div>
<p>Recording ready! Size: {(recordedBlob.size / 1024 / 1024).toFixed(2)} MB</p>
<button onclick="{downloadRecording}">Download Recording</button>
</div>
)}
{!isRecordingSupported() && (
<p style="{{" color:="" 'red'="" }}="">MediaRecorder is not supported in this browser</p>
)}
</div>
);
};
export default LocalRecorder;</code></pre><br/><p>This component is designed to:</p><ul><li>Start and stop recording smoothly using the <code>MediaRecorder</code> API.</li><li>Handle your recorded data as a Blob and give you the option to download it as an MP4 file.</li><li>Check if your browser supports recording with <code>isRecordingSupported()</code> so you know if it will work.</li></ul><br/><p>If you have any questions or need help tweaking this to better fit your needs, just let me know! I’m here to help you through it.</p>` Sources: src/room/track/LocalTrack.ts | README.md