Hello Support! I have setup a self-hosted vm live...
# ask-ai
r
Hello Support! I have setup a self-hosted vm livekit, and my setup includes a FastAPI livekit_token generator, a livekit agent, a frontend node js app. My issue is whenever I try to join the room on the frontend app, my livekit agent returns the following error:
Copy code
2025-11-25 14:32:56,485 - DEBUG asyncio - Using selector: EpollSelector 
2025-11-25 14:32:56,487 - DEV  livekit.agents - Watching /home/USER/projects/PROJECT_NAME/agents 
2025-11-25 14:33:06,688 - DEBUG asyncio - Using selector: EpollSelector 
/home/USER/projects/PROJECT_NAME/.venv/lib/python3.13/site-packages/livekit/agents/utils/http_server.py:13: DeprecationWarning: loop argument is deprecated
  self._app = web.Application(loop=self._loop)
2025-11-25 14:33:06,695 - INFO livekit.agents - starting worker {"version": "1.2.5", "rtc-version": "1.0.12"}
2025-11-25 14:33:06,695 - INFO livekit.agents - preloading plugins {"packages": ["livekit.plugins.langchain", "livekit.plugins.openai", "livekit.plugins.silero", "livekit.plugins.turn_detector", "av"]}
2025-11-25 14:33:06,696 - INFO livekit.agents - starting inference executor 
2025-11-25 14:33:10,528 - INFO livekit.agents - initializing process {"pid": 4187619, "inference": true}
2025-11-25 14:33:13,275 - DEBUG livekit.agents - initializing inference runner {"runner": "lk_end_of_utterance_multilingual", "pid": 4187619, "inference": true}
None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used.
2025-11-25 14:33:14,620 - INFO livekit.agents - process initialized {"pid": 4187619, "inference": true, "elapsed_time": 4.09}
/home/USER/projects/PROJECT_NAME/.venv/lib/python3.13/site-packages/livekit/agents/utils/http_server.py:26: DeprecationWarning: Application.make_handler(...) is deprecated, use AppRunner API instead
  handler = self._app.make_handler()
2025-11-25 14:33:14,620 - DEBUG livekit.agents - inference runner initialized {"runner": "lk_end_of_utterance_multilingual", "elapsed_time": 1.3442534310743213, "pid": 4187619, "inference": true}
2025-11-25 14:33:14,620 - DEBUG asyncio - Using selector: EpollSelector {"pid": 4187619, "inference": true}
2025-11-25 14:33:14,629 - INFO livekit.agents - registered worker {"id": "AW_XXXXXXXXXXXXXX", "url": "ws://livekit.example.local:7880", "region": "", "protocol": 16}

