@ctx.room.on("disconnected") async def on_...
# ask-ai
p
@ctx.room.on("disconnected") async def on_room_disconnected(): """Handle room disconnect - ensure transcription is saved""" await lkapi.room.delete_room(api.DeleteRoomRequest(ctx.room.name))
t
Thanks for reaching out, arpan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
p
is this ok @ctx.room.on("disconnected") async def on_room_disconnected(): """Handle room disconnect - ensure transcription is saved""" await lkapi.room.delete_room(api.DeleteRoomRequest(ctx.room.name))
t
Could you please help me understand a bit better? Are you wondering if this code snippet is syntactically correct, or are you asking if it follows LiveKit's best practices for handling room disconnections and deleting rooms? I’m here to help with whichever you need!
p
yes
t
It's great that you're using
@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:
Copy code
@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:
Copy code
@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.py
p
whitch is beetter option use both or any one # Handle session end and participant disconnect @ctx.room.on("participant_disconnected") async def on_participant_disconnected(participant): """Handle participant disconnect - save transcription to MongoDB""" if current_call_id and transcription_logger: print(f"📞 Participant disconnected - saving transcription for call {current_call_id}") transcriptions = transcription_logger.close_transcription() caller_info.end_call(current_call_id,transcriptions) transcription_logger.remove_txt() print(f"✅ Call {current_call_id} ended and transcription saved to MongoDB") # # Handle room disconnect @ctx.room.on("disconnected") def on_room_disconnected(): """Handle room disconnect - ensure transcription is saved""" if current_call_id and transcription_logger: print(f"🏠 Room disconnected - saving transcription for call {current_call_id}") transcriptions = transcription_logger.close_transcription() caller_info.end_call(current_call_id,transcriptions) transcription_logger.remove_txt() print(f"✅ Call {current_call_id} ended and transcription saved to MongoDB")
t
Both
participant_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.dart
p
in my app it taking 1gb of memory hoe to reduce it
t
I’m glad you reached out! To help reduce memory usage in your LiveKit application, here are some friendly tips you might find useful: • Optimize Video Quality: Try lowering the video quality settings to ease the memory load from video processing. For instance, using the
useLowCPUOptimizer
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.md
p
i am using audio telephonic using twilo
t
To help you get the best memory usage for your audio telephony application with Twilio and LiveKit, here are some friendly tips you might find useful: • Enable Opus DTX: Turning on Opus Discontinuous Transmission (DTX) can really help by reducing the audio bitrate during silent moments, which means less memory and bandwidth use. • Use Lightweight Audio Processing: For short audio buffering, try using
rtc.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 WebRTC
p
this is my agent if i want fast response import sys import os import uuid import asyncio from datetime import datetime from livekit import api from livekit.agents import Agent, JobContext, AgentSession, metrics, MetricsCollectedEvent, RoomInputOptions, ChatContext, AutoSubscribe from livekit.agents.llm import function_tool from livekit.plugins import silero, noise_cancellation import base64 from livekit.agents.telemetry import set_tracer_provider from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.sdk.trace import TracerProvider from opentelemetry.util.types import AttributeValue import time import requests from livekit import rtc from dotenv import load_dotenv # Load environment variables load_dotenv() from src.utils.logger import logging from src.utils.exception import CustomException from src.pipeline.agentic_rag_pipeline import AgenticRAG from src.prompt.voice_agent_prompt import get_language_agent from src.constants.model_request_config import ModelConfig from src.voice_agent.transcription_logger import TranscriptionLogger from src.voice_agent.call_logger import CallLogger last_user_activity = time.time() # Create a mock Tool class for testing class Tool: def run(self, input_data): return {"generation": f"Mock response for: {input_data.get('user_transcript', 'No query')}"} # Model configuration model_config = ModelConfig() usage_collector = metrics.UsageCollector() def setup_langfuse( host: str | None = None, public_key: str | None = None, secret_key: str | None = None, metadata: dict | None = None ): public_key = public_key or os.getenv("LANGFUSE_PUBLIC_KEY") secret_key = secret_key or os.getenv("LANGFUSE_SECRET_KEY") host = host or os.getenv("LANGFUSE_HOST") if not public_key or not secret_key or not host: raise ValueError("LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and LANGFUSE_HOST must be set") langfuse_auth = base64.b64encode(f"{public_key}:{secret_key}".encode()).decode() os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = f"{host.rstrip('/')}/api/public/otel" os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {langfuse_auth}" trace_provider = TracerProvider() trace_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) set_tracer_provider(trace_provider) return async def handle_inbound_call(room_id): # Generate a unique room name for the inbound call room_name = f"inbound-call-{room_id}" agent_name = "voice-agent" # Initialize LiveKit API client lkapi = api.LiveKitAPI( url=os.getenv("LIVEKIT_URL"), api_key=os.getenv("LIVEKIT_API_KEY"), api_secret=os.getenv("LIVEKIT_API_SECRET"), ) # Create an agent dispatch for the room dispatch = await lkapi.agent_dispatch.create_dispatch( api.CreateAgentDispatchRequest( agent_name=agent_name, room=room_name, metadata=f'{{"room_id": "{room_id}"}}' ) ) print("Created dispatch for inbound call:", dispatch) # List all dispatches in the room dispatches = await lkapi.agent_dispatch.list_dispatch(room_name=room_name) print(f"There are {len(dispatches)} dispatches in {room_name}") await lkapi.aclose() async def entrypoint(ctx: JobContext): """Main entrypoint for the LiveKit agent""" try: room_id = str(uuid.uuid4()) print(room_id) await handle_inbound_call(room_id=room_id) # Set up Langfuse trace_provider = setup_langfuse( metadata={ "langfuse.session.id": ctx.room.name, "langfuse.session": ctx.room.metadata, } ) # Set up recording req = api.RoomCompositeEgressRequest( room_name=ctx.room.name, audio_only=True, file_outputs=[ api.EncodedFileOutput( file_type=api.EncodedFileType.MP4, filepath=f"recordings/{datetime.now().strftime('%Y-%m-%d')}", s3=api.S3Upload( access_key=os.getenv("AWS_ACCESS_KEY_ID"), secret=os.getenv("AWS_SECRET_ACCESS_KEY"), region=os.getenv("AWS_REGION"), bucket="holionix-voice-agent" ), ), ], ) lkapi = api.LiveKitAPI() await lkapi.egress.start_room_composite_egress(req) print("🚀 Starting LiveKit agent...") await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY) print("✅ Agent created with tools") print("✅ Connecting to room") # Create the information tool info_tool = create_tool_function() print("✅ Information tool created") # Prompts instruction = get_language_agent( industry=model_config.get_behaviors()['industry'], response_style=model_config.get_behaviors().get('response_style'), personality=model_config.get_behaviors().get('personality'), dialect=model_config.get_behaviors().get('dialect'), ) # Wait for participant print("⏳ Waiting for participant...") participant = await ctx.wait_for_participant() # Initialize transcription logger transcription_logger = TranscriptionLogger( mongo_uri=os.getenv("MONOGO_DB_URI"), db_name=os.getenv("MONGODB_DB_NAME_TRANSCRIPTION") ) # Intilaize call info logger caller_info= CallLogger( mongo_uri=os.getenv("MONOGO_DB_URI"), db_name="caller_info" ) # Create session with error handling for each component print("🔧 Creating session components...") try: vad = silero.VAD.load() print("✅ VAD loaded") models = model_config.get_models() stt = models.get('stt') print("✅ STT configured") llm = models.get('llm') print("✅ LLM configured") tts = models.get('tts') except Exception as e: print(f"❌ TTS error: {e}") raise CustomException(e,sys) print("✅ Session created") session = AgentSession( use_tts_aligned_transcript=True, preemptive_generation=True ) print("✅ Transcription logging set up") # Set up transcription logging # Check if this is a SIP call and initialize logging is_sip_call = ( hasattr(participant, 'kind') and participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP ) current_call_id = caller_info.start_call(participant) # Start transcription logging for both SIP and web calls if current_call_id: call_type = "SIP" if is_sip_call else "WEB" print(f"📞 {call_type} Call detected - Call ID: {current_call_id}") if is_sip_call: print(f"📱 Caller: {participant.attributes.get('sip.phoneNumber', 'Unknown')}") transcription_logger.start_transcription(session_id=current_call_id, room_id=room_id, session=session, mode=call_type) logging.info(f"Call logging started for call ID: {current_call_id}") else: print("⚠️ Failed to start call logging") agent = Agent( instructions=instruction, stt=stt, llm=llm, tools=[info_tool], vad=vad, tts=tts ) # Start the session await session.start(agent=agent, room=ctx.room,room_input_options=RoomInputOptions(close_on_disconnect=False,noise_cancellation=noise_cancellation.BVCTelephony()),) print("✅ Session started") print("✅ Initial greeting sent") print("🎙️ Agent is now active and listening...") logging.info("Agent is now active and listening...") # Send initial greeting await session.generate_reply(instructions="Hello! How can I assist you today?") # Set up comprehensive transcription event handlers @session.on("user_speech_committed") def on_user_speech(event): """Handle user speech transcription""" if transcription_logger and hasattr(event, 'user_transcript') and event.user_transcript: transcription_logger.log_user_speech(event.user_transcript) @session.on("agent_speech_committed") def on_agent_speech(event): """Handle agent speech transcription""" if transcription_logger and hasattr(event, 'agent_transcript') and event.agent_transcript: transcription_logger.log_agent_response(event.agent_transcript) # Additional event handlers for comprehensive logging @session.on("conversation_item_added") def on_conversation_item(event): """Handle conversation items (covers both user and agent messages)""" if transcription_logger and hasattr(event, 'item'): item = event.item if hasattr(item, 'content') and item.content: # Determine speaker based on item type or role speaker = "USER" if hasattr(item, 'role') and item.role == 'user' else "AGENT" transcription_logger.log_transcription(item.content, is_final=True, speaker=speaker) # # Handle room disconnect @ctx.room.on("disconnected") def on_room_disconnected(): """Handle room disconnect - ensure transcription is saved""" if current_call_id and transcription_logger: print(f"🏠 Room disconnected - saving transcription for call {current_call_id}") transcriptions = transcription_logger.close_transcription() caller_info.end_call(current_call_id,transcriptions) transcription_logger.remove_txt() print(f"✅ Call {current_call_id} ended and transcription saved to MongoDB") ctx.delete_room() print(f"✅ Room Deleted") async def flush_trace(): trace_provider.force_flush() ctx.add_shutdown_callback(flush_trace) ctx.add_shutdown_callback(log_usage) await lkapi.aclose() except Exception as e: error_msg = f"Voice agent error: {e}" print(f"❌ {error_msg}") logging.error(error_msg) raise CustomException(e, sys)
t
To help your LiveKit agent respond faster and use less memory in your audio telephony application, here are some friendly tips you might find useful: • Reduce Latency: Try placing the agent close to your LLM, STT, and TTS services. This helps cut down on network delays. Also, enabling streaming APIs can allow for incremental processing and even start generating responses sooner by overlapping tasks. • Optimize Audio Processing: For short audio snippets, using
rtc.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.md
p
import asyncio from src.pipeline.voice_agent_pipeline import entrypoint from livekit import agents if name == "__main__": from livekit.agents import cli, WorkerOptions asyncio.run(cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint,agent_name="telephony_agent",initialize_process_timeout=180)))
t
To help you get the most out of your LiveKit agent initialization and entrypoint for telephony applications, here are some friendly tips you might find useful: • Increase Initialization Timeout: Your current
initialize_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!
p
how to get recording engress id
t
I'm happy to help you understand how the recording egress ID works in LiveKit! When you start an egress session, the
EgressInfo
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:
Copy code
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.ts
p
this code i want file name with engress id req = api.RoomCompositeEgressRequest( room_name=ctx.room.name, audio_only=True, file_outputs=[ api.EncodedFileOutput( file_type=api.EncodedFileType.MP4, filepath=f"recordings/{datetime.now().strftime('%Y-%m-%d %H-%M-%S')}", s3=api.S3Upload( access_key=os.getenv("AWS_ACCESS_KEY_ID"), secret=os.getenv("AWS_SECRET_ACCESS_KEY"), region=os.getenv("AWS_REGION"), bucket="holionix-voice-agent" ), ), ], )
t
I understand that including the
egress_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.pyi
p
i want to acces json data of each recodins with file name
t
I'd be happy to help you access the JSON data containing the filename for each recording in LiveKit. Here's a simple way to do it: 1. Enable Manifest Creation: LiveKit usually creates a manifest file for egress recordings automatically, unless you choose to disable it. This JSON file holds important details like the filename, where it's stored, timestamps, the room name, and the egress ID. 2. Retrieve the Manifest: Once your recording finishes, you'll find the manifest file (like
manifest.json
) saved alongside your recording in your chosen cloud storage (such as S3). This file contains structured information like:
Copy code
{
  "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.go
p
can you example code recodings name and json name same
t
To help you keep the recording filename and its metadata perfectly in sync, it’s a great idea to use a consistent naming convention for your recording files. Here’s a friendly example to guide you:
Copy code
from 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!
p
i want json file and recoding mp4 fike name same
t
Hi there! I understand you're looking to have the JSON manifest file and the MP4 recording file share the exact same name in LiveKit. While LiveKit doesn't support this natively through configuration, no worries—we can definitely work around it with a couple of helpful strategies: 1. Use Egress ID as the Base Name: You can set the MP4
filepath
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 Docs
p
code example
t
Here’s a helpful example Python script to align the JSON manifest file and MP4 recording file names by renaming the manifest after the recording completes:
Copy code
import 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!
p
i am using tel call in fornted i want to show call duration
t
I'd be happy to help you display call duration for telephony calls in your LiveKit frontend! Here’s a simple way to approach it: 1. Retrieve Call Start and End Times: You can use the
started_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