Hi guys, I hope you're all well. I need help with ...
# agents
i
Hi guys, I hope you're all well. I need help with something. The system I want to set up is as follows: I have developed virtual people using Gemini Live API + Simli API. I am working on a fiction that this structure will serve without stopping. There are 2 agents in the system I have built now. And I tried to set up a loop with them. • IDLE Agent: Listen to whether there is a user voice using Silero VAD. If there is, run the WAKE Agent. • WAKE Agent: Start working and provide virtual human service using Gemini Live + Simli. Switch off when the session time is over or after 30 seconds of silence. Switch off and activate the IDLE Agent. But my IDLE Agent is not working. I must have misunderstood something in the LiveKit architecture. Here is my agent.py file. What am I doing wrong?
Copy code
import 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,
        )
    )
g
Interesting use case. I noticed that you use the latest Gemini Live model, have you been able to use it in production? The sound etc is great but in all my testing I have had a lot of problems with the agent just disappearing mid conversation, seen other people report it to. Just want to know how your experience has been?
i
It works miraculously well. I highly recommend you use it. Just remember to use this version. "gemini-live-2.5-flash-preview-native-audio-09-2025"
And max session time was 10 min
It also supports use with vertex, if you will use more than 50 sessions per day, it is necessary to work with vertex.
g
Ok. Great. I think i just got it through Ai Studio so will try again using it through Vertex and see if is is more stable. We are using gpt-realtime right now, works great but the voices and especially price is a lot better with the live-2.5-flash so fingers crossed we can get it stable.
b
@important-rainbow-47551 - have you resolved your issue? let me know if I can help you to troubleshoot.