2025-11-25 14:37:46,862 - INFO livekit.agents - received job request {"job_id": "AJ_XXXXXXXXXXXXXX", "dispatch_id": "AD_XXXXXXXXXXXXXX", "room_name": "room-UUID-REDACTED", "agent_name": "", "resuming": false}
2025-11-25 14:37:46,868 - INFO livekit.agents - initializing process {"pid": 4190560}
2025-11-25 14:37:49,164 - INFO livekit.agents - process initialized {"pid": 4190560, "elapsed_time": 2.3}
2025-11-25 14:37:49,164 - DEBUG asyncio - Using selector: EpollSelector {"pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 14:37:49.171 | DEBUG    | agents.mem0stt:entrypoint:92 - [*] Starting the entrypoint
error: failed to fetch server settings: http status: 404
2025-11-25 14:37:51.908 | DEBUG    | agents.mem0stt:entrypoint:94 - [*] Awaiting connection
2025-11-25 14:37:51.909 | DEBUG    | agents.mem0stt:entrypoint:96 - Found participant: rtc.RemoteParticipant(sid=PA_XXXXXXXXXXXX, identity=user@example.com, name=user@example.com)
2025-11-25 14:37:51.909 | INFO     | agents.mem0stt:entrypoint:98 - user@example.com
2025-11-25 14:37:51,908 - ERROR livekit - livekit_ffi::server::room:149:livekit_ffi::server::room - audio filter cannot be enabled: LiveKit Cloud is required {"pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 14:37:52,079 - INFO mem0.vector_stores.pgvector - Using psycopg2 for PostgreSQL connections {"pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 14:37:52.110 | DEBUG    | src.memory.mem0_memory:__init__:46 - Initialized MemoryEnabledAgent for user_id: user@example.com
2025-11-25 14:37:52.110 | DEBUG    | agents.mem0stt:__init__:51 - Mem0 Agent initialized. Using user_id: user@example.com
2025-11-25 14:37:52,113 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 14:37:52.129 | DEBUG    | src.memory.mem0_memory:search_memory:68 - Searching memory store
2025-11-25 14:37:52,186 - DEBUG livekit.agents - using audio io: `RoomIO` -> `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 14:37:52,186 - DEBUG livekit.agents - using transcript io: `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 14:37:53.579 | DEBUG    | src.memory.mem0_memory:search_memory:68 - Searching memory store
2025-11-25 14:38:21,684 - INFO livekit.agents - process exiting {"reason": "", "pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 14:38:21,683 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false, "pid": 4190560, "job_id": "AJ_XXXXXXXXXXXXXX"}
t
Thanks for reaching out, Josimar. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I reviewed your logs. The key error is: "audio filter cannot be enabled: LiveKit Cloud is required" This means the agent is trying to enable an enhanced noise-cancellation/audio filter (e.g., BVC/NC) that only works on LiveKit Cloud. That feature and certain inference runners are not available on self-hosted servers, so the agent fails when the filter is enabled. What you can do now • Disable noise cancellation in your agent's RoomInputOptions. Example:
Copy code
await session.start(
      room_input_options=RoomInputOptions(
          noise_cancellation=None
      )
  )
Or remove any
noise_cancellation.BVC()
/
noise_cancellation.NC()
usage. • Avoid cloud-only inference/turn-detection runners. Use local VAD instead (for example,
silero.VAD.load()
), and remove any
turn_detection
settings that depend on server/cloud models. • The log also shows ML frameworks missing (PyTorch/TensorFlow/Flax). Those are needed only if you intend to run models locally; disabling cloud features avoids that requirement. Quick clarifying questions 1. Do you intend to remain fully self-hosted, or do you plan to use LiveKit Cloud features? 2. Can you share the code snippet where you create the
AgentSession
/
RoomInputOptions
(or the plugin config) so I can point to the exact line to change? If you confirm you want self-hosted and paste that snippet, I’ll show the minimal edit to stop the error. Sources: Enhanced noise cancellation | LiveKit docs | Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW... | OpenAI and LiveKit partner to turn Advanced Voice into an API | Turn detection and interruptions | LiveKit Docs | Deploying to custom environments | LiveKit Docs
r
Here's my agent python file:
Copy code
from livekit import agents
from livekit.agents import (
    Agent,
    AgentSession,
    ChatContext,
    ChatMessage,
    RoomInputOptions,
)
from livekit.plugins import (
    langchain,
    noise_cancellation,
    openai,
    silero,
)
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from loguru import logger

from src.agent.di_container.agent_container import AgentContainer
from src.config.general.mem0 import LivekitMode, Mem0RuntimeSettings
from src.config.llm.azure_openai import (
    AzureOpenAiBaseSTTSettings,
    AzureOpenAiBaseTTSSettings,
)
from src.memory.mem0_memory import MemoryManager

# TODO fix violations after we have working script:
# agents/mem0_stt.py:32: error: Class cannot subclass "Agent" (has type "Any")  [misc]
# agents/mem0_stt.py:49: error: Need type annotation for "_seen_results" (hint: "_seen_results: set[<type>] = ...")  [var-annotated]
# agents/mem0_stt.py:54: error: Function is missing a return type annotation  [no-untyped-def]
# agents/mem0_stt.py:54: note: Use "-> None" if function does not return a value


class MemoryEnabledAgent(Agent):  # type: ignore[misc]
    """
    An agent that can answer questions using RAG (Retrieval Augmented Generation) with Mem0.
    """

    def __init__(self, user_id: str) -> None:
        super().__init__(
            instructions="""
                You are an intelligent assistant agent working for Astellas, designed to support employees across a wide range of tasks.
                You have deep knowledge about internal tools, processes, teams, and general company information.
                Your responses should be short, clear, and concise. No unnecessary fluff.
                If you're unsure about something, let the user know honestly.
                You're curious and highly interactive, asking thoughtful questions and engaging the user to better understand their needs.
                You can remember past interactions and use them to inform your answers.
                Use semantic memory retrieval to provide contextually relevant responses.
            """,
        )
        self.memory = MemoryManager(user_id=user_id)
        logger.debug(f"Mem0 Agent initialized. Using user_id: {user_id}")

    async def on_enter(self) -> None:
        name_search_results = await self.memory.search_memory("Name of the user")
        language_search_results = await self.memory.search_memory(
            "Preferred language of the user"
        )
        self.session.generate_reply(
            instructions=f"""Briefly greet the user and offer your assistance.
                            Greet using name if you have memories of the user, check these memories: {name_search_results}
                            Greet and talk to the user in preferred language if you have any memories of preferred langauge of the user, check these memories: {language_search_results}
                            If user does not have any preferred language in memories then with greetings ask the user if they want to save any preferred language for communication
                            Communicate with user in their preferred language.
                            Do not reference or infer anything from other memories."""
        )

    async def on_user_turn_completed(
        self, turn_ctx: ChatContext, new_message: ChatMessage
    ) -> None:
        # Persist the user message in Mem0
        logger.debug(f"Adding user message to Mem0: {new_message.text_content}")
        add_result = await self.memory.add_to_memory(new_message.text_content)
        logger.debug(f"Mem0 add result (user): {add_result}")

        # RAG: Retrieve relevant context from Mem0 and inject as assistant message
        logger.debug("About to await mem0_client.search for RAG context")
        search_results = await self.memory.search_memory(new_message.text_content)
        logger.debug(f"mem0_client.search returned: {search_results}")
        if len(search_results) > 0:
            full_context = "\n\n".join(search_results)
            logger.debug(f"Injecting RAG context: {full_context}")
            turn_ctx.add_message(role="assistant", content=full_context)
            await self.update_chat_ctx(turn_ctx)

        await super().on_user_turn_completed(turn_ctx, new_message)


async def entrypoint(
    ctx: agents.JobContext,
) -> None:
    mem0_settings = Mem0RuntimeSettings()  # type: ignore[call-arg,unused-ignore]
    logger.debug("[*] Starting the entrypoint")
    await ctx.connect()
    logger.debug("[*] Awaiting connection")
    participant = await ctx.wait_for_participant()
    logger.debug(f"Found participant: {participant}")
    user_id = participant.identity
    logger.info(user_id)

    agent_container: AgentContainer = AgentContainer()

    if mem0_settings.livekit_mode == LivekitMode.CLOUD:
        noise_cancellation_feature = noise_cancellation.BVC()
    else:
        noise_cancellation_feature = None

    # Initialize STT and TTS configurations
    stt_config = AzureOpenAiBaseSTTSettings()  # type: ignore[call-arg, unused-ignore]
    tts_config = AzureOpenAiBaseTTSSettings()  # type: ignore[call-arg, unused-ignore]
    # https://docs.livekit.io/reference/python/v1/livekit/agents/#livekit.agents.AgentSession
    session: AgentSession = AgentSession(
        stt=openai.STT.with_azure(
            model=stt_config.model_name,
            azure_endpoint=stt_config.endpoint,
            api_key=stt_config.api_key.get_secret_value(),
            api_version=stt_config.api_version,
        ),
        llm=langchain.LLMAdapter(
            graph=agent_container.similarity_search_agent().build()
        ),
        tts=openai.TTS.with_azure(
            model=tts_config.model_name,
            voice=tts_config.voice_type,
            api_key=tts_config.api_key.get_secret_value(),
            azure_endpoint=tts_config.endpoint,
            api_version=tts_config.api_version,
        ),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
    )

    agent = MemoryEnabledAgent(user_id=user_id)

    await session.start(
        room=ctx.room,
        agent=agent,
        room_input_options=RoomInputOptions(
            # LiveKit Cloud enhanced noise cancellation
            # - If self-hosting, omit this parameter
            # - For telephony applications, use `BVCTelephony` for best results
            noise_cancellation=noise_cancellation_feature,
        ),
    )


if __name__ == "__main__":
    agents.cli.run_app(
        agents.WorkerOptions(
            entrypoint_fnc=entrypoint, initialize_process_timeout=200.0
        )
    )
t
Thanks — your code shows the cause: you set
noise_cancellation_feature = noise_cancellation.BVC()
when
mem0_settings.livekit_mode == LivekitMode.CLOUD
. On a self-hosted server that causes the exact error: "audio filter cannot be enabled: LiveKit Cloud is required" What to change (minimal edit) • Ensure
noise_cancellation
is None when self-hosted. Your code already does this via the conditional, but confirm
mem0_settings.livekit_mode
is actually set to
LivekitMode.SELF_HOSTED
(or not
CLOUD
) at runtime. If it’s self-hosted, keep the RoomInputOptions as:
Copy code
room_input_options=RoomInputOptions(
    noise_cancellation=None
)
Other recommendations • Remove or avoid any plugins/config that enable BVC/NC by default. •
turn_detection=MultilingualModel()
and the
lk_end_of_utterance_multilingual
runner may rely on cloud models — if you see issues, replace with local VAD-based detection (you already load
silero.VAD.load()
which is appropriate). • The log about missing PyTorch/TensorFlow indicates local model inference won’t work unless you install those frameworks; that’s only needed if you intend to run models locally. Quick checks for you 1. What is the value of
mem0_settings.livekit_mode
at runtime? 2. If it’s set to CLOUD but you’re self-hosting, change it to your self-hosted mode so
noise_cancellation_feature
becomes
None
. If you paste the runtime value of
mem0_settings.livekit_mode
or confirm you want to stay self-hosted, I’ll give the exact one-line change to ensure the filter is disabled.
r
mem0_settings.livekit_mode is actually equal to "local", meaning the cloud noise cancellation feature is never enabled. What else can I do?
t
Thanks — since
livekit_mode
is "local" but the error still appears, let's narrow the cause and eliminate other cloud-dependent features. Please try these steps and share results/log lines: 1. Temporarily remove/disable all audio-filter and cloud-dependent options in
AgentSession
and `AgentSession.start`: ◦ Set
noise_cancellation=None
explicitly (you already do). ◦ Remove
turn_detection=MultilingualModel()
(comment it out). ◦ Remove any other plugins that might enable filters by default (e.g., cloud inference runners). 1. Start the agent and paste the first ~50 lines of the agent logs after it registers the worker and when it receives the job request (the lines around the error). Look for any line mentioning "audio filter", "inference runner", or "lk_end_of_utterance_multilingual". 2. Verify there are no environment variables or config files enabling cloud features: ◦ Share the value of
mem0_settings
(or its source) — specifically how
livekit_mode
is derived. ◦ Confirm no
LIVEKIT_*
or agent-related env var points to a cloud endpoint. 1. Check the RoomInputOptions object actually passed at runtime: ◦ Add a debug log right before
await session.start(...)
printing
room_input_options
(or
noise_cancellation_feature
) to confirm it is None. If after disabling
turn_detection
and confirming
noise_cancellation
is None you still see the error, paste the requested logs and the printed
room_input_options
output and I’ll identify the next precise change.
r
I disabled noise cancellation, and commented multimodal, but still the same error is observed
t
Thanks — since you've already disabled
noise_cancellation
and commented out multimodal and the error persists, let's narrow down remaining causes and rule out indirect references. Please try these steps and paste the short outputs/log lines requested when you run them: 1) Confirm the actual RoomInputOptions at runtime • Add a debug log immediately before `await session.start(...)`:
Copy code
logger.debug(f"room_input_options: noise_cancellation={noise_cancellation_feature}")
• Restart the agent and paste that single debug line from the logs. 2) Search for any indirect imports/usages of noise cancellation or cloud filters • From your project root run:
Copy code
grep -R "noise_cancellation" -n .
  grep -R "BVC(" -n .
• Paste any matching filenames/lines. 3) Check installed packages (to detect noise-cancellation plugin) • In your agent venv run:
Copy code
pip list | grep -i livekit
• Paste the livekit-related package list. 4) Clear caches and restart • Remove pyc files and restart the worker:
Copy code
find . -name "*.pyc" -delete
  pkill -f agents || true
  # then restart your agent process
