import asyncio import json import logging import o...
# ask-ai
l
import asyncio import json import logging import os from dotenv import load_dotenv from livekit import api from livekit.agents import ( Agent, AgentSession, JobContext, JobProcess, WorkerOptions, cli, ) logger = logging.getLogger("agent") load_dotenv(".env.local") # Load SIP trunk ID for outbound calls outbound_trunk_id = os.getenv("SIP_OUTBOUND_TRUNK_ID") class Assistant(Agent): def __init__(self) -> None: super().__init__( instructions="""You are a helpful voice AI assistant. The user is interacting with you via voice, even if you perceive the conversation as text. You eagerly assist users with their questions by providing information from your extensive knowledge. Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols. You are curious, friendly, and have a sense of humor.""", ) _# To add tools, use the @function_tool decorator._ # Here's an example that adds a simple weather tool. _# You also have to add
from livekit.agents import function_tool, RunContext
to the top of this file_ _# @function_tool_ _# async def lookup_weather(self, context: RunContext, location: str):_ # """Use this tool to look up current weather information in the given location. # # If the location is not supported by the weather service, the tool will indicate this. You must tell the user the location's weather is unavailable. # # Args: # location: The location to look up weather information for (e.g. city name) # """ # # logger.info(f"Looking up weather for {location}") # # return "sunny with a temperature of 70 degrees." def prewarm(_proc_: JobProcess) -> None: # Empty prewarm function - required by LiveKit multiprocessing system # Plugins are imported lazily in entrypoint to reduce idle CPU usage pass async def entrypoint(_ctx_: JobContext): # Lazy import plugins to avoid spawning multiprocessing workers until needed from livekit.plugins import azure, openai # Logging setup # Add any other context you want in all log entries here ctx.log_context_fields = { "room": ctx.room.name, } logger.info(f"Connecting to room {ctx.room.name} with metadata: {ctx.job.metadata}") # Connect to the room first await ctx.connect() # Parse metadata for dial information (if provided) phone_number = None participant_identity = None if ctx.job.metadata: _try_: dial_info = json.loads(ctx.job.metadata) phone_number = dial_info.get("phone_number") participant_identity = phone_number logger.info(f"Dial info parsed - phone_number: {phone_number}") except (json.JSONDecodeError, AttributeError) as e: logger.warning(f"Could not parse metadata as JSON: {e}") # Load Azure configuration from environment variables azure_speech_key = os.getenv("AZURE_SPEECH_KEY", "") azure_speech_region = os.getenv("AZURE_SPEECH_REGION", "") azure_openai_api_key = os.getenv("AZURE_OPENAI_API_KEY", "") azure_openai_api_url = os.getenv("AZURE_OPENAI_API_URL", "") azure_openai_api_version = os.getenv("AZURE_OPENAI_API_VERSION", "") # Load language and voice configuration # Azure Speech Services requires language codes in format "language-locale" (e.g., "en-US", not just "en") language = os.getenv("LANGUAGE", "en-US") voice = os.getenv("AZURE_TTS_VOICE", "en-US-JennyNeural") llm_model = os.getenv("AZURE_OPENAI_MODEL", "gpt-4o-mini") temperature = float(os.getenv("AZURE_OPENAI_TEMPERATURE", "0.7")) # Create Azure STT object with error handling _try_: stt_obj = azure.STT( _speech_key_=azure_speech_key, _speech_region_=azure_speech_region, language=language, ) logger.info(f"Azure STT initialized with language: {language}") except Exception as e: logger.error(f"Failed to initialize Azure STT: {e}") raise # Create Azure OpenAI LLM object with error handling _try_: llm_obj = openai.LLM.with_azure( model=llm_model, _api_key_=azure_openai_api_key, _azure_endpoint_=azure_openai_api_url, _api_version_=azure_openai_api_version, temperature=temperature, ) logger.info(f"Azure OpenAI LLM initialized with model: {llm_model}") except Exception as e: logger.error(f"Failed to initialize Azure OpenAI LLM: {e}") raise # Create Azure TTS object with error handling _try_: tts_obj = azure.TTS( _speech_key_=azure_speech_key, _speech_region_=azure_speech_region, language=language, voice=voice, ) logger.info(f"Azure TTS initialized with voice: {voice}") except Exception as e: logger.error(f"Failed to initialize Azure TTS: {e}") raise # Set up a voice AI pipeline using Azure Speech Services and Azure OpenAI session = AgentSession( # Speech-to-text (STT) using Microsoft Azure Speech Services # See all available models at https://docs.livekit.io/agents/models/stt/ stt=stt_obj, # A Large Language Model (LLM) using Azure OpenAI # See all available models at https://docs.livekit.io/agents/models/llm/ llm=llm_obj, # Text-to-speech (TTS) using Microsoft Azure Speech Services # See all available models as well as voice selections at https://docs.livekit.io/agents/models/tts/ tts=tts_obj, # VAD and turn detection are used to determine when the user is speaking and when the agent should respond # See more at https://docs.livekit.io/agents/build/turns _# turn_detection=MultilingualModel(),_ # vad=ctx.proc.userdata["vad"], # allow the LLM to generate a response while waiting for the end of turn # See more at https://docs.livekit.io/agents/build/audio/#preemptive-generation _preemptive_generation_=True, ) # Start the session as a task (non-blocking) so we can create SIP participant agent = Assistant() session_started = asyncio.create_task( session.start( agent=agent, room=ctx.room, ) ) # Create SIP participant if phone number is provided (for outbound calls) if phone_number and outbound_trunk_id: _try_: logger.info(f"Creating SIP participant for {phone_number}") await ctx.api.sip.create_sip_participant( api.CreateSIPParticipantRequest( _room_name_=ctx.room.name, _sip_trunk_id_=outbound_trunk_id, _sip_call_to_=phone_number, _participant_identity_=participant_identity, # Function blocks until user answers the call, or if the call fails _wait_until_answered_=True, ) ) # Wait for the agent session to start and participant to join await session_started participant = await ctx.wait_for_participant(identity=participant_identity) logger.info(f"Participant joined: {participant.identity}") except api.TwirpError as e: logger.error( f"Error creating SIP participant: {e.message}, " f"SIP status: {e.metadata.get('sip_status_code')} " f"{e.metadata.get('sip_status')}" ) ctx.shutdown() return _else_: # For non-SIP calls, just wait for session to start await session_started if name == "__main__": cli.run_app( WorkerOptions( _entrypoint_fnc_=entrypoint, _agent_name_=os.getenv("agent_name", "outbound-caller"), ) ) just a basic agent.py is using more CPU 15-20 % in Standard D4s v5 (4 vcpus, 16 GiB memory) why and how to reduce it its increasing exponentially when we make multiple concurrent calls
t
Thanks for reaching out, Pavan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thank you for reaching out! I understand that the high CPU usage (15-20%) in your basic
agent.py
script on a Standard D4s v5 instance can be concerning. This is mainly due to LiveKit's default CPU monitoring and worker pre-warming features. Let me guide you through some steps to help reduce it: • Customize or Disable CPU Load Monitoring: You can override the default
load_fnc
in
WorkerOptions
to reduce or even stop frequent CPU sampling. For example:
Copy code
def constant_load():
    return 0.1  # Simulate 10% load

WorkerOptions(
    entrypoint_fnc=entrypoint,
    load_fnc=constant_load
)
• Reduce or Disable Idle Process Pre-warming: Setting
num_idle_processes=0
in
WorkerOptions
helps avoid keeping idle processes active unnecessarily:
Copy code
WorkerOptions(
    entrypoint_fnc=entrypoint,
    num_idle_processes=0
)
• Avoid Unnecessary Plugin Initialization: If you don’t need plugins like VAD or turn detection, make sure they’re not loaded—for instance, avoid loading
silero.VAD
in the
prewarm
function. • Optimize Deployment Environment: Check that your containerized environment has proper CPU limits and guarantees set, and set the
NUM_CPUS
environment variable so the agent knows its CPU allocation. By making these adjustments, you should see a noticeable reduction in baseline CPU usage and better efficiency, especially when managing multiple concurrent calls. If you have any questions or need further help, feel free to ask—I’m here to support you! Sources: livekit-agents/livekit/agents/worker.py | chain-of-thought-tts/agent.py | agent-examples/agent_examples/pipeline_agent.py | Deploying to custom environments | LiveKit Docs