polite-dog-12152
09/09/2025, 7:28 AMtall-airline-16756
09/09/2025, 7:28 AMpolite-dog-12152
09/09/2025, 7:28 AMtall-airline-16756
09/09/2025, 7:29 AMpolite-dog-12152
09/09/2025, 7:29 AMtall-airline-16756
09/09/2025, 7:30 AM@ctx.room.on("disconnected") to handle room disconnection and include room deletion logic—that's definitely a valid and supported approach! Just a quick heads-up: you'll need to explicitly call ctx.delete_room() or use the server API to delete the room, since the disconnection event itself doesn't automatically delete the room or end the session for all participants.
Here's a simple example to help you implement this:
@ctx.room.on("disconnected")
def on_disconnected(reason):
logger.info(f"Disconnected from room: {reason}")
ctx.delete_room() # Explicitly delete the room
Alternatively, if you're looking to handle cleanup specifically for an agent, you might find the session.on("close") event useful to manage room deletion when the agent's session ends:
@session.on("close")
def on_session_close(ev: CloseEvent):
ctx.delete_room()
If you'd like, I’d be happy to guide you through when it’s best to use disconnected versus session.close for deleting rooms, tailored to your specific situation. Just let me know!
Sources: Inside a session | LiveKit Docs | src/agent.ts | examples/basic_room.py | livekit-agents/livekit/agents/ipc/job_proc_lazy_main.py | stream_audio.pypolite-dog-12152
09/09/2025, 7:35 AMtall-airline-16756
09/09/2025, 7:35 AMparticipant_disconnected and disconnected events have their own important roles in LiveKit, and choosing which to use really depends on what you need:
• participant_disconnected: This event fires when a specific participant leaves the room. It’s perfect for handling tasks related to that participant, like saving transcription data linked to them.
• disconnected: This one triggers when the local client disconnects from the room completely. It’s great for room-wide cleanup, such as saving any remaining transcription data, stopping tracks, and resetting the room’s state.
For your situation, using both events makes a lot of sense:
• Use participant_disconnected to save transcription data as each participant leaves.
• Use disconnected to make sure any leftover transcription data is saved and to handle overall cleanup when the room disconnects.
If you’d like, I’m here to help you with how to implement these events together smoothly. Just let me know!
Sources: examples/avatar_agents/audio_wave/avatar_runner.py | examples/demo/demo.ts | lib/src/core/room.dartpolite-dog-12152
09/09/2025, 9:10 AMtall-airline-16756
09/09/2025, 9:11 AMuseLowCPUOptimizer hook to set video quality to LOW when memory or CPU usage is high can make a big difference.
• Manage Logging: Cutting back on logging verbosity, especially INFO-level logs, can help reduce memory usage from logging activities.
• Enable Server Optimizations: Make sure your LiveKit server is up to date to take advantage of built-in optimizations like reduced memory allocation for RTP and probe packets.
• Monitor Agent Memory: If you’re using agent-based apps, memory monitoring tools can be super helpful to set limits and automatically stop processes that go over those limits.
• Fix Memory Leaks: It’s always a good idea to check for any memory leaks in your app or SDKs. Keeping your SDK versions current can help, as they often include important memory leak fixes.
• Optimize Deployment Resources: Lastly, ensuring your deployment environment has enough memory is key. LiveKit generally recommends 8GB of RAM per worker for most voice AI applications.
If you’d like, I’m here to walk you through any of these strategies in more detail—just let me know!
Sources: livekit-agents/livekit/agents/ipc/supervised_proc.py | agents/src/ipc/supervised_proc.ts | Deploying to custom environments | LiveKit Docs | .changes/transceiver-refix | components/media_lib_sal/mem_trace/README.mdpolite-dog-12152
09/09/2025, 9:14 AMtall-airline-16756
09/09/2025, 9:15 AMrtc.AudioStream instead of RecorderIO. This way, you can handle audio snippets smoothly without extra memory overhead from encoding.
• Scale Infrastructure: It’s a good idea to allocate at least 4 CPU cores and 8GB of RAM per worker, and if noise cancellation isn’t essential for your use case, consider turning it off to save memory.
• Leverage SFU Routing: LiveKit’s Selective Forwarding Unit (SFU) helps distribute media efficiently without transcoding, which lightens the processing load.
• Optimize Twilio SIP Trunk: Make sure your Twilio SIP trunk is set up with the right origination URL and credentials to prevent connection retries and orphaned sessions.
By the way, are you currently using features like noise cancellation or full-session recording? Sometimes these can increase memory use. Feel free to reach out if you'd like me to walk you through any of these optimizations in more detail—I’m here to help!
Sources: Speech & Audio Processing | livekit/livekit_composite | DeepWiki | packages/sip--um-actually/src/setup-twilio.ts | Protocol & WebRTC | livekit/livekit_composite | DeepWiki | .env.example | Bringing Zoom's end-to-end optimizations to WebRTCpolite-dog-12152
09/09/2025, 9:28 AMtall-airline-16756
09/09/2025, 9:29 AMrtc.AudioStream instead of RecorderIO can be lighter on memory since it avoids extra encoding and disk writes.
• Improve TTS Speed: Applying time-stretching to TTS output can make audio playback faster without changing the pitch. Choosing TTS models designed for lower latency can also make a big difference.
• Scale Resources: It’s a good idea to allocate at least 4 CPU cores and 8GB RAM per worker. If noise cancellation isn’t essential for your use case, turning it off can save memory too.
• Update Agent Version: Make sure you’re running the latest LiveKit agent (v1.0+), as it includes important fixes for memory leaks and boosts performance.
• Monitor Performance: Keep an eye on LiveKit’s metrics to track latency and memory usage. Key numbers like Time To First Token (TTFT) and overall latency can give you great insights.
If you’d like, I’m here to walk you through any of these steps in more detail or offer advice tailored to your current setup. Just let me know how I can help!
Sources: Voice Assistants | livekit/livekit_composite | DeepWiki | Agent Testing & Evaluation | livekit/livekit_composite | DeepWiki | Agent speech and audio | LiveKit Docs | Agent speech and audio | LiveKit Docs | agents/CHANGELOG.mdpolite-dog-12152
09/10/2025, 6:56 AMtall-airline-16756
09/10/2025, 6:57 AMinitialize_process_timeout=180 looks good for complex setups. Just double-check that this gives enough time to load all necessary models and initialize external services like STT, TTS, and SIP integrations smoothly.
• Optimize Telephony-Specific Events: It’s great to use SIP-specific attributes and lifecycle events to manage telephony workflows effectively. For example, keeping an eye on SIP attributes like sip.phoneNumber and using create_sip_participant for outbound calls can really streamline things.
• Streamline Entry Point: Try to keep your entrypoint function light and delegate heavier initialization tasks to asynchronous handlers. This approach helps reduce any startup delays for your agent.
• Preload Resources: Preloading frequently used models such as VAD, STT, and TTS during initialization can help avoid runtime delays. Using a prewarming function to load these efficiently is a handy trick.
• Monitor Initialization Metrics: Keeping an eye on initialization times and resource usage during startup can reveal any bottlenecks. LiveKit’s telemetry tools are really helpful for collecting these metrics and fine-tuning your setup.
If you’d like, I’d be happy to walk you through any of these strategies in more detail or offer tailored advice for your specific telephony use case. Just let me know!polite-dog-12152
09/13/2025, 4:13 AMtall-airline-16756
09/13/2025, 4:14 AMEgressInfo object includes this ID. If you don’t provide one in your request, LiveKit will automatically generate it for you, and you can find it in the egress_id field in the response.
Here’s a simple example in Python to illustrate:
response = await lkapi.egress.start_room_composite_egress(req)
egress_id = response.egress_id
print(f"Egress ID: {egress_id}")
Additionally, if you want to check the egress IDs for recordings that are currently ongoing or recent, you can use the ListEgress method. This will give you a list of EgressInfo objects, each with its own egress ID.
If you’d like, I’m here to walk you through starting or managing your egress sessions—just let me know how I can assist!
Sources: Docs::Home | Universal Egress | livekit-api/livekit/api/egress_service.py | livekit-api/src/services/egress.rs | packages/livekit-server-sdk/src/EgressClient.tspolite-dog-12152
09/13/2025, 4:15 AMtall-airline-16756
09/13/2025, 4:15 AMegress_id directly in the filepath template for a RoomCompositeEgressRequest isn't possible, but don’t worry—we can work around this by managing the file renaming after the egress session starts.
Here are two friendly approaches you might find helpful:
1. Post-Process File Renaming: You can begin the egress with a placeholder filename. Once the egress starts, grab the egress_id from the EgressInfo response. After the recording finishes, simply rename the file in your storage (like S3) using that egress_id.
2. Store Metadata: Another way is to use the egress_id as a unique key in your database, linking it to where the recording is stored. This means you won’t need to rename files, and you’ll always be able to find your recordings easily.
If you’d like, I’m here to walk you through either of these methods step-by-step—just let me know!
Sources: README.md | Egress output types | LiveKit Docs | rpc/egress.pb.go | livekit-protocol/livekit/protocol/egress.pyipolite-dog-12152
09/13/2025, 4:16 AMtall-airline-16756
09/13/2025, 4:17 AMmanifest.json) saved alongside your recording in your chosen cloud storage (such as S3). This file contains structured information like:
{
"egress_id": "EG_...",
"room_name": "test-room",
"started_at": 1700000000,
"ended_at": 1700003600,
"files": [
{
"filename": "recordings/my-room-test.ogg",
"location": "s3://your-bucket/recordings/my-room-test.ogg"
}
]
}
3. Customize Filenames: You can personalize the filenames by using templating in your egress request (for example, {room_name}-{time}). The manifest will then show those filenames in the files array.
If you'd like, I can guide you step-by-step on how to enable the manifest or how to find and retrieve it from your storage. Just let me know!
Sources: Docs::Home | Egress output types | LiveKit Docs | Docs::Home | Session recording and transcripts | LiveKit Docs | pkg/config/manifest.gopolite-dog-12152
09/13/2025, 4:20 AMtall-airline-16756
09/13/2025, 4:21 AMfrom datetime import datetime
from livekit import api
# Define the filename template
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
filename = f"recording_{timestamp}"
# Create the egress request
req = api.RoomCompositeEgressRequest(
room_name="example-room",
audio_only=True,
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.MP4,
filepath=f"recordings/{filename}.mp4",
s3=api.S3Upload(
access_key="your-aws-access-key",
secret="your-aws-secret-key",
region="your-aws-region",
bucket="your-s3-bucket"
),
),
],
)
# Start the egress
lkapi = api.LiveKitAPI(
url="your-livekit-url",
api_key="your-api-key",
api_secret="your-api-secret"
)
response = await lkapi.egress.start_room_composite_egress(req)
# Retrieve the egress ID
egress_id = response.egress_id
print(f"Egress started with ID: {egress_id}")
With this setup, your recording file will be named recording_{timestamp}.mp4, making it easy to keep everything organized. Plus, you can use the egress ID to track and manage your recording metadata smoothly through your code.
If you’d like, I’m here to help you walk through this setup or answer any questions you might have!polite-dog-12152
09/13/2025, 4:46 AMtall-airline-16756
09/13/2025, 4:47 AMfilepath to match the egress ID. For example:
`{
"file_outputs": [
{
"filepath": "egress_ID.mp4",
"s3": { ... }
}
]
}`This way, both the MP4 file and the manifest file (like egress_ID.json) will share the same base name, making things nice and tidy.
2. Post-Egress Rename: After your recording is done:
This process can be automated smoothly using webhooks or server SDKs.
◦ Grab the EgressInfo response to find the egress ID and file path.
◦ Rename the manifest file ({egress_id}.json) so it matches your MP4 filename ({your_file_name}.mp4).
◦ If needed, re-upload the renamed manifest file.
If you'd like, I’d be happy to share an example script to help automate the renaming, or walk you through implementing these strategies step-by-step. Just let me know how I can assist!
Sources: protobufs/livekit_egress.proto | template-default/public/index.html | Egress API | LiveKit Docs | Egress output types | LiveKit Docspolite-dog-12152
09/13/2025, 4:51 AMtall-airline-16756
09/13/2025, 4:51 AMimport os
import requests
# Example webhook payload (replace with actual webhook data)
webhook_payload = {
"egress_id": "EG_1234567890",
"file_results": [
{
"filename": "recordings/my-room-2023-10-10_12-00-00.mp4",
"location": "s3://your-bucket/recordings/my-room-2023-10-10_12-00-00.mp4"
}
]
}
# Extract details from the webhook payload
egress_id = webhook_payload["egress_id"]
mp4_filename = webhook_payload["file_results"][0]["filename"]
# Derive the manifest file path
manifest_filename = f"recordings/{egress_id}.json"
# Rename the manifest file to match the MP4 filename
new_manifest_filename = mp4_filename.replace(".mp4", ".json")
# Simulate renaming (replace with actual file operations)
print(f"Renaming {manifest_filename} to {new_manifest_filename}")
os.rename(manifest_filename, new_manifest_filename)
# If files are stored in S3, use boto3 to rename
import boto3
s3 = boto3.client("s3")
bucket_name = "your-bucket"
# Copy the manifest file to the new name
s3.copy_object(
Bucket=bucket_name,
CopySource={"Bucket": bucket_name, "Key": manifest_filename},
Key=new_manifest_filename
)
# Delete the old manifest file
s3.delete_object(Bucket=bucket_name, Key=manifest_filename)
print(f"Manifest file renamed and updated in S3: {new_manifest_filename}")
This script is designed with a few assumptions to keep in mind:
• You'll receive a webhook payload when the egress completes.
• The manifest file starts off named using the egress ID (for example, EG_1234567890.json).
• You have access to the storage location, whether that’s a local filesystem or something like S3.
If you’d like, I’m here to help you take the next steps and integrate this smoothly into your workflow. Just let me know!polite-dog-12152
09/13/2025, 7:16 AMtall-airline-16756
09/13/2025, 7:16 AMstarted_at and ended_at timestamps from the SIPCallInfo object. These timestamps are in seconds since the Unix epoch, which makes it easy to calculate how long the call lasted.
2. Track Call Status: Keep an eye on the call_status field in SIPCallInfo. When it switches to "disconnected," that’s your cue to calculate and show the final call duration.
3. Show Live Timer: While the call is ongoing (when call_status is "active"), you can display a live timer by comparing the current time to started_at right in your UI.
4. Backend Integration: If you don’t have direct access to SIPCallInfo on your frontend, no worries! You can expose this info through a backend service that listens to SIP call events using webhooks or by querying LiveKit’s APIs.
If you'd like, I can also provide an example implementation to help you calculate and display the call duration in your frontend. Just let me know!
Sources: LiveKit Docs | rpc/io.pb.go | livekit-protocol/src/livekit.rs | livekit-protocol/livekit/protocol/sip.pyi | SIP APIs | LiveKit Docs