important-rainbow-47551
10/25/2025, 5:13 PMimport logging
import os
import asyncio
from dotenv import load_dotenv
from livekit.agents import (
Agent,
AgentSession,
JobContext,
JobProcess,
RoomInputOptions,
RoomOutputOptions,
WorkerOptions,
cli,
ChatContext,
metrics,
UserStateChangedEvent,
)
from livekit.agents.vad import VADEventType
from livekit.plugins import google, simli, silero
from livekit.agents.llm import function_tool
logger = logging.getLogger("aura-agent")
load_dotenv()
class IdleAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="This is a silent agent. Its only job is to listen for voice activity.",
)
self._active_tasks = set() # To manage active tasks
async def on_enter(self):
logger.info("IdleAgent is active and listening for speech.")
# We connect the event to a synchronous callback function.
self.session.on("user_state_changed", self._user_state_changed_handler)
# The generate_reply() call that caused a previous error has been removed.
# Helper method to handle the asynchronous operation (Core Logic)
async def _async_handoff(self, event: UserStateChangedEvent):
if event.new_state == "speaking":
logger.info("Speech detected! Handoff to WakeAgent.")
# Synchronous Event Handler (Callback)
def _user_state_changed_handler(self, event: UserStateChangedEvent):
"""This synchronous method is called immediately when the event occurs."""
if event.new_state == "speaking":
# Start the asynchronous handoff process as a new task.
wake_agent = WakeAgent()
# The agent change is an asynchronous operation.
self.session.update_agent(wake_agent)
class WakeAgent(Agent):
"""
Interacts with the user using Simli and Gemini Live API.
Returns to IdleAgent when a session error occurs (e.g., API connection loss).
"""
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):
"""When the agent becomes active, it registers an error listener and greets the user."""
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):
"""When the agent is deactivated, it removes the error listener."""
self.session.off("error", self._on_session_error)
async def _on_session_error(self, error: Exception):
"""
Triggered when a session error is caught. This typically happens
if the API connection times out or is lost.
"""
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(vad=self._vad))
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
print("VAD prewarmed and stored in process userdata.")
async def entrypoint(ctx: JobContext):
# We start the session without VAD.
# The STT plugin inside IdleAgent will manage VAD automatically.
session = AgentSession(
vad=silero.VAD.load(),
)
# 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 within 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,
prewarm_fnc=prewarm,
)
)
GUYS I NEED CODE REVİEW PLEASE CAN SOMEONE REVİEW MY CODEcreamy-megabyte-39753
10/25/2025, 8:35 PM