important-rainbow-47551
10/23/2025, 2:31 PMimport logging
import os
import asyncio
from dotenv import load_dotenv
from livekit.agents import (
Agent,
AgentSession,
JobContext,
JobProcess,
RoomInputOptions,
RoomOutputOptions,
WorkerOptions,
cli,
ChatContext,
)
from livekit.agents.vad import VADEventType
from livekit.plugins import google, simli, silero
# uncomment to enable Krisp BVC noise cancellation, currently supported on Linux and MacOS
# from livekit.plugins import noise_cancellation
## This script implements a multi-agent setup that can handoff the session from one agent to another.
## This example demonstrates a workflow with multiple agents (IdleAgent and WakeAgent).
## Each agent can have its own instructions, as well as different STT, LLM, TTS,
## or realtime models.
logger = logging.getLogger("aura-agent")
load_dotenv()
class IdleAgent(Agent):
"""
This agent actively listens using VAD until it detects human speech.
When speech is detected, it switches to WakeAgent.
"""
def __init__(self) -> None:
super().__init__(
instructions="This is a silent agent. Its only job is to listen for voice activity.",
stt=google.STT(),
)
async def on_enter(self):
# Register the event listener
self.session.on("vad_update", self._vad_update_handler)
logger.info("IdleAgent is active and listening for speech.")
async def on_exit(self):
# Remove the event listener
self.session.off("vad_update", self._vad_update_handler)
def _vad_update_handler(self, event: VADEventType):
# This normal (sync) function starts the async function as a task.
asyncio.create_task(self._on_vad_update(event))
async def _on_vad_update(self, event: VADEventType):
# When we capture the start of speech
if event.type == VADEventType.START_OF_SPEECH:
logger.info("Human speech detected, switching to WakeAgent.")
# Switch to WakeAgent
await self.session.update_agent(WakeAgent())
class WakeAgent(Agent):
"""
Interacts with the user using Simli and Gemini Live API.
If an error occurs in the session (like an API connection drop), it returns to IdleAgent.
"""
def __init__(self) -> None:
super().__init__(
instructions="Your name is Aura. You are a helpful AI assistant. "
"You can see the user's video. Keep your answers short and friendly.",
llm=google.beta.realtime.RealtimeModel(
model="gemini-live-2.5-flash-preview-native-audio-09-2025",
voice="Zephyr",
vertexai=True,
),
)
async def on_enter(self):
"""Registers the error listener and greets the user when the agent becomes active."""
self.session.on("error", self._on_session_error)
logger.info("WakeAgent is active. Listening for session errors to trigger handoff.")
await self.session.generate_reply(
instructions="Introduce yourself briefly as Aura and ask how you can help."
)
async def on_exit(self):
"""Removes the error listener when the agent deactivates."""
self.session.off("error", self._on_session_error)
async def _on_session_error(self, error: Exception):
"""
Triggered when an error is caught in the session. This works
in cases like API connection timeouts or drops.
"""
logger.warning(f"Caught a session error: {error}. This is likely an API timeout. Switching back to IdleAgent.")
# Switch to IdleAgent to reset the state after an error
await self.session.update_agent(IdleAgent())
def prewarm(proc: JobProcess):
# We load the VAD with a more sensitive threshold.
# First, we load the VAD...
vad = silero.VAD.load()
# ...then we adjust its sensitivity.
vad.speech_threshold = 0.1 # We lower the value to increase sensitivity.
proc.userdata["vad"] = vad
async def entrypoint(ctx: JobContext):
# We start the Session without VAD.
# The STT plugin inside IdleAgent will manage VAD automatically.
session = AgentSession()
# Configure the Simli Avatar
simli_avatar = simli.AvatarSession(
simli_config=simli.SimliConfig(
api_key=os.getenv("SIMLI_API_KEY"),
face_id=os.getenv("SIMLI_FACE_ID"),
),
)
await simli_avatar.start(session, room=ctx.room)
# Start the session with IdleAgent. The logic inside IdleAgent will handle the rest.
await session.start(
agent=IdleAgent(),
room=ctx.room,
room_input_options=RoomInputOptions(video_enabled=True), # Video is required for Simli
room_output_options=RoomOutputOptions(transcription_enabled=True),
)
if __name__ == "__main__":
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
)
)gifted-magazine-79240
10/23/2025, 6:25 PMimportant-rainbow-47551
10/23/2025, 7:16 PMimportant-rainbow-47551
10/23/2025, 7:17 PMimportant-rainbow-47551
10/23/2025, 7:18 PMgifted-magazine-79240
10/23/2025, 7:22 PMbrief-analyst-2675
10/24/2025, 6:31 AM