I have implemented Livekit Workflows with multi ag...
# ask-ai
w
I have implemented Livekit Workflows with multi agent and it has caused the memory consumption to be extremely high. I have ensured that I dont have any dangling async tasks, event listeners but the issue still persists. On looking at HTOP , i could see a lot of threads and processes spinning up. Memory consumption is high in a single agent flow as well but not remotely as close to the workflows impelementation. the memory consumptions becomes so high that instance is crashing. What could be going wrong here? I have implemented the workflows based on the recipes available on github for workflows.
t
Thanks for reaching out, jaswant. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand that high memory consumption in LiveKit workflows with multi-agent setups can be quite challenging. Let’s walk through some common reasons this might happen and how we can address them together: • Resource-Intensive Features: Features like enhanced noise cancellation or turn detectors are fantastic but can use a lot of memory, especially when many tasks run at once. • Concurrency and Worker Load: Ideally, one worker should manage about 10–25 concurrent jobs. Going beyond that might cause memory to spike. • Model Usage Per Agent: If multiple STT, LLM, or TTS models run across agents, memory use can increase due to duplicated instances. • State and Context Propagation: Sending full chat histories during agent handoffs can build up data in memory over time. • Inefficient Memory Monitoring: It’s important to use the latest LiveKit Agents SDK to ensure accurate memory tracking. Here are some friendly tips to help manage memory effectively: • Start with 4 CPU cores and 8GB RAM per worker for voice AI applications. • Keep an eye on performance when under load and adjust the number of workers as needed. • Try to reuse model instances when you can, avoiding unnecessary re-initializations. • Pass only the essential context during agent handoffs instead of the entire chat history. If you'd like, I’m here to help you profile memory usage or optimize a specific agent workflow. Just let me know how I can support you! Sources: main.py | agents/CHANGELOG.md | Deploying to custom environments | LiveKit Docs | Deploying to custom environments | LiveKit docs | examples/voice_agents/multi_agent.py
w
Copy code
class WorkflowBaseAgent(Agent):
    def __init__(self, instructions: str = ""):
        super().__init__(instructions=instructions)
        # Initialize CallEvents once per agent instance, not on every on_enter
        self.call_events = CallEvents()
        self.participant: rtc.RemoteParticipant | None = None
        self.last_speaker = None
        # Note: Silence detection is now handled by user_away_timeout in AgentSession
        # These values are kept for reference but not used for timer management
        self._silence_nudge_after_s: int = 20
        self._silence_hang_after_s: int = 15
        self.console_mode: bool = False

    async def on_enter(self) -> None:
        agent_name = self.__class__.__name__
        logger.info(f"Entering workflow: {agent_name}")

        userdata: UserData = self.session.userdata
        userdata.due_date_words = date_to_words(userdata.due_date)
        userdata.minimum_amount_pending = float(userdata.amount_pending) * 0.5
        userdata.minimum_amount_pending_words = convert_to_english_words(
            amount=userdata.minimum_amount_pending
        )

        # Note: Silence detection is now handled by user_away_timeout in AgentSession
        self._silence_nudge_after_s = userdata.silence_nudge_after_s
        self._silence_hang_after_s = userdata.silence_hang_after_s
        self.console_mode = userdata.console_mode
        # CallEvents already initialized in __init__, no need to recreate

        # Only copy chat_ctx if we need to modify it, otherwise use directly
        # Since we're adding a system message, we do need a copy to avoid mutating shared state
        chat_ctx = self.chat_ctx.copy()
        chat_ctx.add_message(role="system", content=get_global_instructions(userdata))
        await self.update_chat_ctx(chat_ctx)
        await self.session.generate_reply()

    def set_participant(self, participant: rtc.RemoteParticipant):
        self.participant = participant

    async def _transfer_to_agent(self, context: RunContext_T, agent_key: str) -> Agent:
        userdata = context.userdata
        # Lazy-load agent if not already created
        if agent_key not in userdata.agents:
            userdata.agents[agent_key] = _create_agent_by_key(agent_key)
        current_agent = context.session.current_agent
        next_agent = userdata.agents[agent_key]
        userdata.prev_agent = current_agent
        return next_agent

    async def hangup(self, delete_room: bool = True):
        """Hangup method compatible with BaseVoiceAgent interface."""
        logger.info("Hanging up the call")
        job = get_job_context()
        try:
            if delete_room and not getattr(self, "console_mode", False):
                try:
                    await job.api.room.delete_room(api.DeleteRoomRequest(room=job.room.name))
                    logger.debug("Room deleted successfully")
                except Exception as e:
                    logger.warning(f"Could not delete room: {e}")
        finally:
            # Note: Silence timer cleanup is handled by user_away_timeout framework
            pass
        job.shutdown()

    async def end_call_without_ctx(self) -> str | None:
      
        logger.info("end_call_without_ctx function called")
        await self.session.say(
            text="I haven't heard you for a while, so I will end the call now. Goodbye!",
            allow_interruptions=False,
        )
        await self.hangup(delete_room=False)
        return None

    async def on_user_turn_completed(self, turn_ctx, new_message) -> None:
        text = new_message.text_content.strip()
        if text:
            logger.debug("User spoke", text=text)
            # Note: Silence detection is now handled by user_away_timeout
            # User speaking will automatically reset the away state
            self.last_speaker = "user"
