wooden-solstice-35084
11/11/2025, 9:14 AMtall-airline-16756
11/11/2025, 9:15 AMtall-airline-16756
11/11/2025, 9:16 AMwooden-solstice-35084
11/11/2025, 9:24 AMclass 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"tall-airline-16756
11/11/2025, 9:24 AMWorkflowBaseAgent 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.pywooden-solstice-35084
11/11/2025, 9:26 AMtall-airline-16756
11/11/2025, 9:26 AMWorkflowBaseAgent 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 Cloudwooden-solstice-35084
11/11/2025, 10:37 AMmemoryWarnMB and memoryLimitMB) to catch and handle any processes using too much memory.
help me set this up ?tall-airline-16756
11/11/2025, 10:38 AMmemoryWarnMB 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:
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:
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:
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:
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.pywooden-solstice-35084
11/11/2025, 10:52 AMsession.start(
agent=agent,
room=ctx.room,
room_input_options=RoomInputOptions(),
)tall-airline-16756
11/11/2025, 10:52 AMmemoryWarnMB 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:
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:
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