I have been using the gemini realtime speech to sp...
# ask-ai
r
I have been using the gemini realtime speech to speech model and the livekit agent which is self hosted. My libraries are up to date and i have experiencing latency issues after I complete my turn and the time it takes to say first token has increased wierdly this was not issue
t
Thanks for reaching out, Rahul. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm sorry to hear you're facing latency issues with the Gemini real-time speech-to-speech model in your self-hosted LiveKit agent. Let's work through some helpful steps together to troubleshoot and optimize your setup: 1. Verify Model Configuration: Please double-check that you're using a supported Gemini Live model, like
gemini-2.0-flash-live-001
, and that the
modalities
parameter includes
AUDIO
. It's important to avoid mixing incompatible turn detection modes to keep things running smoothly. 2. Monitor Metrics: Gathering metrics such as time-to-first-token (TTFT) and tokens per second can really help us identify where the bottlenecks are. This way, we can see if the delay is happening during model inference or audio processing. 3. Optimize Parameters: You might find adjusting settings like
temperature
(around 0.8) beneficial for quicker responses. Also, make sure your audio is resampled correctly—input at 16kHz and output at 24kHz—to ensure optimal performance. 4. Check Network and Infrastructure: Deploying your agent close to Google’s API endpoints can significantly reduce latency. Using private networking solutions, ensuring sufficient bandwidth, and managing QoS will help too. For consistent performance, high-frequency CPU instances are recommended. 5. Session Setup: Using the
AgentSession
with the
RealtimeModel
allows you to take advantage of integrated capabilities and can help avoid the higher latency often seen with traditional pipelines. If you’d like to dive deeper, the High Latency in Agent Responses section and the Latency Optimization Checklist offer some great additional guidance. Sources: Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | livekit-agents/livekit/agents/voice/agent_activity.py | Google AI and LiveKit | LiveKit Docs | Introducing LiveKit Inference: A unified model interface for voice AI | The metaverse needs open infrastructure
r
can you give me example of setting up monitor metrics?
so I can check delay is happening during model inference or audio processing
t
I'm happy to share an example of how you can set up monitoring metrics for the Gemini real-time speech-to-speech model in your LiveKit agent. This will help you keep an eye on important performance details:
Copy code
from livekit.agents.metrics import RealtimeModelMetrics
from livekit.plugins import google

# Create the realtime model
realtime_model = google.beta.realtime.RealtimeModel(
    model="gemini-2.5-flash-native-audio-preview-09-2025",
    proactivity=True,
    enable_affective_dialog=True
)

# Set up metrics collection
def on_metrics_collected(metrics):
    if isinstance(metrics, RealtimeModelMetrics):
        print(f"Response Duration: {metrics.duration:.3f}s")
        print(f"Time to First Token: {metrics.ttft:.3f}s")
        print(f"Tokens per Second: {metrics.tokens_per_second:.1f}")
        print(f"Input Tokens: {metrics.input_tokens}")
        print(f"Output Tokens: {metrics.output_tokens}")
        print(f"Audio Tokens In: {metrics.input_token_details.audio_tokens}")
        print(f"Audio Tokens Out: {metrics.output_token_details.audio_tokens}")
        print(f"Model: {metrics.metadata.model_name}")