• Paste the first 30 log lines after restart around worker registration and job request. 5) If still failing, search for any environment or config indicating Cloud mode • Print the derived setting and any LIVEKIT env vars:
Copy code
python - <<'PY'
  import os
  from src.config.general.mem0 import Mem0RuntimeSettings
  print("LIVEKIT envs:", {k:v for k,v in os.environ.items() if "LIVEKIT" in k})
  print("mem0 livekit_mode:", Mem0RuntimeSettings().livekit_mode)
  PY
• Paste outputs. What I’ll look for when you reply • The debug line proving
noise_cancellation_feature
is None. • Any grep hits showing remaining references. • Whether
livekit-plugins-noise-cancellation
(or similar) is installed. • Log lines showing the exact moment the error appears after restart. If you paste those outputs I’ll point to the exact file or package to remove or the next targeted code change. Sources: Enhanced noise cancellation | LiveKit docs | Voice AI quickstart | LiveKit docs | Noise & echo cancellation | LiveKit docs
r
After disabling noise cancellation everywhere, now I get:
Copy code
2025-11-25 15:08:59,465 - DEBUG asyncio - Using selector: EpollSelector
2025-11-25 15:08:59,467 - DEV  livekit.agents - Watching /home/**user**/repos/**project-backend**/agents
2025-11-25 15:09:08,102 - DEBUG asyncio - Using selector: EpollSelector
/home/**user**/repos/**project-backend**/.venv/lib/python3.13/site-packages/livekit/agents/utils/http_server.py:13: DeprecationWarning: loop argument is deprecated
  self._app = web.Application(loop=self._loop)
2025-11-25 15:09:08,108 - INFO livekit.agents - starting worker {"version": "1.2.5", "rtc-version": "1.0.12"}
2025-11-25 15:09:08,109 - INFO livekit.agents - preloading plugins {"packages": ["livekit.plugins.langchain", "livekit.plugins.openai", "livekit.plugins.silero", "livekit.plugins.turn_detector", "av"]}
2025-11-25 15:09:08,110 - INFO livekit.agents - starting inference executor
2025-11-25 15:09:11,821 - INFO livekit.agents - initializing process {"pid": 19919, "inference": true}
2025-11-25 15:09:13,980 - DEBUG livekit.agents - initializing inference runner {"runner": "lk_end_of_utterance_multilingual", "pid": 19919, "inference": true}
None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used.
2025-11-25 15:09:15,346 - INFO livekit.agents - process initialized {"pid": 19919, "inference": true, "elapsed_time": 3.52}
/home/**user**/repos/**project-backend**/.venv/lib/python3.13/site-packages/livekit/agents/utils/http_server.py:26: DeprecationWarning: Application.make_handler(...) is deprecated, use AppRunner API instead
  handler = self._app.make_handler()
