When the agents needs longer than e.g. 1s to gener...
# ask-ai
w
When the agents needs longer than e.g. 1s to generate a reply i want to detect this immediately. How can i detect this instantly and create a callback on this?
t
Thanks for reaching out, Lukas. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to detect immediately when an agent's reply generation exceeds a threshold (e.g., 1s) and trigger a callback. You can do this by listening for the agent's metrics and checking the LLM Time-to-First-Token (
ttft
) metric. Do you want a short code example for Node.js or Python? Sources: Observability data hooks | LiveKit docs
w
in Python please
t
Regarding detecting slow LLM starts in Python: listen for the AgentSession
metrics_collected
event and check
LLMMetrics.ttft
. If it exceeds your threshold (1.0s) call your callback. Example:
Copy code
from livekit.agents import AgentSession, MetricsCollectedEvent, LLMMetrics

THRESHOLD_SECONDS = 1.0

def on_slow_generation(ttft):
    # your immediate callback logic here
    print(f"LLM slow start detected: {ttft:.3f}s")

session = AgentSession(...)  # your existing session

@session.on("metrics_collected")
def handle_metrics(ev: MetricsCollectedEvent):
    if isinstance(ev.metrics, LLMMetrics):
        ttft = ev.metrics.ttft
        if ttft is not None and ttft > THRESHOLD_SECONDS:
            on_slow_generation(ttft)
If you want end-to-end latency instead, I can show how to combine
end_of_utterance_delay
,
LLMMetrics.ttft
, and TTS `ttfb`—do you need that?
w
but i want to detect or trigger this callbac in the exact moment where it exceeds 1s.
t
You're right —
metrics_collected
gives you a metric after the LLM has started, which can feel delayed if you need the callback to fire the moment the elapsed time crosses 1s. To trigger exactly when the threshold is crossed in Python, instrument the request flow locally with a timer that starts when you send the generation request (or when end-of-utterance is detected) and fires a callback if the LLM hasn't produced a first token by 1s. When the LLM produces the first token, cancel the timer. Do you start generations via an API call you control (so you can run code before/after the request) or are you only receiving session events? Which event signals “start waiting” for you (e.g., end-of-utterance, send request call, or something else)? Once I know that, I’ll give a concise runnable Python snippet that uses a timer + cancel-on-first-token logic to call your callback at the exact 1s boundary.
w
I am no using API calls, only session events. I want to measure the time from the moment where the user stops speaking.
t
Thanks — since you only have session events and want timing from when the user stops speaking, use the EndOfUtterance event to start a timer and cancel it when you detect the LLM's first token (via LLMMetrics or a first-token event). Below is a concise, runnable Python pattern you can adapt.
Copy code
import threading
from livekit.agents import AgentSession, EndOfUtteranceEvent, MetricsCollectedEvent, LLMMetrics

THRESHOLD = 1.0  # seconds

def on_threshold_exceeded(utterance_id):
    print(f"Threshold exceeded for utterance {utterance_id}")

session = AgentSession(...)  # your existing session

# store active timers keyed by utterance id
_active_timers = {}

@session.on("end_of_utterance")
def handle_end_of_utterance(ev: EndOfUtteranceEvent):
    utterance_id = ev.utterance_id  # or other unique id in the event
    # start a one-shot timer that fires after THRESHOLD seconds
    timer = threading.Timer(THRESHOLD, lambda: on_threshold_exceeded(utterance_id))
    _active_timers[utterance_id] = timer
    timer.start()

@session.on("metrics_collected")
def handle_metrics(ev: MetricsCollectedEvent):
    # detect first-token arrival via LLMMetrics.ttft being present
    if isinstance(ev.metrics, LLMMetrics):
        utterance_id = ev.metrics.utterance_id  # use the id provided by metrics
        timer = _active_timers.pop(utterance_id, None)
        if timer:
            timer.cancel()
        # If you still want to know actual ttft:
        # ttft = ev.metrics.ttft
Notes and tips: • Use a unique utterance identifier from EndOfUtteranceEvent and LLMMetrics to correlate timers. If the events lack a shared id, correlate by session + recent timestamps (ensure uniqueness). • This fires the callback exactly at 1s after end-of-utterance unless canceled when the first token arrives. • If multiple overlapping utterances are possible, this per-utterance timer handles them independently. Would you like a variant using asyncio instead of threading, or help identifying the exact fields for your EndOfUtterance and LLMMetrics events?
w
I think there is no end_of_utterance event
t
Thanks — since there's no
end_of_utterance
event, use the
user_state_changed
event (detect when user switches to
listening
) to start timing, and the
agent_state_changed
event (detect when agent becomes
thinking
) to stop timing. Below is a concise, runnable Python pattern that triggers a callback exactly when the delay from user stop to agent start exceeds 1s.
Copy code
import time
from livekit.agents import AgentSession, UserStateChangedEvent, AgentStateChangedEvent

THRESHOLD = 1.0  # seconds

session = AgentSession(...)  # your existing session
_user_stop_ts = None

def on_threshold_exceeded(delay):
    # immediate callback when delay > THRESHOLD
    print(f"Reply delay exceeded: {delay:.3f}s")

@session.on("user_state_changed")
def handle_user_state(ev: UserStateChangedEvent):
    global _user_stop_ts
    # when user stops speaking, state becomes "listening"
    if ev.new_state == "listening":
        _user_stop_ts = time.time()

@session.on("agent_state_changed")
def handle_agent_state(ev: AgentStateChangedEvent):
    global _user_stop_ts
    # when agent starts processing, state becomes "thinking"
    if ev.new_state == "thinking" and _user_stop_ts is not None:
        delay = time.time() - _user_stop_ts
        if delay > THRESHOLD:
            on_threshold_exceeded(delay)
        _user_stop_ts = None
If you need: • asyncio version instead of blocking time calls • handling overlapping turns (per-user timers) • include EOUMetrics/LLMMetrics cross-checks for extra accuracy tell me which and I’ll provide that snippet. Sources: Observability data hooks | LiveKit docs | Events and error handling | LiveKit docs