# Listen for metrics events
realtime_model.on("metrics_collected", on_metrics_collected)
This setup will collect and log key metrics like response duration, time to first token (TTFT), tokens per second, and detailed token counts. These insights can be really valuable for spotting if any latency is happening during model inference or audio processing. If you'd like, I’m here to help you implement this or walk through the metrics analysis—just let me know! Sources: livekit-agents/livekit/agents/voice/agent_activity.py
r
async def entrypoint(ctx: agents.JobContext): """ Main entry point for the Du customer care agent """ await ctx.connect() usage_collector = metrics.UsageCollector() call_start_time = asyncio.get_event_loop().time() # Check if this is a PSTN call pstn_room_pattern = r"^call-_\\+\\d{10,15}(?:_|$)" is_pstn_room = bool(re.match(pstn_room_pattern, ctx.room.name)) # if not is_pstn_room: # logging.info(f"Skipping non-PSTN room: {ctx.room.name}") # ctx.shutdown(reason="Non-PSTN room pattern; skipping agent") # return # Extract caller number from room name if possible match = re.search(r"\\+(\\d{10,15})", ctx.room.name) caller_number = match.group(0) if match else None print(f"Caller number extracted: {caller_number}") # End call implementation async def _end_call_impl(): logging.info(f"Agent requested call end.") try: await ctx.api.room.delete_room(lk_api.DeleteRoomRequest(room=ctx.room.name)) logging.info(f"Room '{ctx.room.name}' deleted by end_call.") except Exception as e: logging.debug(f"Room deletion by end_call skipped: {e}") finally: ctx.shutdown(reason="Ended by agent") # Create the agent session try: logging.info(f"Creating Du customer care session for room: {ctx.room.name}") # Initialize the agent agent = DuCustomerCareAgent(end_call_coro=_end_call_impl) agent.caller_number = caller_number # 👇 Force PCM/8000 both directions session = AgentSession( llm=RealtimeModel( model="gemini-2.5-flash-native-audio-preview-09-2025", api_key=GOOGLE_API_KEY, voice="Fenrir", language="en-US", modalities=["AUDIO"], temperature=0.3, tool_behavior="NON_BLOCKING", ) ) # Start the agent session logging.info("Starting Du customer care agent session...") await session.start( room=ctx.room, agent=agent, room_input_options=RoomInputOptions(audio_enabled=True, audio_sample_rate=8000), room_output_options=RoomOutputOptions(audio_enabled=True, audio_sample_rate=8000) ) logging.info("Du customer care agent session started successfully") # Initial greeting logging.info("Generating initial greeting...") await session.generate_reply( instructions=""" You should have arabic accent. Greet warmly as Jawaher from Du Business. Say: "Welcome to Du Business, you're speaking with Jawaher. How may I assist you today?" Be natural, warm, and professional. """ ) logging.info("Initial greeting initiated") except Exception as e: logging.error(f"Failed to initialize Du customer care session: {e}") ctx.shutdown(reason=f"Failed to initialize: {str(e)}") return # Handle participant disconnection @ctx.room.on("participant_disconnected") def _on_participant_disconnected(_: rtc.RemoteParticipant) -> None: if len(ctx.room.remote_participants) == 0: async def _cleanup() -> None: try: await ctx.api.room.delete_room(lk_api.DeleteRoomRequest(room=ctx.room.name)) logging.info(f"Room '{ctx.room.name}' deleted (last participant left).") except Exception as e: logging.debug(f"Room deletion skipped: {e}") finally: ctx.shutdown(reason="All participants left") asyncio.create_task(_cleanup()) if name == "__main__": agents.cli.run_app( agents.WorkerOptions( entrypoint_fnc=entrypoint, agent_name="du_customer_care" # 👈 add this line ) ) this is my sample code can you let me know how can I look setup the metrics so I can check if the delay if from model inference or the audio processing
t
I'd love to help you integrate metrics monitoring into your code so you can easily find out whether the delay is coming from model inference or audio processing. Here's a friendly guide to modifying your implementation: 1. Set Up Metrics Collection: You can add a listener for the
metrics_collected
event emitted by the
RealtimeModel
. This will help you capture and log useful metrics like time-to-first-token (TTFT) and token generation rates.
Copy code
from livekit.agents.metrics import RealtimeModelMetrics

# Define a function to handle collected metrics
def on_metrics_collected(metrics):
    if isinstance(metrics, RealtimeModelMetrics):
        print(f"Response Duration: {metrics.duration:.3f}s")
        print(f"Time to First Token: {metrics.ttft:.3f}s")
        print(f"Tokens per Second: {metrics.tokens_per_second:.1f}")
        print(f"Input Tokens: {metrics.input_tokens}")
        print(f"Output Tokens: {metrics.output_tokens}")
        print(f"Audio Tokens In: {metrics.input_token_details.audio_tokens}")
        print(f"Audio Tokens Out: {metrics.output_token_details.audio_tokens}")