t
It looks like the
WorkflowBaseAgent
implementation you shared might be custom or tailored to your setup. Could you please let me know if this is based on a specific LiveKit example or if it’s part of your own code? Also, are there any particular parts of this implementation where you’re noticing memory inefficiencies—maybe during agent transitions, context handling, or how the model is being used? I’m here to help you work through this! Sources: lerobot/common/utils/buffer.py | Deploying to custom environments | LiveKit docs | Deploying to custom environments | LiveKit Docs | complex-agents/role-playing/agents/base_agent.py
w
its part of my own code, I have referred to github recipes on workflows. I have not yet profiled the memory but trying to figure what in my code could possible cause such high usage of memory. I create an initial agent that inherits from Workflow Base Agent and attach it to the AgentSession that is all.
t
High memory usage in custom LiveKit agent implementations inheriting from
WorkflowBaseAgent
and using
AgentSession
can happen for a few reasons, and I’m here to help you understand them better: • Turn Detection Models: Multilingual models typically need around 400MB of RAM, while English-only models use about 200MB. If you don’t need multilingual support, switching to the lighter model might be a great way to save memory. • Preemptive Generation: Speculative LLM and TTS requests can increase memory usage. If low latency isn’t a must for your use case, you might consider disabling
preemptive_generation
to help reduce memory load. • Concurrent Sessions: Keep in mind that each session loads multiple AI models (like STT, LLM, TTS), so memory usage can add up quickly when you have many sessions running at once. • Memory Monitoring: LiveKit offers built-in process supervision where you can set memory thresholds (
memoryWarnMB
and
memoryLimitMB
) to catch and handle any processes using too much memory. • Resource Cleanup: It’s really important to manage your session lifecycle properly by calling
session.drain()
and registering cleanup tasks with
JobContext.add_shutdown_callback()
to free up resources when they’re no longer needed. To help optimize memory usage, here are some practical tips: • Start with a baseline of 4 CPU cores and 8GB RAM per worker for voice AI applications. • Keep an eye on memory usage using tools like
pidusage
or LiveKit’s built-in metrics collection. • Consider deploying with autoscaling and load balancing so the load is shared efficiently. • Review your plugins and models, and remove any that aren’t being used to lighten the load. If you’d like, I’m happy to walk you through profiling your memory usage or help you with specific steps to apply these optimizations. Just let me know! Sources: examples/voice_agents/basic_agent.py | agents/src/ipc/supervised_proc.ts | Deploying to custom environments | LiveKit docs | CLI Tools & Token Management | livekit/livekit_composite | DeepWiki | Deploy and scale agents on LiveKit Cloud
w
• Memory Monitoring: LiveKit offers built-in process supervision where you can set memory thresholds (
memoryWarnMB
and
memoryLimitMB
) to catch and handle any processes using too much memory. help me set this up ?
t
Let's walk through how to set up
memoryWarnMB
and
memoryLimitMB
for memory monitoring in LiveKit together. Here’s a simple guide to help you: • JobProcExecutor: You can pass the memory thresholds as arguments when creating the executor, like this:
Copy code
const executor = new JobProcExecutor(
  agent,
  inferenceExecutor,
  initializeTimeout,
  closeTimeout,
  memoryWarnMB,      // e.g., 512 (MB)
  memoryLimitMB,     // e.g., 1024 (MB)
  pingInterval,
  pingTimeout,
  highPingThreshold
);
• InferenceProcExecutor: Just include these values in the options:
Copy code
const inferenceExecutor = new InferenceProcExecutor({
  runners,
  initializeTimeout,
  closeTimeout,
  memoryWarnMB: 512,
  memoryLimitMB: 1024,
  pingInterval,
  pingTimeout,
  highPingThreshold,
});
• ProcPool: Pass the memory settings to the process pool like so:
Copy code
const pool = new ProcPool(
  agent,
  numIdleProcesses,
  initializeTimeout,
  closeTimeout,
  inferenceExecutor,
  memoryWarnMB,
  memoryLimitMB
);
• SupervisedProc (Python): When using Python, you can set
memory_warn_mb
and
memory_limit_mb
in the constructor:
Copy code
class MySupervisedProc(SupervisedProc):
    def __init__(self, *, memory_warn_mb: float, memory_limit_mb: float, **kwargs):
        super().__init__(
            memory_warn_mb=memory_warn_mb, 
            memory_limit_mb=memory_limit_mb,
            **kwargs
        )
