import asyncio import logging from livekit.agents ...
# ask-ai
b
import asyncio import logging from livekit.agents import ( AgentSession, JobContext, JobProcess, UserInputTranscribedEvent, WorkerOptions, cli, metrics, AgentFalseInterruptionEvent, RoomInputOptions, UserStateChangedEvent, MetricsCollectedEvent, ) from livekit.plugins import openai, silero, noise_cancellation from src.api.routes import run_fastapi from src.utils.config import ( LLM_MODEL_NAME, LOG_LEVEL, STT_MODEL_NAME, VoiceConfig, LoadBalancingConfig, ) from src.utils.logger import setup_logging from src.voice_assistant import Assistant from dotenv import load_dotenv from src.utils.tts_provider import create_tts load_dotenv() disconnect_task = None def prewarm(proc: JobProcess) -> None: proc.userdata["vad"] = silero.VAD.load( min_speech_duration=VoiceConfig.min_speech_duration, min_silence_duration=VoiceConfig.min_silence_duration, activation_threshold=VoiceConfig.activation_threshold, force_cpu=VoiceConfig.force_cpu, padding_duration=VoiceConfig.padding_duration, max_buffered_speech=VoiceConfig.max_buffered_speech, ) async def entrypoint(ctx: JobContext) -> None: logger = logging.getLogger("support-assistant") logger.info("Initializing support assistant...") await ctx.connect() tts_instance = create_tts() session = AgentSession( llm=openai.LLM(model=LLM_MODEL_NAME), stt=openai.STT(language=VoiceConfig.language, model=STT_MODEL_NAME), tts=tts_instance, vad=ctx.proc.userdata["vad"], preemptive_generation=True, user_away_timeout=15, ) @session.on("agent_false_interruption") def _on_false_interrupt(ev: AgentFalseInterruptionEvent): logger.info("False positive interruption detected, resuming...") session.generate_reply(instructions=ev.extra_instructions or "") @session.on("user_input_transcribed") def on_user_input_transcribed(event: UserInputTranscribedEvent): logger.info( f"User Transcript: {event.transcript}, identity: {event.speaker_id}" ) usage_collector = metrics.UsageCollector() @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage summary: {summary}") ctx.add_shutdown_callback(log_usage) await session.start( agent=Assistant(room=ctx.room), room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) try: await session.say( "Hi there! I'm Maya, your voice assistant specialized in personalized skincare consultations. " "Are you looking for skincare products, or a gift for someone?", allow_interruptions=False, ) logger.info("Initial greeting delivered to user") except Exception as e: logger.error(f"Failed to deliver greeting: {e}") if name == "__main__": setup_logging() run_fastapi() worker_opts = WorkerOptions( entrypoint_fnc=entrypoint, load_threshold=LoadBalancingConfig.load_threshold, num_idle_processes=LoadBalancingConfig.num_idle_processes, max_retry=LoadBalancingConfig.max_retry, shutdown_process_timeout=LoadBalancingConfig.shutdown_timeout, initialize_process_timeout=LoadBalancingConfig.initialize_timeout, prewarm_fnc=prewarm, ) cli.run_app(worker_opts) this is my app.py file I want that if LIVEKIT API key or secret key is wrong and due to which the livekit can't establish the connection then it should automatically crash the server and exit
t
Thanks for reaching out, Mayank. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I completely understand that you want your server to crash and exit when the LiveKit API key or secret key is incorrect, and I’m here to help you achieve that smoothly. The good news is that the LiveKit SDK has built-in validation that raises exceptions if your credentials are invalid or missing, which is exactly what you need. For instance, the
LiveKitAPI
class will raise a
ValueError
if the API key or secret is missing or empty. To make sure your server behaves as expected, here are a few friendly tips: • Try not to wrap the SDK initialization in a try-except block so the error can naturally cause the crash. • When you’re testing failure scenarios, make sure the environment variables
LIVEKIT_API_KEY
and
LIVEKIT_API_SECRET
are either unset or intentionally invalid. • Avoid setting fallback or default values for these credentials in your code to let the validation do its job. Here’s a simple example to illustrate this:
Copy code
from livekit.api import LiveKitAPI