# Attach the listener to the RealtimeModel
realtime_model = RealtimeModel(
    model="gemini-2.5-flash-native-audio-preview-09-2025",
    api_key=GOOGLE_API_KEY,
    voice="Fenrir",
    language="en-US",
    modalities=["AUDIO"],
    temperature=0.3,
    tool_behavior="NON_BLOCKING",
)

realtime_model.on("metrics_collected", on_metrics_collected)
1. Log Metrics During Session: To make sure you’re capturing these metrics throughout the session, include the logging in your
entrypoint
function where the session starts.
Copy code
# Start the agent session
session = AgentSession(
    llm=realtime_model,
    vad=silero.VAD.load()
)

await session.start(
    room=ctx.room,
    agent=agent,
    room_input_options=RoomInputOptions(audio_enabled=True, audio_sample_rate=8000),
    room_output_options=RoomOutputOptions(audio_enabled=True, audio_sample_rate=8000)
)
With this setup, you’ll be able to monitor key metrics like TTFT and token generation rates, which should really help pinpoint whether delays are happening during model inference or audio processing. If you’d like, I’m here to walk you through any part of this or help with anything else!
r
I want to log the metrics during the session at each turn
t
To help you log metrics during each turn of your session, you can easily update your code to capture and log these details right after every response is generated. Here’s a friendly guide on how to do that: 1. Attach Metrics Logging to Each Turn: Once a reply is generated in the session, you can retrieve and log the metrics for that specific turn.
Copy code
from livekit.agents.metrics import RealtimeModelMetrics

# Define a function to log metrics
def log_turn_metrics(metrics):
    if isinstance(metrics, RealtimeModelMetrics):
        print(f"Turn Metrics:")
        print(f"  Response Duration: {metrics.duration:.3f}s")
        print(f"  Time to First Token: {metrics.ttft:.3f}s")
        print(f"  Tokens per Second: {metrics.tokens_per_second:.1f}")
        print(f"  Input Tokens: {metrics.input_tokens}")
        print(f"  Output Tokens: {metrics.output_tokens}")
        print(f"  Audio Tokens In: {metrics.input_token_details.audio_tokens}")
        print(f"  Audio Tokens Out: {metrics.output_token_details.audio_tokens}")

# During the session, log metrics after each turn
await session.generate_reply(
    instructions="""
    You should have arabic accent.
    Greet warmly as Jawaher from Du Business. Say:
    "Welcome to Du Business, you're speaking with Jawaher. How may I assist you today?"
    Be natural, warm, and professional.
    """
)

# Retrieve and log metrics for the turn
session.llm.on("metrics_collected", log_turn_metrics)
By connecting the
log_turn_metrics
function to the
metrics_collected
event, you’ll be able to see the metrics for each turn during your session. This is a great way to keep track of important performance details like time-to-first-token (TTFT) and token generation speed for every interaction. If you have any questions or want me to walk you through this further, just let me know—I’m here to help!
r
can you give me whole code so I place the code correctly
t
Here is the complete code with metrics logging integrated for each turn during the session:
Copy code
import asyncio
import re
from livekit.agents import JobContext, RoomInputOptions, RoomOutputOptions
from livekit.agents.voice import AgentSession, Agent
from livekit.agents.metrics import RealtimeModelMetrics
from livekit.plugins import google, silero

class DuCustomerCareAgent(Agent):
    def __init__(self, end_call_coro):
        super().__init__(instructions="You are a helpful voice AI assistant.")
        self.end_call_coro = end_call_coro