Here are a few recommendations to keep in mind: • Try setting
memoryWarnMB
to around 70-80% of your expected max memory usage. This helps you catch early warnings. • Set
memoryLimitMB
closer to 90-100% of your available memory to help prevent any crashes. • Keep an eye on your logs for warnings and feel free to adjust these thresholds as you learn more about your workload. If you'd like, I’m here to help you implement this in your specific setup or answer any questions you might have. Just let me know! Sources: agents/src/ipc/inference_proc_executor.ts | livekit-agents/livekit/agents/ipc/supervised_proc.py
w
I am doing a self hosted one and not really using any executor, simply setting up a session and attaching an agent and starting the session. the entrypoint info :
Copy code
session.start(
            agent=agent,
            room=ctx.room,
            room_input_options=RoomInputOptions(),
        )
t
I'm glad you're looking into setting up
memoryWarnMB
and
memoryLimitMB
for memory monitoring in your self-hosted LiveKit session! To get this working, you'll want to configure these values directly in your code. Since you're not using executors, a great approach is to wrap your session logic with a process supervision class like
SupervisedProc
. Here’s a friendly example in Python to guide you:
Copy code
proc = MySupervisedProc(
    initialize_timeout=30.0,
    close_timeout=10.0,
    memory_warn_mb=1024.0,  # Set warning threshold (MB)
    memory_limit_mb=2048.0, # Set termination threshold (MB)
    ping_interval=5.0,
    ping_timeout=15.0,
    high_ping_threshold=3.0
)

await proc.start()
await proc.initialize()
Just a few helpful notes: • Memory usage is checked every 5 seconds, and if it goes beyond your set limits, warnings or terminations will be logged to keep things running smoothly. • These thresholds need to be set programmatically—they can’t be configured directly through environment variables or config files. • If you want more flexibility, you can read these threshold values from environment variables and pass them when creating your process, like this:
Copy code
memory_warn_mb = float(os.getenv("MEMORY_WARN_MB", 1024))
memory_limit_mb = float(os.getenv("MEMORY_LIMIT_MB", 2048))
If you'd like, I’m here to help you step-by-step with integrating this into your session setup. Just let me know! Sources: livekit-agents/livekit/agents/ipc/supervised_proc.py | agents/src/ipc/inference_proc_executor.ts | Self-hosting the Egress Service | LiveKit docs | livekit-server/values.yaml | Deploying to custom environments | LiveKit Docs