# Your application will crash here with ValueError if credentials are invalid or missing
lk_api = LiveKitAPI(url="https://your-livekit-url", api_key="", api_secret="")
This way, your server will stop running unless you explicitly catch the error, making the most of the SDK’s helpful fail-fast behavior on invalid configurations. If you have any questions or want to explore this further, I’m here to support you! Sources: frontend/lib/server-utils.ts | livekit-api/livekit/api/livekit_api.py | livekit-agents/livekit/agents/worker.py
b
what changes i have to do
t
I understand you want your server to crash and exit when the LiveKit API key or secret key is incorrect. Let me guide you through the steps to achieve this smoothly: 1. First, try removing any
try-except
blocks that catch exceptions during the LiveKit API initialization. This way, if the credentials are invalid, the exception won’t be caught, and your server will stop as expected. 2. Next, make sure that the
LIVEKIT_API_KEY
and
LIVEKIT_API_SECRET
environment variables are either unset or deliberately set to invalid values for testing—this helps simulate the crash scenario. 3. Also, avoid providing fallback or default values for these keys in your code. For example, instead of using
api_key = os.getenv('LIVEKIT_API_KEY', 'default_key')
, leave it without a default so the error surfaces clearly. Here’s a simple example to illustrate how your code might look:
Copy code
from livekit.api import LiveKitAPI\n\n# This will raise a ValueError and crash the server if credentials are invalid\nlk_api = LiveKitAPI(url="https://your-livekit-url", api_key="", api_secret="")
By following these steps, your server will automatically terminate if the credentials are incorrect or missing. If you run into any issues or want to chat more about this, I’m here to help!
b
does WorkerOptions throws any execption? can i catch it
t
I’m glad you asked about the
WorkerOptions
class! It’s good to know that this class itself doesn’t throw exceptions during instantiation since it mainly sets up configurations. However, when you use the
Worker
class with
WorkerOptions
, there might be some exceptions during initialization or while it’s running. The great news is you can catch these in your application to keep things running smoothly. Here are a few exceptions you might encounter: • ValueError: This happens if some required credentials, like your API key or secret, are missing or invalid when you start up. • RuntimeError: This can occur if the worker can’t connect to LiveKit even after trying multiple times. • WorkerError: This is thrown if the worker fails to connect or if it’s already running. • AssignmentTimeoutError: Raised when a job assignment takes too long and times out. To handle these gracefully, you can wrap your code in a
try-except
block. Here’s a simple example to guide you:
Copy code
from livekit.agents import Worker, WorkerOptions\n\ntry:\n    worker = Worker(WorkerOptions(...))\n    worker.run()\nexcept ValueError as e:\n    print(f\"Initialization error: {e}\")\nexcept RuntimeError as e:\n    print(f\"Runtime error: {e}\")
This way, you’re prepared to catch errors and decide whether to handle them or stop the server, making your application more reliable. If you have any more questions or need further help, I’m here for you! Sources: README.md | livekit-agents/livekit/agents/cli/_run.py
b
can you write this code in my code
t
I'd love to help you integrate exception handling into your existing code so that your server can either handle errors smoothly or exit gracefully if the LiveKit API key or secret key isn't quite right. Here's a friendly example you can follow:
Copy code
from livekit.agents import Worker, WorkerOptions
from livekit.api import LiveKitAPI
import logging

def setup_worker():
    try:
        # Initialize WorkerOptions
        worker_opts = WorkerOptions(
            entrypoint_fnc=entrypoint,
            load_threshold=LoadBalancingConfig.load_threshold,
            num_idle_processes=LoadBalancingConfig.num_idle_processes,
            max_retry=LoadBalancingConfig.max_retry,
            shutdown_process_timeout=LoadBalancingConfig.shutdown_timeout,
            initialize_process_timeout=LoadBalancingConfig.initialize_timeout,
            prewarm_fnc=prewarm,
        )

        # Initialize Worker
        worker = Worker(worker_opts)
        worker.run()

    except ValueError as e:
        logging.error(f"Initialization error: {e}")
        raise SystemExit("Server exiting due to invalid LiveKit credentials.")

    except RuntimeError as e:
        logging.error(f"Runtime error: {e}")
        raise SystemExit("Server exiting due to runtime error.")

    except Exception as e:
        logging.error(f"Unexpected error: {e}")
        raise SystemExit("Server exiting due to an unexpected error.")

if __name__ == "__main__":
    setup_logging()
    run_fastapi()
    setup_worker()
This approach helps catch any problems with your LiveKit API credentials or worker setup, logs them clearly, and then stops the server safely. If you have any questions or want to tweak this further, feel free to ask—I'm here to support you every step of the way!
b
C\Users\mayanksingh01\Desktop\livekit\cashmere ai support agent\app.py153: RuntimeWarning: coroutine 'Worker.run' was never awaited worker.run() RuntimeWarning: Enable tracemalloc to get the object allocation traceback
t
It looks like the error happens because
Worker.run()
is a coroutine and needs to be awaited. To resolve this, you’ll want to use
await
when calling
worker.run()
. Since your main function isn’t asynchronous, a great way to handle this is by using
asyncio.run
to properly run the coroutine. Here’s an updated version of your code that should help:
Copy code
import asyncio
from livekit.agents import Worker, WorkerOptions
from livekit.api import LiveKitAPI
import logging

async def setup_worker():
    try:
        # Initialize WorkerOptions
        worker_opts = WorkerOptions(
            entrypoint_fnc=entrypoint,
            load_threshold=LoadBalancingConfig.load_threshold,
            num_idle_processes=LoadBalancingConfig.num_idle_processes,
            max_retry=LoadBalancingConfig.max_retry,
            shutdown_process_timeout=LoadBalancingConfig.shutdown_timeout,
            initialize_process_timeout=LoadBalancingConfig.initialize_timeout,
            prewarm_fnc=prewarm,
        )

        # Initialize Worker
        worker = Worker(worker_opts)
        await worker.run()

    except ValueError as e:
        logging.error(f\"Initialization error: {e}\")
        raise SystemExit(\"Server exiting due to invalid LiveKit credentials.\")

    except RuntimeError as e:
        logging.error(f\"Runtime error: {e}\")
        raise SystemExit(\"Server exiting due to runtime error.\")

    except Exception as e:
        logging.error(f\"Unexpected error: {e}\")
        raise SystemExit(\"Server exiting due to an unexpected error.\")

if __name__ == \"__main__\":
    setup_logging()
    run_fastapi()
    asyncio.run(setup_worker())
This way, the coroutine gets awaited properly, and you won’t see that
RuntimeWarning
anymore. If you have any questions or want to walk through this together, I’m here to help!