rapid-van-16677
11/01/2025, 9:43 AMtall-airline-16756
11/01/2025, 9:43 AMtall-airline-16756
11/01/2025, 9:44 AMgemini-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 infrastructurerapid-van-16677
11/01/2025, 9:51 AMrapid-van-16677
11/01/2025, 9:52 AMtall-airline-16756
11/01/2025, 9:53 AMfrom 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.pyrapid-van-16677
11/01/2025, 9:56 AMtall-airline-16756
11/01/2025, 9:56 AMmetrics_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.
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.
# 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!rapid-van-16677
11/01/2025, 10:01 AMtall-airline-16756
11/01/2025, 10:02 AMfrom 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!rapid-van-16677
11/01/2025, 10:04 AMtall-airline-16756
11/01/2025, 10:05 AMimport 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!rapid-van-16677
11/01/2025, 10:18 AMtall-airline-16756
11/01/2025, 10:19 AMRealtimeModel 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:
# 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