async def entrypoint(ctx: JobContext):
    await ctx.connect()

    # Extract caller number from room name
    match = re.search(r"\\+(\\d{10,15})", ctx.room.name)
    caller_number = match.group(0) if match else None

    # Define a function to log metrics
    def log_turn_metrics(metrics):
        if isinstance(metrics, RealtimeModelMetrics):
            print(f"Turn Metrics:")
            print(f"  Response Duration: {metrics.duration:.3f}s")
            print(f"  Time to First Token: {metrics.ttft:.3f}s")
            print(f"  Tokens per Second: {metrics.tokens_per_second:.1f}")
            print(f"  Input Tokens: {metrics.input_tokens}")
            print(f"  Output Tokens: {metrics.output_tokens}")
            print(f"  Audio Tokens In: {metrics.input_token_details.audio_tokens}")
            print(f"  Audio Tokens Out: {metrics.output_token_details.audio_tokens}")

    # End call implementation
    async def _end_call_impl():
        try:
            await ctx.api.room.delete_room(lk_api.DeleteRoomRequest(room=ctx.room.name))
        except Exception as e:
            print(f"Room deletion skipped: {e}")
        finally:
            ctx.shutdown(reason="Ended by agent")

    # Create the realtime model
    realtime_model = google.beta.realtime.RealtimeModel(
        model="gemini-2.5-flash-native-audio-preview-09-2025",
        api_key=GOOGLE_API_KEY,
        voice="Fenrir",
        language="en-US",
        modalities=["AUDIO"],
        temperature=0.3,
        tool_behavior="NON_BLOCKING",
    )

    # Attach the metrics logging function
    realtime_model.on("metrics_collected", log_turn_metrics)

    # Create the agent session
    session = AgentSession(
        llm=realtime_model,
        vad=silero.VAD.load()
    )

    await session.start(
        room=ctx.room,
        agent=DuCustomerCareAgent(end_call_coro=_end_call_impl),
        room_input_options=RoomInputOptions(audio_enabled=True, audio_sample_rate=8000),
        room_output_options=RoomOutputOptions(audio_enabled=True, audio_sample_rate=8000)
    )

    # Generate the initial greeting
    await session.generate_reply(
        instructions="""
        You should have arabic accent.
        Greet warmly as Jawaher from Du Business. Say:
        "Welcome to Du Business, you're speaking with Jawaher. How may I assist you today?"
        Be natural, warm, and professional.
        """
    )

if __name__ == "__main__":
    from livekit.agents.cli import run_app
    from livekit.agents import WorkerOptions

    run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            agent_name="du_customer_care"
        )
    )
This code thoughtfully integrates metrics logging for each turn by attaching the
log_turn_metrics
function to the
metrics_collected
event. It helps you keep track of important details like response duration, time-to-first-token (TTFT), and token information after every interaction. If you have any questions or need help with further adjustments, please don’t hesitate to ask. I’m here to support you!
r
ERROR root - Failed to initialize Du customer care session: 'RealtimeModel' object has no attribute 'on'
t
Thanks for reaching out! The error you're seeing happens because the
RealtimeModel
class doesn’t support the
.on()
method directly for event listeners. But no worries—we can work around this by creating a
RealtimeSession
instance from your
RealtimeModel
and then attaching the event listeners to that session. Here’s a friendly guide on how you can update your code:
Copy code
# Create the realtime model
realtime_model = google.beta.realtime.RealtimeModel(
    model="gemini-2.5-flash-native-audio-preview-09-2025",
    api_key=GOOGLE_API_KEY,
    voice="Fenrir",
    language="en-US",
    modalities=["AUDIO"],
    temperature=0.3,
    tool_behavior="NON_BLOCKING",
)

# Create a session from the realtime model
realtime_session = realtime_model.session()

# Define a function to log metrics
def log_turn_metrics(metrics):
    print(f"Turn Metrics:")
    print(f"  Response Duration: {metrics.duration:.3f}s")
    print(f"  Time to First Token: {metrics.ttft:.3f}s")
    print(f"  Tokens per Second: {metrics.tokens_per_second:.1f}")
    print(f"  Input Tokens: {metrics.input_tokens}")
    print(f"  Output Tokens: {metrics.output_tokens}")
    print(f"  Audio Tokens In: {metrics.input_token_details.audio_tokens}")
    print(f"  Audio Tokens Out: {metrics.output_token_details.audio_tokens}")

# Attach the metrics logging function to the session
realtime_session.on("metrics_collected", log_turn_metrics)
By making this adjustment, your metrics logging function will be properly connected to the
RealtimeSession
, allowing you to track metrics smoothly during each turn. If you run into any more questions or need a hand with anything else, feel free to ask—I’m here to help! Sources: livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | Events and error handling | LiveKit docs | agents/src/llm/realtime.ts