2025-11-25 15:09:15,345 - DEBUG livekit.agents - inference runner initialized {"runner": "lk_end_of_utterance_multilingual", "elapsed_time": 1.365403609815985, "pid": 19919, "inference": true}
2025-11-25 15:09:15,346 - DEBUG asyncio - Using selector: EpollSelector {"pid": 19919, "inference": true}
2025-11-25 15:09:15,355 - INFO livekit.agents - registered worker {"id": "AW_XXXXXX", "url": "ws://livekit.example.local:7880", "region": "", "protocol": 16}
2025-11-25 15:09:37,611 - INFO livekit.agents - received job request {"job_id": "AJ_XXXXXXX", "dispatch_id": "AD_XXXXXXX", "room_name": "room-7346c2ca-f128-4f1a-88b2-7d6d7e73f24c", "agent_name": "", "resuming": false}
2025-11-25 15:09:37,617 - INFO livekit.agents - initializing process {"pid": 20215}
2025-11-25 15:09:39,916 - INFO livekit.agents - process initialized {"pid": 20215, "elapsed_time": 2.3}
2025-11-25 15:09:39,917 - DEBUG asyncio - Using selector: EpollSelector {"pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:09:39.924 | DEBUG    | agents.mem0stt:entrypoint:90 - [*] Starting the entrypoint
2025-11-25 15:09:40.187 | DEBUG    | agents.mem0stt:entrypoint:92 - [*] Awaiting connection
2025-11-25 15:09:40.187 | DEBUG    | agents.mem0stt:entrypoint:94 - Found participant: rtc.RemoteParticipant(sid=PA_XXXXXXXX, identity=user@example.com, name=user@example.com)
2025-11-25 15:09:40.187 | INFO     | agents.mem0stt:entrypoint:96 - user@example.com
2025-11-25 15:09:40,313 - INFO mem0.vector_stores.pgvector - Using psycopg2 for PostgreSQL connections {"pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:09:40.344 | DEBUG    | src.memory.mem0_memory:__init__:46 - Initialized MemoryEnabledAgent for user_id: user@example.com
2025-11-25 15:09:40.344 | DEBUG    | agents.mem0stt:__init__:49 - Mem0 Agent initialized. Using user_id: user@example.com
2025-11-25 15:09:43.003 | DEBUG    | agents.mem0stt:entrypoint:138 - [*] Starting the session
2025-11-25 15:09:43,006 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:09:43.022 | DEBUG    | src.memory.mem0_memory:search_memory:68 - Searching memory store
2025-11-25 15:09:43,065 - DEBUG livekit.agents - using audio io: `RoomIO` -> `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:09:43,065 - DEBUG livekit.agents - using transcript io: `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:09:43.805 | DEBUG    | src.memory.mem0_memory:search_memory:68 - Searching memory store
2025-11-25 15:10:12,683 - INFO livekit.agents - process exiting {"reason": "", "pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:10:12,683 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false, "pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:11:12,684 - ERROR livekit.agents - process did not exit in time, killing process {"pid": 20215, "job_id": "AJ_XXXXXXX"}
2025-11-25 15:11:12,684 - INFO livekit.agents - killing process {"pid": 20215, "job_id": "AJ_XXXXXXX"}
And my frontend app has errors:
Copy code
Received leave request while trying to (re)connect
{
  room: 'room-3453af59-912a-42f9-ab91-fd1c7d01a33c',
  roomID: 'RM_XXXXXXX',
  participant: 'user@example.com',
  pID: 'PA_XXXXXXXXXXX',
  error: ConnectionError: Received leave request while trying to (re)connect
    at SignalClient.<anonymous> (http://localhost:5173/node_modules/.vite/deps/chunk-M6XMSJNE.js:11142:22)
    at Generator.next (<anonymous>)
    at http://localhost:5173/node_modules/.vite/deps/chunk-M6XMSJNE.js:5765:67
    at new Promise (<anonymous>)
    at __awaiter (http://localhost:5173/node_modules/.vite/deps/chunk-M6XMSJNE.js:5747:10)
    at ws.onmessage (http://localhost:5173/node_modules/.vite/deps/chunk-M6XMSJNE.js:11101:37)
}

pID: "PA_XXXXXXXXXXX"
participant: "user@example.com"
room: "room-3453af59-912a-42f9-ab91-fd1c7d01a33c"
roomID: "RM_XXXXXXX"
t
Thanks — given the new logs, two things are happening: 1) The agent job is exiting (then being killed), which causes the room to close. 2) When the frontend tries to reconnect it receives a leave because the room was deleted/closed. Do these three quick checks and paste the outputs you get: 1. Confirm the session start options — add this one-line debug right before
await session.start(...)
and restart the agent:
Copy code
logger.debug(f"room_input_options: close_on_disconnect={close_on_disconnect}, delete_room_on_close={delete_room_on_close}, noise={noise_cancellation_feature}")
Paste that debug line from your logs. 1. Remove preloaded cloud-only plugins — ensure you are NOT importing or preloading
livekit.plugins.turn_detector
anywhere (including indirect imports). From project root run and paste results:
Copy code
grep -R "turn_detector" -n .
grep -R "turn_detection" -n .
1. Prevent room deletion on agent exit — update your
session.start()
call to explicitly set these in
RoomInputOptions
and restart the agent:
Copy code
await session.start(
  room=ctx.room,
  agent=agent,
  room_input_options=RoomInputOptions(
    noise_cancellation=None,
    close_on_disconnect=False,
    delete_room_on_close=False,
  ),
)
After restarting, paste the first ~40 agent log lines from worker registration through the job lifecycle (the section where the job starts and then exits). What I’ll check when you paste those outputs • That the debug line shows
close_on_disconnect=False
and
delete_room_on_close=False
(so room won't be deleted). • Any remaining imports/usages of
turn_detector
or other cloud-only plugins. • The moment and reason the process exits (to identify the underlying crash or timeout). After you share those logs I’ll point to the exact file or package to change or the next targeted setting to fix. Sources: Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW... | Agent session | LiveKit docs
r
Now getting the following on the agent log:
Copy code
2025-11-25 15:26:38,161 - INFO livekit.agents - starting worker {"version": "1.2.5", "rtc-version": "1.0.12"}
2025-11-25 15:26:38,161 - INFO livekit.agents - preloading plugins {"packages": ["livekit.plugins.langchain", "livekit.plugins.openai", "livekit.plugins.silero", "livekit.plugins.turn_detector", "av"]}
2025-11-25 15:26:38,162 - INFO livekit.agents - starting inference executor
2025-11-25 15:26:41,661 - INFO livekit.agents - initializing process {"pid": 31016, "inference": true}
2025-11-25 15:26:43,861 - DEBUG livekit.agents - initializing inference runner {"runner": "lk_end_of_utterance_multilingual", "pid": 31016, "inference": true}
None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used.
2025-11-25 15:26:45,236 - INFO livekit.agents - process initialized {"pid": 31016, "inference": true, "elapsed_time": 3.57}
/home/**user**/repos/personaX-backend/.venv/lib/python3.13/site-packages/livekit/agents/utils/http_server.py:26: DeprecationWarning: Application.make_handler(...) is deprecated, use AppRunner API instead
  handler = self._app.make_handler()
2025-11-25 15:26:45,235 - DEBUG livekit.agents - inference runner initialized {"runner": "lk_end_of_utterance_multilingual", "elapsed_time": 1.3735550730489194, "pid": 31016, "inference": true}
2025-11-25 15:26:45,236 - DEBUG asyncio - Using selector: EpollSelector {"pid": 31016, "inference": true}
2025-11-25 15:26:45,245 - INFO livekit.agents - registered worker {"id": "AW_XXXXXXXXXXXXXX", "url": "ws://livekit.local:7880", "region": "", "protocol": 16}
2025-11-25 15:27:06,107 - INFO livekit.agents - received job request {"job_id": "AJ_XXXXXXXXXXXXXX", "dispatch_id": "AD_XXXXXXXXXXXXXX", "room_name": "room-23c7f7d8-1258-4d8e-9af8-b7dfa116ee97", "agent_name": "", "resuming": false}
2025-11-25 15:27:06,113 - INFO livekit.agents - initializing process {"pid": 31297}
2025-11-25 15:27:08,338 - INFO livekit.agents - process initialized {"pid": 31297, "elapsed_time": 2.22}
2025-11-25 15:27:08,339 - DEBUG asyncio - Using selector: EpollSelector {"pid": 31297, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 15:27:08.346 | DEBUG    | agents.mem0stt:entrypoint:90 - [*] Starting the entrypoint
2025-11-25 15:27:08.404 | DEBUG    | agents.mem0stt:entrypoint:92 - [*] Awaiting connection
2025-11-25 15:27:08.405 | DEBUG    | agents.mem0stt:entrypoint:94 - Found participant: rtc.RemoteParticipant(sid=PA_XXXXXXXXXXX, identity=user@example.com, name=user@example.com)
2025-11-25 15:27:08.405 | INFO     | agents.mem0stt:entrypoint:96 - user@example.com
2025-11-25 15:27:08,530 - INFO mem0.vector_stores.pgvector - Using psycopg2 for PostgreSQL connections {"pid": 31297, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 15:27:08.559 | DEBUG    | src.memory.mem0_memory:__init__:46 - Initialized MemoryEnabledAgent for user_id: user@example.com
2025-11-25 15:27:08.559 | DEBUG    | agents.mem0stt:__init__:49 - Mem0 Agent initialized. Using user_id: user@example.com
2025-11-25 15:27:08.560 | DEBUG    | agents.mem0stt:entrypoint:139 - [*] Starting the session
2025-11-25 15:27:08,562 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 31297, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 15:27:08.571 | DEBUG    | src.memory.mem0_memory:search_memory:68 - Searching memory store
2025-11-25 15:27:08,604 - DEBUG livekit.agents - using audio io: `RoomIO` -> `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 31297, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 15:27:08,604 - DEBUG livekit.agents - using transcript io: `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO` {"pid": 31297, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 15:27:10.254 | DEBUG    | src.memory.mem0_memory:search_memory:68 - Searching memory store
2025-11-25 15:27:40,685 - INFO livekit.agents - process exiting {"reason": "room disconnected", "pid": 31297, "job_id": "AJ_XXXXXXXXXXXXXX"}
2025-11-25 15:27:40,684 - DEBUG livekit.agents - shutting down job task {"reason": "room disconnected", "user_initiated": false, "pid": 31297, "job_id": "AJ_XXXXXXXXXXXXXX"}
And the frontend app containing the following code:
Copy code
import {
  ControlBar,
  RoomAudioRenderer,
  RoomContext,
} from "@livekit/components-react";
import { Room } from "livekit-client";
import "@livekit/components-styles";
import { useState, useEffect } from "react";
import config from "../utils/config";
import MyVideoConference from "../components/livekit/MyVideoConference";
import TranscriptionDisplay from "../components/livekit/Transcription/TranscriptionDisplay";
import { Chat } from "@livekit/components-react";
import { useNavigate } from "react-router-dom";
import { useMsal } from "@azure/msal-react";
import { useAutoLiveKitTimeout } from "../utils/livekitHelpers";

const VoiceAgentPage: React.FC = () => {
  const navigate = useNavigate();
  const liveKitURL = config.liveKitURL;
  const [room, setRoom] = useState<Room | null>(null);
  const [error, setError] = useState<string | null>(null);
  const { accounts } = useMsal();

  // Another useEffect for controlling the logic of when a LiveKit room is disconnected.
  useEffect(() => {
    if (!room) return;

    const handleDisconnect = () => {
      navigate("/");
    };

    room.on("disconnected", handleDisconnect);

    return () => {
      room.off("disconnected", handleDisconnect);
    };
  }, [room, navigate]);

  useEffect(() => {
    let mounted = true;
    const controller = new AbortController();
    const TIMEOUT_MS = 10_000;

    // fail timer: fires if we haven't connected in time
    const failTimer = setTimeout(() => {
      if (!mounted) return;
      setError("Could not join the room in time.");
      controller.abort();
    }, TIMEOUT_MS);

    const fetchTokenAndConnect = async () => {
      try {
        const res = await fetch(config.backendURL + "/livekit_token", {
          signal: controller.signal,
          headers: {
            "Content-Type": "application/json",
            "X-Username": accounts[0].username,
          },
        });

        const data = await res.json();

        if (!mounted || !data?.token) return;
        const newRoom = new Room({
          adaptiveStream: true,
          dynacast: true,
        });

        // race connect against the same timeout window, in case fetch was faster.
        try {
          await Promise.race([
            newRoom.connect(liveKitURL, data.token),
            new Promise<never>((_, reject) =>
              setTimeout(() => reject(new Error("connect-timeout")), TIMEOUT_MS)
            ),
          ]);
        
          // ✅ connected
          console.log("connected");
        } catch (err) {
          // ❌ either connect failed or we timed out
          if (err instanceof Error && err.message === "connect-timeout") {
            console.warn("connection timed out");
          } else {
            console.error("connect failed:", err);
          }
        }

        if (!mounted) {
          newRoom.disconnect();
          return;
        }

        clearTimeout(failTimer); // successfully joined room, so cancel the failure timer.
        setRoom(newRoom);
      } catch (err) {
        if (!mounted) return;

        //set error if we haven't already succeeded...can also redirect here.
        setError("Failed to join the room.");
        console.error("Error fetching token or connecting to room: ", err);
      }
    };

    fetchTokenAndConnect();

    return () => {
      mounted = false;
      clearTimeout(failTimer);
      controller.abort();
      room?.disconnect();
    };
  }, []);

  useAutoLiveKitTimeout(room, {
    idleMs: 60_000,
  });

  if (!room && !error) {
    return (
      <div className="h-screen flex flex-col items-center justify-center bg-neutral-950 text-white">
        <div className="animate-spin rounded-full h-10 w-10 border-4 border-gray-300 border-t-indigo-600"></div>
        <p className="mt-4 text-lg font-medium">Joining the room...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="h-screen flex items-center  justify-center bg-neutral-950 text-white">
        <div className="text-center">
          <p className="text-lg font-semibold">{error}</p>
          <button
            className="mt-4 inline-flex items-center justify-center rounded-2xl bg-indigo-600 px-6 py-3 font-semibold shadow transition hover:bg-indigo-500 focus:outline-non focus:ring-2 focus:ring-indigo-400 focus:ring-offset-2 focus:ring-offset-neutral-950"
            onClick={() => navigate("/")}
          >
            Go Back
          </button>
        </div>
      </div>
    );
  }

  return (
    <RoomContext.Provider value={room!}>
      <div
        className="w-full h-screen flex flex-row bg-neutral-950 text-black px-4 py-4 gap-4"
        data-lk-theme="default"
      >
        {/** Left: Chat */}
        <div className="flex w-[22%] min-w-[240px] h-full">
          <Chat />
        </div>

        {/** Center: Video + Controls */}
        <div className="flex flex-col flex-1 h-full ">
          <div className="flex-1">
            <MyVideoConference />
            <RoomAudioRenderer />
          </div>

          <div>
            <ControlBar className="!border-none" />
          </div>
        </div>

        {/** Right: Transcription */}
        <div className="w-[20%] min-w-[220px] h-full overflow-hidden">
          <TranscriptionDisplay />
        </div>
      </div>
    </RoomContext.Provider>
  );
};

export default VoiceAgentPage;
Returns a timeout error:
Copy code
VoiceAgentPage.tsx:83 connection timed out
fetchTokenAndConnect	@	VoiceAgentPage.tsx:83
await in fetchTokenAndConnect		
(anonymous)	@	VoiceAgentPage.tsx:105
<VoiceAgentPage>
t
Thanks — useful logs. Two things stand out: the agent process exits with reason "room disconnected", and the frontend times out while connecting. Both are linked: the room is being closed or the token/connection is not finishing before the timeout. Here's a focused checklist to fix and diagnose next. 1) Prevent the agent from deleting/closing the room • Ensure you pass these options when starting the session:
Copy code
await session.start(
  room=ctx.room,
  agent=agent,
  room_input_options=RoomInputOptions(
    noise_cancellation=None,
    close_on_disconnect=False,
    delete_room_on_close=False,
  ),
)
• Restart the agent and confirm logs show those values in your debug line. 2) Remove/prevent cloud-only plugin preloads • Your worker still preloads
livekit.plugins.turn_detector
. Remove any import or reference to
turn_detector
so it is not loaded at start (search project for
turn_detector
and
turn_detection
). • Rebuild/restart the agent after removing imports to avoid automatic preloading. 3) Confirm participant is attached to the agent session • Logs show
input stream attached {"participant": null ...}
— that means the agent didn’t attach to the participant audio. Ensure you call
await ctx.wait_for_participant()
and then start the session using that participant (your code does this, but verify ctx.room and participant mapping are correct). • Add a debug right after
wait_for_participant()
printing the participant.sid and ctx.room.name. 4) Increase frontend connect timeout and check token latency • Your frontend times out at 10s. Increase TIMEOUT_MS to 30_000 temporarily. • Log the duration of the token fetch and the time between fetch completion and
newRoom.connect()
to ensure token generation isn't slow. • If token fetch is slow, optimize backend
/livekit_token
or return a token faster. 5) Inspect LiveKit server logs for disconnect reason • On the LiveKit server, watch logs during a connect attempt for lines indicating why it is disconnecting or closing the room (room deletion, duplicate identity, or auth failure). Paste any server log lines mentioning the room or participant if you want me to interpret them. 6) If the agent still exits with "room disconnected" • Reproduce while tailing agent logs and server logs simultaneously. If room is closed by agent, we’ll see agent lifecycle lines; if closed by server, server logs will show the trigger (e.g., duplicate identity or auth error). What to send me next • The debug line showing
room_input_options
values (from your agent logs). • Any grep results for
turn_detector
or
turn_detection
you find. • A short excerpt of your LiveKit server logs during a connect attempt (the lines that mention the room or participant around the same timestamp). I’ll use those to point to the exact import/config to remove or the precise server reason for the disconnect.
r
"delete_room_on_close" is not available as an option in livekit-agents[openai,silero,turn-detector]~=1.0
t
Good catch — thanks for calling that out. Short answer •
delete_room_on_close
is not available in the older
livekit-agents~=1.0
you’re using. That option (and other room-lifecycle improvements) were added in later releases (1.2+). What you can do next (pick one) 1) Upgrade (recommended) • Upgrade
livekit-agents
to v1.2.5 (or any 1.2+ release). That gives you
delete_room_on_close
/ better shutdown handling and avoids needing manual workarounds. • After upgrading, set RoomInputOptions (or RoomOutputOptions if required by the API) when starting the session:
Copy code
RoomInputOptions(
    noise_cancellation=None,
    close_on_disconnect=False,
    delete_room_on_close=False,
  )
• Restart your agent and confirm the agent no longer deletes the room when it exits. 2) If you cannot upgrade right now — workaround • Prevent the room being deleted by managing lifecycle yourself: ◦ Do NOT rely on agent options to keep the room alive. ◦ Before the agent exits, explicitly avoid calling any delete-room behavior from your agent code. ◦ If a room still gets deleted on agent shutdown, recreate it as needed or return a 200 token for a short-lived room and re-create participants after agent restarts. • Or explicitly call the LiveKit server API yourself to control room deletion/creation:
Copy code
from livekit.api import LiveKitAPI
  from livekit.models import DeleteRoomRequest
  api = LiveKitAPI(url=LIVEKIT_URL, api_key=API_KEY, api_secret=API_SECRET)
  await api.room.delete_room(DeleteRoomRequest(room=ctx.room.name))
(Use this only if you need to manually delete; otherwise just avoid calling delete.) 3) Additional actions you should keep doing • Remove any cloud-only plugins (e.g., turn_detector, BVC) so the agent is stable on self-hosted. • Ensure
noise_cancellation=None
and
turn_detection
is not set (or use local VAD). • Increase frontend connect timeout while debugging (e.g., 30s) to rule out slow token generation. • Tail both agent and LiveKit server logs together to confirm whether the server or agent is closing the room. If you want, tell me: • Whether you can upgrade now (I can give the exact pip command and any code changes you’ll need), or • If you must stay on 1.0, I’ll give a minimal pattern to manage room lifecycle manually and prevent sudden room deletions. Sources: Agent session | LiveKit docs | Voice AI quickstart | LiveKit docs | Managing rooms | LiveKit docs | Job lifecycle | LiveKit docs | Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW...
r
If I want to support noise cancellation on my self hosted vm docker compose, what should I do?
t
Short answer: LiveKit’s enhanced AI noise-cancellation (BVC / Krisp) is only available on LiveKit Cloud — it is not provided in the self-hosted server or the official noise-cancellation plugins for Docker Compose. You cannot enable the cloud BVC models on a self-hosted LiveKit instance. What you can do instead (options ranked by effort / quality) 1) Use browser / WebRTC built-in suppression (easy, effective) • Enable echoCancellation, noiseSuppression, autoGainControl in the client:
Copy code
const room = new Room({
  audioCaptureDefaults: {
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },
});
• This runs in the browser and requires no server changes. 2) Add client-side noise filtering (moderate effort) • Integrate a JS/WebAudio noise-suppression library or TF.js model in the browser pipeline before publishing audio. Lower latency than server-side approaches but increases CPU on client devices. 3) Implement agent-side/custom server processing (higher effort) • Run your own noise-suppression model (RNNoise, DeepFilterNet, etc.) in your agent container: ◦ Capture audio frames using the Agents audio APIs or AudioStream. ◦ Process frames through your model (ensure you have low-latency, real-time inference). ◦ Republish cleaned audio into the room. • Requires installing ML runtimes (PyTorch/ONNX/TensorFlow), building/serving the model, and careful performance tuning. 4) Use a dedicated media-proxy or DSP service (engineering + infra) • Insert a media-processing service between clients and LiveKit to apply noise cancellation in real time (e.g., a custom server that receives audio, runs models, then forwards audio). Similar complexity to agent-side processing. 5) Move to LiveKit Cloud (recommended if you need production-quality AI noise cancellation) • LiveKit Cloud offers the licensed BVC/Krisp models and server-side audio filters out-of-the-box. If you require high-quality, low-effort AI noise cancellation, this is the supported path. Practical checklist to proceed • If you want the easiest improvements: enable WebRTC suppression in the client and test. • If you want to build your own model: pick an open-source model (RNNoise / DeepFilterNet), add PyTorch/ONNX to your agent Docker container, implement frame processing and republishing, and measure latency/CPU. • If you prefer not to build: evaluate migrating audio workloads to LiveKit Cloud. If you tell me which path you prefer (browser-only, build agent-side model, or evaluate LiveKit Cloud), I’ll give the exact steps and Docker/package changes and a small code snippet for that approach. Sources: Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW... | Enhanced noise cancellation | LiveKit docs | Noise & echo cancellation | LiveKit docs | Optimizing Video Calls for Low-Powered Devices in LiveKit (JS SDK ≥ v2.14.0...
r
what about the region settings?
t
Good question — here’s how region settings work and what you can do for a self-hosted VM/Docker Compose setup. Key points • Protocol-based region pinning is a LiveKit Cloud feature (not available for self-hosted). You cannot enable LiveKit Cloud region-pinning on a self-hosted server. • For self-hosted, “region” is whatever region your server(s) run in — control residency by where you deploy (cloud region, on-prem site, or edge hosts) and by DNS/network routing. • Agent region setting: when running agents you can set an agent region (CLI flag or service configuration) so the agent advertises a region — useful if you run multiple agent pools in different locations. This does not enable Cloud region-pinning; it just tags/routs agent jobs by region. What to do for common goals • Low latency / locality ◦ Deploy LiveKit + agents in the cloud region or data center nearest your users. ◦ Use region-specific DNS or route users to the correct instance. • Data residency / compliance ◦ Host servers (signaling/media/agents) inside the target country/region and enforce network/DNS policies so traffic does not leave that region. • Multi-region availability (self-hosted) ◦ Run separate LiveKit clusters per region and use your own routing/load-balancer to steer clients to the nearest cluster. ◦ Synchronize any required data between regions via your own services (DB replication, etc.). • Agent placement ◦ Start agents with a region flag to group them by location. That helps your dispatcher or your own job-routing to pick nearby agents. If you were asking about a specific setting or how to configure an agent’s region flag (CLI or code), tell me: • Are you running multiple agent hosts across regions or a single self-hosted cluster? • Do you need instructions for the agent CLI flag, Docker Compose env var, or token-generation routing? Tell me which and I’ll give the exact command/envs or a short docker/CLI example. Sources: Region pinning | LiveKit docs | SIP cloud and region pinning | LiveKit docs | SIP outbound trunk | LiveKit docs | LiveKit Cloud | LiveKit Docs | Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW...
r
On the livekit generated cloud-init code, how can configure caddy to use ssl/tls provided by my issuerer?
t
You can use your own issuer’s TLS certs, but you must replace the cloud-init / generated automatic ACME setup with a custom Caddy config and mount your certs into the Caddy container. Below are the concise steps and exact snippets to do that. 1) Obtain files • certificate: cert.pem (or fullchain.pem) • private key: key.pem • (optional) intermediate bundle: chain.pem 2) Place files in your cloud VM (e.g., /srv/livekit/certs/yourdomain/) • /srv/livekit/certs/yourdomain/cert.pem • /srv/livekit/certs/yourdomain/key.pem • (optional) /srv/livekit/certs/yourdomain/chain.pem 3) Mount certs into the Caddy container • Edit your docker-compose (or cloud-init-generated compose) service for caddy to mount certs and your custom config:
Copy code
services:
    caddy:
      volumes:
        - /srv/livekit/certs/yourdomain/cert.pem:/etc/caddy/certs/cert.pem:ro
        - /srv/livekit/certs/yourdomain/key.pem:/etc/caddy/certs/key.pem:ro
        - ./caddy.yaml:/etc/caddy/caddy.yaml:ro
Adjust paths to match your deployment. 4) Replace automatic ACME in Caddy config with explicit TLS certs • If you use caddy.yaml, set the certificates block or tls directive to point to mounted files. Example minimal TLS directive:
Copy code
apps:
    http:
      servers:
        srv0:
          listen: [":443"]
          routes:
            - match:
                - host: ["livekit.example.com"]
              handle:
                - handler: reverse_proxy
                  upstreams:
                    - dial: "livekit:7880"
          tls:
            certificates:
              - certificate: /etc/caddy/certs/cert.pem
                key: /etc/caddy/certs/key.pem
• If you use a Caddyfile, use:
Copy code
livekit.example.com {
      reverse_proxy livekit:7880
      tls /etc/caddy/certs/cert.pem /etc/caddy/certs/key.pem
  }
5) If you need an intermediate bundle, combine or reference it: • Combine cert + chain into a single file (fullchain.pem) and reference that as
certificate
or first arg in `tls`: cat cert.pem chain.pem > fullchain.pem mount fullchain.pem as cert.pem inside container and reference it. 6) TURN / LiveKit server TLS (if you use TURN over TLS) • LiveKit’s TURN uses its own cert/key in livekit.yaml. If you enable TURN tls_port, set paths to the same certs and mount them into the livekit container: livekit.yaml:
Copy code
turn:
    enabled: true
    tls_port: 5349
    domain: turn.livekit.example.com
    cert_file: /etc/livekit/certs/cert.pem
    key_file: /etc/livekit/certs/key.pem
• Mount those files into the livekit container in docker-compose. 7) Restart containers • docker-compose down && docker-compose up -d (or use systemctl/docker commands per cloud-init) • Verify Caddy logs for successful load and that no ACME challenge runs. 8) Notes and cautions • LiveKit cloud-init generates configs expecting automatic ACME; after you modify, future cloud-init re-generation may overwrite changes. Keep backups or manage overrides outside auto-generated paths. • Ensure file permissions allow Caddy to read the files. • If you keep port 80 open for redirects, Caddy will still listen but won’t attempt ACME if TLS is explicit. • If you later want to revert to ACME, restore the original caddy config and remove the explicit tls entries. If you want, paste your current generated caddy.yaml or docker-compose caddy service block and I’ll give the exact edited snippet to apply. Sources: Deploy to a VM | LiveKit docs
r
This is my cloud_init.ubuntu.yaml part containing
caddy.yaml
configuration, how do I update this to reflect that change:
Copy code
- path: /opt/livekit/caddy.yaml
    content: |
      logging:
        logs:
          default:
            level: INFO
      storage:
        "module": "file_system"
        "root": "/data"
      apps:
        tls:
          certificates:
            automate:
              - livekit-personax-dev.astellasaiservices.com
              - livekit-turn-personax-dev.astellasaiservices.com
              - livekit-whip-personax-dev.astellasaiservices.com
        layer4:
          servers:
            main:
              listen: [":443"]
              routes:
                - match:
                  - tls:
                      sni:
                        - "livekit-turn-personax-dev.astellasaiservices.com"
                  handle:
                    - handler: tls
                    - handler: proxy
                      upstreams:
                        - dial: ["localhost:5349"]
                - match:
                    - tls:
                        sni:
                          - "livekit-personax-dev.astellasaiservices.com"
                  handle:
                    - handler: tls
                      connection_policies:
                        - alpn: ["http/1.1"]
                    - handler: proxy
                      upstreams:
                        - dial: ["localhost:7880"]
                - match:
                    - tls:
                        sni:
                          - "livekit-whip-personax-dev.astellasaiservices.com"
                  handle:
                    - handler: tls
                      connection_policies:
                        - alpn: ["http/1.1"]
                    - handler: proxy
                      upstreams:
                        - dial: ["localhost:8080"]
t
Thanks — below is a minimal, safe edit to your provided
caddy.yaml
that replaces ACME automation with explicit certificate file references, plus the cloud-init steps to place and mount those cert files so Caddy can read them. Important: this disables automatic ACME issuance. Make sure your cert/key files exist on the VM and are readable by the Caddy container. 1) Add cert files on the VM (example paths) • /opt/livekit/certs/livekit-personax-dev.crt (fullchain / cert + intermediates) • /opt/livekit/certs/livekit-personax-dev.key • /opt/livekit/certs/livekit-turn-personax-dev.crt • /opt/livekit/certs/livekit-turn-personax-dev.key • /opt/livekit/certs/livekit-whip-personax-dev.crt • /opt/livekit/certs/livekit-whip-personax-dev.key Put the files in that folder (or another path you control) and ensure permissions allow the docker process to read them (e.g., chown root:root and 0644). 2) Replace your caddy.yaml content with this (keeps same routes, uses explicit certs):
Copy code
logging:
  logs:
    default:
      level: INFO
storage:
  module: "file_system"
  root: "/data"
apps:
  tls:
    certificates:
      certs:
        - certificate: /etc/caddy/certs/livekit-personax-dev.crt
          key: /etc/caddy/certs/livekit-personax-dev.key
        - certificate: /etc/caddy/certs/livekit-turn-personax-dev.crt
          key: /etc/caddy/certs/livekit-turn-personax-dev.key
        - certificate: /etc/caddy/certs/livekit-whip-personax-dev.crt
          key: /etc/caddy/certs/livekit-whip-personax-dev.key
  layer4:
    servers:
      main:
        listen: [":443"]
        routes:
          - match:
              - tls:
                  sni:
                    - "livekit-turn-personax-dev.astellasaiservices.com"
            handle:
              - handler: tls
              - handler: proxy
                upstreams:
                  - dial: ["localhost:5349"]
          - match:
              - tls:
                  sni:
                    - "livekit-personax-dev.astellasaiservices.com"
            handle:
              - handler: tls
                connection_policies:
                  - alpn: ["http/1.1"]
              - handler: proxy
                upstreams:
                  - dial: ["localhost:7880"]
          - match:
              - tls:
                  sni:
                    - "livekit-whip-personax-dev.astellasaiservices.com"
            handle:
              - handler: tls
                connection_policies:
                  - alpn: ["http/1.1"]
              - handler: proxy
                upstreams:
                  - dial: ["localhost:8080"]
3) Update cloud-init to place certs and mount them into the Caddy container • In your cloud-init you already write
/opt/livekit/caddy.yaml
. Also add steps to copy your certs into
/opt/livekit/certs/
(or have your provisioning drop them there). Then ensure docker-compose mounts that path into the caddy container as
/etc/caddy/certs
. Example docker-compose caddy service snippet (ensure your cloud-init writes or updates docker-compose.yml accordingly):
Copy code
services:
  caddy:
    image: caddy:2
    volumes:
      - /opt/livekit/caddy.yaml:/etc/caddy/caddy.yaml:ro
      - /opt/livekit/certs:/etc/caddy/certs:ro
      - caddy_data:/data
      - caddy_config:/config
    ports:
      - "80:80"
      - "443:443"
4) Restart containers • sudo docker-compose down • sudo docker-compose up -d • Check Caddy logs (sudo docker-compose logs -f caddy) for errors loading certs. 5) TURN (TLS) note • If you also configured LiveKit TURN TLS in
livekit.yaml
, ensure the same cert/key paths are mounted into the LiveKit container and
livekit.yaml
points to those container paths (e.g.,
/etc/livekit/certs/...
). 6) Rollback and reminder • Keep a copy of the original generated caddy.yaml — cloud-init regeneration may overwrite your changes. If you want these changes persistent through re-provisioning, integrate them into your cloud-init script: write the certs and the modified caddy.yaml as part of cloud-init user-data. If you’d like, paste the relevant caddy service block from your docker-compose.yml and I’ll return the exact mount lines to insert.