Files
livekit-agents/tests/test_agent_session.py
Théo Monnom c0aa5612f4 Merge commit 'b58e83f5c' into HEAD
# Conflicts:
#	livekit-agents/livekit/agents/llm/utils.py
#	livekit-agents/livekit/agents/version.py
#	uv.lock
2026-10-12 14:05:55 -07:00

2437 lines
89 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import asyncio
import logging
import time
from collections.abc import AsyncIterable
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock, patch
import pytest
from livekit import rtc
from livekit.agents import (
NOT_GIVEN,
Agent,
AgentFalseInterruptionEvent,
AgentStateChangedEvent,
APIConnectionError,
ConversationItemAddedEvent,
FlushSentinel,
LanguageCode,
LiveSession,
MetricsCollectedEvent,
ModelSettings,
NotGivenOr,
RunContext,
TurnHandlingOptions,
UserInputTranscribedEvent,
UserStateChangedEvent,
function_tool,
inference,
vad,
)
from livekit.agents.llm import (
FunctionTool,
FunctionToolCall,
InputTranscriptionCompleted,
RawFunctionTool,
ToolContext,
ToolFlag,
Toolset,
)
from livekit.agents.llm.chat_context import ChatContext, ChatMessage
from livekit.agents.stt import SpeechData, SpeechEvent, SpeechEventType, STTError
from livekit.agents.utils import aio
from livekit.agents.voice.agent_activity import AgentActivity, _transcripts_equivalent
from livekit.agents.voice.audio_recognition import AudioRecognition, _EndOfTurnInfo
from livekit.agents.voice.endpointing import BaseEndpointing
from livekit.agents.voice.events import AgentState, FunctionToolsExecutedEvent, UserState
from livekit.agents.voice.io import PlaybackFinishedEvent
from livekit.agents.voice.tool_executor import UPDATE_TEMPLATE
from .fake_session import FakeActions, create_session, run_session
pytestmark = [pytest.mark.unit, pytest.mark.virtual_time, pytest.mark.no_concurrent]
class MyAgent(Agent):
def __init__(
self,
*,
generate_reply_on_enter: bool = False,
say_on_user_turn_completed: bool = False,
on_user_turn_completed_delay: float = 0.0,
turn_handling: NotGivenOr[TurnHandlingOptions] = NOT_GIVEN,
) -> None:
super().__init__(
instructions=("You are a helpful assistant."),
turn_handling=turn_handling,
)
self.generate_reply_on_enter = generate_reply_on_enter
self.say_on_user_turn_completed = say_on_user_turn_completed
self.on_user_turn_completed_delay = on_user_turn_completed_delay
self._close_session_task: asyncio.Task[None] | None = None
async def on_enter(self) -> None:
if self.generate_reply_on_enter:
self.session.generate_reply(instructions="instructions:say hello to the user")
@function_tool
async def get_weather(self, location: str) -> str:
"""
Called when the user asks about the weather.
Args:
location: The location to get the weather for
"""
return f"The weather in {location} is sunny today."
@function_tool
async def goodbye(self) -> None:
await self.session.generate_reply(instructions="instructions:say goodbye to the user")
self._close_session_task = asyncio.create_task(self.session.aclose())
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
if self.say_on_user_turn_completed:
self.session.say("session.say from on_user_turn_completed")
if self.on_user_turn_completed_delay > 0.0:
await asyncio.sleep(self.on_user_turn_completed_delay)
SESSION_TIMEOUT = 60.0
def test_realtime_user_input_transcription_preserves_item_id() -> None:
captured_events: list[UserInputTranscribedEvent] = []
class DummySession:
def _user_input_transcribed(self, ev: UserInputTranscribedEvent) -> None:
captured_events.append(ev)
activity = object.__new__(AgentActivity)
activity._session = DummySession()
AgentActivity._on_input_audio_transcription_completed(
activity,
InputTranscriptionCompleted(
item_id="item_123",
transcript="hello",
is_final=False,
),
)
assert len(captured_events) == 1
assert captured_events[0].transcript == "hello"
assert captured_events[0].is_final is False
assert captured_events[0].item_id == "item_123"
@pytest.mark.parametrize(
("has_local_vad", "should_interrupt"),
[
(False, True),
(True, False),
],
)
def test_interim_transcript_interrupts_only_without_local_vad(
has_local_vad: bool, should_interrupt: bool
) -> None:
captured_events: list[UserInputTranscribedEvent] = []
activity = object.__new__(AgentActivity)
activity._agent = SimpleNamespace(llm=NOT_GIVEN, vad=NOT_GIVEN)
activity._session = SimpleNamespace(
_text_only=False,
llm=None,
vad=Mock(spec=vad.VAD) if has_local_vad else None,
_user_input_transcribed=captured_events.append,
)
activity._turn_detection = None
activity._paused_speech = None
activity._interrupt_by_audio_activity = Mock()
activity.on_interim_transcript(
SpeechEvent(
type=SpeechEventType.INTERIM_TRANSCRIPT,
alternatives=[SpeechData(text="hello", language=LanguageCode("en"))],
),
speaking=None,
)
assert len(captured_events) == 1
assert captured_events[0].transcript == "hello"
if should_interrupt:
activity._interrupt_by_audio_activity.assert_called_once_with()
else:
activity._interrupt_by_audio_activity.assert_not_called()
async def test_events_and_metrics() -> None:
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Hello, how are you?", stt_delay=0.2) # EOU at 2.5+0.5=3.0s
actions.add_llm("I'm doing well, thank you!", ttft=0.1, duration=0.3)
actions.add_tts(
2.0, ttfb=0.2, duration=0.3
) # audio playout starts at 3.0+0.3+0.2=3.5s, ends at 5.5s
session = create_session(actions, speed_factor=speed)
agent = MyAgent()
user_state_events: list[UserStateChangedEvent] = []
agent_state_events: list[AgentStateChangedEvent] = []
metrics_events: list[MetricsCollectedEvent] = []
conversation_events: list[ConversationItemAddedEvent] = []
user_transcription_events: list[UserInputTranscribedEvent] = []
session.on("user_state_changed", user_state_events.append)
session.on("agent_state_changed", agent_state_events.append)
session.on("metrics_collected", metrics_events.append)
session.on("conversation_item_added", conversation_events.append)
session.on("user_input_transcribed", user_transcription_events.append)
t_origin = await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
# conversation_item_added
assert len(conversation_events) == 3
assert conversation_events[0].item.type == "agent_handoff"
assert conversation_events[1].item.type == "message"
assert conversation_events[1].item.role == "user"
assert conversation_events[1].item.text_content == "Hello, how are you?"
check_timestamp(conversation_events[1].created_at - t_origin, 3.0, speed_factor=speed)
assert conversation_events[2].item.type == "message"
assert conversation_events[2].item.role == "assistant"
assert conversation_events[2].item.text_content == "I'm doing well, thank you!"
check_timestamp(conversation_events[2].created_at - t_origin, 5.5, speed_factor=speed)
# user_input_transcribed
assert len(user_transcription_events) >= 1
assert user_transcription_events[-1].transcript == "Hello, how are you?"
assert user_transcription_events[-1].is_final is True
check_timestamp(user_transcription_events[-1].created_at - t_origin, 2.7, speed_factor=speed)
# user_state_changed
assert len(user_state_events) == 2
check_timestamp(user_state_events[0].created_at - t_origin, 0.5, speed_factor=speed)
assert user_state_events[0].new_state == "speaking"
check_timestamp(user_state_events[1].created_at - t_origin, 3.0, speed_factor=speed)
assert user_state_events[1].new_state == "listening"
# agent_state_changed
assert len(agent_state_events) == 4
assert agent_state_events[0].old_state == "initializing"
assert agent_state_events[0].new_state == "listening"
assert agent_state_events[1].new_state == "thinking"
check_timestamp(agent_state_events[1].created_at - t_origin, 3.0, speed_factor=speed)
assert agent_state_events[2].new_state == "speaking"
check_timestamp(agent_state_events[2].created_at - t_origin, 3.5, speed_factor=speed)
assert agent_state_events[3].new_state == "listening"
check_timestamp(agent_state_events[3].created_at - t_origin, 5.5, speed_factor=speed)
# metrics
metrics_events = [ev for ev in metrics_events if ev.metrics.type != "vad_metrics"]
assert len(metrics_events) == 3
assert metrics_events[0].metrics.type == "eou_metrics"
check_timestamp(metrics_events[0].metrics.end_of_utterance_delay, 0.5, speed_factor=speed)
check_timestamp(metrics_events[0].metrics.transcription_delay, 0.2, speed_factor=speed)
assert metrics_events[1].metrics.type == "llm_metrics"
check_timestamp(metrics_events[1].metrics.ttft, 0.1, speed_factor=speed)
check_timestamp(metrics_events[1].metrics.duration, 0.3, speed_factor=speed)
assert metrics_events[2].metrics.type == "tts_metrics"
check_timestamp(metrics_events[2].metrics.ttfb, 0.2, speed_factor=speed)
check_timestamp(metrics_events[2].metrics.audio_duration, 2.0, speed_factor=speed)
async def test_tts_node_ttfb_excludes_upstream_latency() -> None:
# the LLM stream stays open for its full duration and the fake TTS only starts
# synthesizing once its input is flushed. tts_node_ttfb must anchor on the text
# being handed to the TTS provider (~2.0s in), not on the first LLM token (~0.1s in),
# otherwise the LLM streaming time is misattributed to the TTS
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Hello, how are you?", stt_delay=0.2)
actions.add_llm("I'm doing well, thank you!", ttft=0.1, duration=2.0)
actions.add_tts(1.0, ttfb=0.2, duration=0.3)
session = create_session(actions, speed_factor=speed)
agent = MyAgent()
conversation_events: list[ConversationItemAddedEvent] = []
session.on("conversation_item_added", conversation_events.append)
await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
assistant_messages = [
ev.item
for ev in conversation_events
if ev.item.type == "message" and ev.item.role == "assistant"
]
assert len(assistant_messages) == 1
metrics = assistant_messages[0].metrics
assert "tts_node_ttfb" in metrics
check_timestamp(metrics["tts_node_ttfb"], 0.2, speed_factor=speed)
async def test_llm_node_ttfs_anchors_on_synthesis_start() -> None:
# ttfs is the LLM->TTS handoff: inference start until the first sentence reached the
# provider. The fake TTS only synthesizes once its input is flushed (~2.0s in, when the
# LLM stream ends), so ttfs must be ~2.0 and ttfb ~0.2 -- together they decompose the
# gap between the first token and the first audio.
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Hello, how are you?", stt_delay=0.2)
actions.add_llm("I'm doing well, thank you!", ttft=0.1, duration=2.0)
actions.add_tts(1.0, ttfb=0.2, duration=0.3)
session = create_session(actions, speed_factor=speed)
agent = MyAgent()
conversation_events: list[ConversationItemAddedEvent] = []
session.on("conversation_item_added", conversation_events.append)
await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
assistant_messages = [
ev.item
for ev in conversation_events
if ev.item.type == "message" and ev.item.role == "assistant"
]
assert len(assistant_messages) == 1
metrics = assistant_messages[0].metrics
assert "llm_node_ttfs" in metrics
check_timestamp(metrics["llm_node_ttfs"], 2.0, speed_factor=speed)
check_timestamp(metrics["tts_node_ttfb"], 0.2, speed_factor=speed)
async def test_slow_tool_keeps_agent_thinking_after_filler() -> None:
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Look up my order")
actions.add_llm(
content="Let me check.",
tool_calls=[FunctionToolCall(name="lookup_order", arguments="{}", call_id="1")],
)
actions.add_tts(2.0)
actions.add_tts(1.0, input="Just a moment.")
actions.add_llm(content="Order 42 is on the way.", input="order 42 shipped")
actions.add_tts(1.0)
class SlowToolAgent(Agent):
def __init__(self) -> None:
super().__init__(instructions="You are a helpful assistant.")
@function_tool
async def lookup_order(self, context: RunContext) -> str:
async with context.with_filler("Just a moment.", delay=0.5):
await asyncio.sleep(8.0)
return "order 42 shipped"
session = create_session(actions, extra_kwargs={"user_away_timeout": 3.0})
agent_state_events: list[AgentStateChangedEvent] = []
user_state_events: list[UserStateChangedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.on("user_state_changed", user_state_events.append)
await asyncio.wait_for(
run_session(session, SlowToolAgent(), drain_delay=10), timeout=SESSION_TIMEOUT
)
# both the reply and the filler end while the tool is still running, so each
# must hand back "thinking", not "listening" (which arms the user-away timer)
speaking_ends = [ev.new_state for ev in agent_state_events if ev.old_state == "speaking"]
assert speaking_ends == ["thinking", "thinking", "listening"]
assert all(ev.new_state != "away" for ev in user_state_events)
async def test_tool_without_a_reply_returns_the_agent_to_listening() -> None:
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Look up my order")
actions.add_llm(
content="Let me check.",
tool_calls=[FunctionToolCall(name="silent_lookup", arguments="{}", call_id="1")],
)
actions.add_tts(2.0)
class SilentToolAgent(Agent):
def __init__(self) -> None:
super().__init__(instructions="You are a helpful assistant.")
@function_tool
async def silent_lookup(self, context: RunContext) -> None:
"""A slow tool that returns nothing, so no reply follows it."""
await asyncio.sleep(8.0)
session = create_session(actions, extra_kwargs={"user_away_timeout": 3.0})
agent_state_events: list[AgentStateChangedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
await asyncio.wait_for(
run_session(session, SilentToolAgent(), drain_delay=20), timeout=SESSION_TIMEOUT
)
# the tool holds the agent in "thinking", and nothing follows it to hand the turn back
transitions = [(ev.old_state, ev.new_state) for ev in agent_state_events]
assert transitions[-2:] == [("speaking", "thinking"), ("thinking", "listening")]
@pytest.mark.parametrize("reset_away_timer", [False, True])
async def test_async_tool_defers_user_away_until_its_reply_lands(reset_away_timer: bool) -> None:
"""A background tool speaks for itself, so "away" must wait for that reply (#6883)."""
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Look up my order")
actions.add_llm(
content="Let me check.",
tool_calls=[FunctionToolCall(name="async_lookup", arguments="{}", call_id="1")],
)
actions.add_tts(2.0)
actions.add_llm(
content="I'm looking it up.",
input=UPDATE_TEMPLATE.format(
function_name="async_lookup", call_id="1", message="looking it up"
),
)
actions.add_tts(1.0)
tool_returned_at = 0.0
class AsyncToolAgent(Agent):
def __init__(self) -> None:
super().__init__(instructions="You are a helpful assistant.")
@function_tool
async def async_lookup(self, context: RunContext) -> str:
"""Look an order up in the background."""
nonlocal tool_returned_at
await context.update("looking it up")
await asyncio.sleep(10.0)
if reset_away_timer:
assert context.session.agent_state == "listening"
context.session.reset_away_timer()
await asyncio.sleep(10.0)
tool_returned_at = time.time()
return "order 42 shipped"
session = create_session(actions, extra_kwargs={"user_away_timeout": 3.0})
away_times: list[float] = []
session.on(
"user_state_changed",
lambda ev: away_times.append(time.time()) if ev.new_state == "away" else None,
)
await asyncio.wait_for(
run_session(session, AsyncToolAgent(), drain_delay=40), timeout=SESSION_TIMEOUT
)
# the agent is genuinely listening while the tool runs, so nothing but the tool holds
# the window off; landing restarts it in full rather than firing on what was left
assert tool_returned_at > 0
assert len(away_times) == 1
assert away_times[0] >= tool_returned_at + 3.0
async def test_async_tool_without_a_reply_still_restarts_the_away_window() -> None:
"""A tool returning ``None`` after an update files no reply, so nothing else can
restart the window it held off."""
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Look up my order")
actions.add_llm(
content="Let me check.",
tool_calls=[FunctionToolCall(name="async_lookup", arguments="{}", call_id="1")],
)
actions.add_tts(2.0)
actions.add_llm(
content="I'm looking it up.",
input=UPDATE_TEMPLATE.format(
function_name="async_lookup", call_id="1", message="looking it up"
),
)
actions.add_tts(1.0)
tool_returned_at = 0.0
class AsyncToolAgent(Agent):
def __init__(self) -> None:
super().__init__(instructions="You are a helpful assistant.")
@function_tool
async def async_lookup(self, context: RunContext) -> None:
"""Look an order up in the background and say nothing more."""
nonlocal tool_returned_at
await context.update("looking it up")
await asyncio.sleep(20.0)
tool_returned_at = time.time()
session = create_session(actions, extra_kwargs={"user_away_timeout": 3.0})
away_times: list[float] = []
session.on(
"user_state_changed",
lambda ev: away_times.append(time.time()) if ev.new_state == "away" else None,
)
await asyncio.wait_for(
run_session(session, AsyncToolAgent(), drain_delay=40), timeout=SESSION_TIMEOUT
)
assert len(away_times) == 1
assert away_times[0] >= tool_returned_at + 3.0
async def test_interruption_options() -> None:
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Tell me a story.")
actions.add_llm("Here is a long story for you ... the end.")
actions.add_tts(5.0) # playout starts at 3.5s
actions.add_user_speech(5.0, 6.0, "Stop!")
actions.add_user_speech(6.5, 7.5, "ok, stop!", stt_delay=0.0)
# it should interrupt at 7.5s after stt, playback position is 4.0s
# test min_interruption_words
session = create_session(
actions,
speed_factor=speed,
turn_handling={"interruption": {"min_words": 3}},
)
playback_finished_events: list[PlaybackFinishedEvent] = []
session.output.audio.on("playback_finished", playback_finished_events.append)
await asyncio.wait_for(run_session(session, MyAgent()), timeout=SESSION_TIMEOUT)
assert len(playback_finished_events) == 1
assert playback_finished_events[0].interrupted is True
check_timestamp(playback_finished_events[0].playback_position, 4.0, speed_factor=speed)
# test allow_interruptions=False
session = create_session(
actions,
speed_factor=speed,
turn_handling={"interruption": {"enabled": False}},
)
playback_finished_events.clear()
session.output.audio.on("playback_finished", playback_finished_events.append)
await asyncio.wait_for(run_session(session, MyAgent()), timeout=SESSION_TIMEOUT)
assert len(playback_finished_events) == 1
assert playback_finished_events[0].interrupted is False
check_timestamp(playback_finished_events[0].playback_position, 5.0, speed_factor=speed)
async def test_false_interruption_before_speaking_resumes() -> None:
"""
Brief VAD-only noise during ``thinking`` must pause then resume on VAD EOS,
letting the stale reply play through normally.
"""
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Tell me a story.")
actions.add_llm("Here is a short reply.", ttft=0.05, duration=0.05)
actions.add_tts(5.0, ttfb=0.05, duration=0.05)
# brief VAD-only noise — same shape as the can_pause=False test, different capability
actions.add_user_speech(3.0, 3.3, "")
session = create_session(actions, speed_factor=speed, can_pause_audio=True)
agent = MyAgent()
agent_state_events: list[AgentStateChangedEvent] = []
playback_finished_events: list[PlaybackFinishedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.output.audio.on("playback_finished", playback_finished_events.append)
t_origin = await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
# the agent resumes and speaks the reply after the false interruption clears
speaking_events = [ev for ev in agent_state_events if ev.new_state == "speaking"]
assert len(speaking_events) == 1
# playout was postponed: the noise ran 3.0–3.3s, so "speaking" should fire at
# ~3.8s (resume on VAD EOS=3.3s + 0.5s min_silence_duration)
check_timestamp(speaking_events[0].created_at - t_origin, 3.8, speed_factor=speed)
# the reply plays to completion (not interrupted); playback_position covers the
# full audio duration
assert len(playback_finished_events) == 1
assert playback_finished_events[0].interrupted is False
check_timestamp(playback_finished_events[0].playback_position, 5.0, speed_factor=speed)
async def test_on_enter_hides_ignore_on_enter_tools() -> None:
"""IGNORE_ON_ENTER tools (bare + toolset-nested) are hidden inside on_enter, restored after."""
class _Toolset(Toolset):
def __init__(self) -> None:
end_call = function_tool(
self._end_call,
name="end_call",
description="ends the call",
flags=ToolFlag.IGNORE_ON_ENTER,
)
keep = function_tool(self._keep, name="keep", description="a normal tool")
super().__init__(id="ts", tools=[end_call, keep])
async def _end_call(self) -> None: ...
async def _keep(self) -> None: ...
@function_tool(flags=ToolFlag.IGNORE_ON_ENTER)
async def bare_ignored() -> None:
"""A bare flagged tool."""
class _Agent(Agent):
def __init__(self) -> None:
super().__init__(instructions="you are helpful", tools=[_Toolset(), bare_ignored])
async def on_enter(self) -> None:
self.session.generate_reply(instructions="instructions:say hello to the user")
actions = FakeActions()
actions.add_llm("Hello!", input="instructions:say hello to the user")
actions.add_tts(1.0)
actions.add_user_speech(2.0, 3.0, "hi there")
actions.add_llm("How can I help?")
actions.add_tts(1.0)
session = create_session(actions)
captured: list[set[str]] = []
orig_chat = session.llm.chat
def _recording_chat(*, chat_ctx, tools=None, **kwargs): # type: ignore[no-untyped-def]
captured.append(
{t.info.name for t in (tools or []) if isinstance(t, (FunctionTool, RawFunctionTool))}
)
return orig_chat(chat_ctx=chat_ctx, tools=tools, **kwargs)
session.llm.chat = _recording_chat # type: ignore[method-assign]
await asyncio.wait_for(run_session(session, _Agent()), timeout=SESSION_TIMEOUT)
assert len(captured) == 2
# on_enter reply: flagged tools hidden, normal tool still offered
assert captured[0] == {"keep"}
# a later (non-on_enter) turn sees every tool again
assert captured[1] == {"keep", "end_call", "bare_ignored"}
async def test_on_enter_hides_tools_in_nested_tool_reply() -> None:
"""When an on_enter reply calls a tool, the tool-response follow-up (a nested speech task)
also hides the flagged tools — proving the on_enter contextvar reaches nested tasks."""
class _Toolset(Toolset):
def __init__(self) -> None:
end_call = function_tool(
self._end_call, name="end_call", description="ends", flags=ToolFlag.IGNORE_ON_ENTER
)
keep = function_tool(self._keep, name="keep", description="a normal tool")
super().__init__(id="ts", tools=[end_call, keep])
async def _end_call(self) -> None: ...
async def _keep(self) -> str:
return "kept"
@function_tool(flags=ToolFlag.IGNORE_ON_ENTER)
async def bare_ignored() -> None:
"""A bare flagged tool."""
class _Agent(Agent):
def __init__(self) -> None:
super().__init__(instructions="you are helpful", tools=[_Toolset(), bare_ignored])
async def on_enter(self) -> None:
self.session.generate_reply(instructions="instructions:say hello to the user")
actions = FakeActions()
# on_enter reply calls the visible `keep` tool instead of speaking, spawning a follow-up
actions.add_llm(
"",
tool_calls=[FunctionToolCall(name="keep", arguments="{}", call_id="1")],
input="instructions:say hello to the user",
)
# tool-response follow-up (keyed on the `keep` return value)
actions.add_llm("Hello there!", input="kept")
actions.add_tts(1.0)
# a user turn ends the run and confirms tools are restored afterwards
actions.add_user_speech(4.0, 5.0, "hi there")
actions.add_llm("How can I help?")
actions.add_tts(1.0)
session = create_session(actions)
captured: list[set[str]] = []
orig_chat = session.llm.chat
def _recording_chat(*, chat_ctx, tools=None, **kwargs): # type: ignore[no-untyped-def]
captured.append(
{t.info.name for t in (tools or []) if isinstance(t, (FunctionTool, RawFunctionTool))}
)
return orig_chat(chat_ctx=chat_ctx, tools=tools, **kwargs)
session.llm.chat = _recording_chat # type: ignore[method-assign]
await asyncio.wait_for(run_session(session, _Agent()), timeout=SESSION_TIMEOUT)
assert len(captured) == 3
greeting, tool_reply, user_turn = captured
# both the greeting reply and its nested tool-response follow-up hide the flagged tools
assert greeting == {"keep"}
assert tool_reply == {"keep"}
# the later (non-on_enter) user turn sees every tool again
assert user_turn == {"keep", "end_call", "bare_ignored"}
def test_on_enter_ignored_tools() -> None:
"""_on_enter_ignored_tools returns flagged tools only inside this agent/session's on_enter."""
from livekit.agents.voice.agent_activity import _OnEnterContextVar, _OnEnterData
class _Toolset(Toolset):
def __init__(self) -> None:
end_call = function_tool(
self._end_call, name="end_call", description="ends", flags=ToolFlag.IGNORE_ON_ENTER
)
ts_keep = function_tool(self._keep, name="ts_keep", description="normal")
super().__init__(id="ts", tools=[end_call, ts_keep])
async def _end_call(self) -> None: ...
async def _keep(self) -> None: ...
@function_tool(flags=ToolFlag.IGNORE_ON_ENTER)
async def bare_ignored() -> None:
"""A flagged bare tool."""
@function_tool
async def bare_keep() -> None:
"""A normal bare tool."""
activity = object.__new__(AgentActivity)
activity._agent = object() # type: ignore[assignment]
activity._session = object() # type: ignore[assignment]
tool_ctx = ToolContext([_Toolset(), bare_ignored, bare_keep])
# outside on_enter: nothing is ignored
assert activity._on_enter_ignored_tools(tool_ctx) == []
# inside this agent/session's on_enter: flagged tools (bare + nested) are returned
tk = _OnEnterContextVar.set(_OnEnterData(session=activity._session, agent=activity._agent))
try:
ignored = {t.info.name for t in activity._on_enter_ignored_tools(tool_ctx)}
finally:
_OnEnterContextVar.reset(tk)
assert ignored == {"end_call", "bare_ignored"}
# a different agent's on_enter must not leak in
tk = _OnEnterContextVar.set(_OnEnterData(session=activity._session, agent=object()))
try:
assert activity._on_enter_ignored_tools(tool_ctx) == []
finally:
_OnEnterContextVar.reset(tk)
@pytest.mark.parametrize(
("kind", "attributes", "expected_duration"),
[
(rtc.ParticipantKind.PARTICIPANT_KIND_SIP, {}, None),
(
rtc.ParticipantKind.PARTICIPANT_KIND_SIP,
{"sip.ruleID": "SDR_inbound"},
3.0,
),
(rtc.ParticipantKind.PARTICIPANT_KIND_STANDARD, {}, 3.0),
],
)
def test_aec_warmup_default_depends_on_call_type(
kind: rtc.ParticipantKind.ValueType,
attributes: dict[str, str],
expected_duration: float | None,
) -> None:
session = LiveSession(vad=None)
participant = MagicMock(spec=rtc.RemoteParticipant)
participant.kind = kind
participant.attributes = attributes
session._on_room_io_participant_linked(participant)
assert session.options.aec_warmup_duration == expected_duration
assert session._aec_warmup_remaining == (expected_duration or 0.0)
@pytest.mark.parametrize("duration", [None, 0.0, 1.5])
def test_explicit_aec_warmup_duration_overrides_outbound_sip_default(
duration: float | None,
) -> None:
session = LiveSession(vad=None, aec_warmup_duration=duration)
participant = MagicMock(spec=rtc.RemoteParticipant)
participant.kind = rtc.ParticipantKind.PARTICIPANT_KIND_SIP
participant.attributes = {}
session._on_room_io_participant_linked(participant)
assert session.options.aec_warmup_duration == duration
assert session._aec_warmup_remaining == (duration or 0.0)
@pytest.mark.parametrize(
("explicit", "expected_duration"),
[(NOT_GIVEN, None), (1.5, 1.5)],
)
def test_simulation_has_no_aec_warmup_by_default(
explicit: NotGivenOr[float | None], expected_duration: float | None
) -> None:
session = AgentSession(vad=None, aec_warmup_duration=explicit)
participant = MagicMock(spec=rtc.RemoteParticipant)
participant.kind = rtc.ParticipantKind.PARTICIPANT_KIND_STANDARD
participant.attributes = {}
with patch("livekit.agents.job.current_simulation", return_value=object()):
session._on_room_io_participant_linked(participant)
assert session.options.aec_warmup_duration == expected_duration
assert session._aec_warmup_remaining == (expected_duration or 0.0)
def test_outbound_sip_cancels_aec_warmup_that_already_started() -> None:
session = LiveSession(vad=None)
timer = MagicMock(spec=asyncio.TimerHandle)
session._aec_warmup_timer = timer
participant = MagicMock(spec=rtc.RemoteParticipant)
participant.kind = rtc.ParticipantKind.PARTICIPANT_KIND_SIP
participant.attributes = {}
session._on_room_io_participant_linked(participant)
timer.cancel.assert_called_once()
assert session._aec_warmup_timer is None
async def test_aec_warmup() -> None:
"""AEC warmup should block audio-activity-based interruptions during the warmup window.
Without warmup, VAD-based interruption fires at 4.0 + 0.5 = 4.5s.
With warmup (3.0s from speaking at 3.5s, expires at 6.5s), the VAD path is blocked.
The interruption is delayed to 5.5s (EOU: speech end 5.0 + 0.5 endpointing delay)
because FakeSTT is timer-based and still produces transcripts during warmup.
"""
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Tell me a story.")
actions.add_llm("Here is a long story for you ... the end.")
actions.add_tts(15.0) # playout starts at 3.5s
# user speaks at 4.0-5.0s — within warmup window (3.5 + 3.0 = 6.5s expiry)
# without warmup: VAD interruption at 4.0 + 0.5 = 4.5s
# with warmup: VAD blocked, falls through to EOU at 5.0 + 0.5 = 5.5s
actions.add_user_speech(4.0, 5.0, "Stop!", stt_delay=0.2)
session = create_session(
actions,
speed_factor=speed,
extra_kwargs={"aec_warmup_duration": 3.0},
)
agent = MyAgent()
agent_state_events: list[AgentStateChangedEvent] = []
playback_finished_events: list[PlaybackFinishedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.output.audio.on("playback_finished", playback_finished_events.append)
t_origin = await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
assert len(playback_finished_events) == 1
assert playback_finished_events[0].interrupted is True
assert agent_state_events[0].new_state == "listening"
assert agent_state_events[1].new_state == "thinking"
assert agent_state_events[2].new_state == "speaking"
# interruption delayed to 5.5s (EOU), not 4.5s (VAD was blocked by warmup)
speaking_to_listening = next(e for e in agent_state_events[3:] if e.new_state == "listening")
check_timestamp(speaking_to_listening.created_at - t_origin, 5.5, speed_factor=speed)
async def test_start_boundary_does_not_block_vad_interruption() -> None:
"""backchannel boundary should not interfere with VAD-based interruption when adaptive
detection is not active. The cooldown timer runs but has no effect on the VAD path.
This validates that the backchannel_boundary config is properly handled and doesn't
regress normal interruption behavior.
"""
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "Tell me a story.")
actions.add_llm("Here is a long story for you ... the end.")
actions.add_tts(15.0) # playout starts at ~3.5s
# user speaks at 4.0-5.0s — within the 1s warmup window (3.5 + 1.0 = 4.5s expiry)
# VAD interruption at 4.0 + 0.5 = 4.5s (warmup does NOT block VAD)
actions.add_user_speech(4.0, 5.0, "Stop!", stt_delay=0.2)
session = create_session(
actions,
speed_factor=speed,
extra_kwargs={"aec_warmup_duration": None},
)
agent = MyAgent()
agent_state_events: list[AgentStateChangedEvent] = []
playback_finished_events: list[PlaybackFinishedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.output.audio.on("playback_finished", playback_finished_events.append)
t_origin = await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
assert len(playback_finished_events) == 1
assert playback_finished_events[0].interrupted is True
assert agent_state_events[0].new_state == "listening"
assert agent_state_events[1].new_state == "thinking"
assert agent_state_events[2].new_state == "speaking"
# VAD interruption fires normally at ~4.5s (warmup doesn't block VAD path)
speaking_to_listening = next(e for e in agent_state_events[3:] if e.new_state == "listening")
check_timestamp(speaking_to_listening.created_at - t_origin, 4.5, speed_factor=speed)
async def test_backchannel_boundary_suppresses_start_boundary_backchannel() -> None:
actions = FakeActions()
session = create_session(
actions,
turn_handling={"interruption": {"backchannel_boundary": (0.05, 0.0)}},
)
hooks = _TestRecognitionHooks()
recognition = AudioRecognition(
session,
hooks=hooks,
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="vad",
)
try:
recognition._on_start_of_agent_speech(started_at=time.time())
# backchannels during the cooldown are dropped
event = _backchannel_event()
hooks.on_overlap_speech(event)
recognition._on_overlap_speech_event(event)
assert hooks.interruptions == []
# a real interruption during the cooldown must still fire
event = _interruption_event()
hooks.on_overlap_speech(event)
recognition._on_overlap_speech_event(event)
assert len(hooks.interruptions) == 1
# after cooldown, both event types behave normally
await asyncio.sleep(0.06)
backchannel_event = _backchannel_event()
hooks.on_overlap_speech(backchannel_event)
recognition._on_overlap_speech_event(backchannel_event)
interruption_event = _interruption_event()
hooks.on_overlap_speech(interruption_event)
recognition._on_overlap_speech_event(interruption_event)
assert len(hooks.interruptions) == 2
finally:
await _close_test_session(session)
async def _make_stt_eos_recognition() -> AudioRecognition:
return AudioRecognition(
create_session(FakeActions()),
hooks=_TestRecognitionHooks(),
endpointing=BaseEndpointing(min_delay=0.0, max_delay=0.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="stt",
)
async def test_stt_eos_resets_active_vad_stream_without_restarting_vad() -> None:
recognition = await _make_stt_eos_recognition()
recognition._speaking = True
recognition._vad_speech_started = True
recognition._vad = MagicMock()
resettable_stream = MagicMock()
recognition._vad_stream = resettable_stream
try:
with patch.object(recognition, "_update_vad") as update_vad:
await recognition._on_stt_event(SpeechEvent(type=SpeechEventType.END_OF_SPEECH))
resettable_stream.flush.assert_called_once_with()
update_vad.assert_not_called()
assert recognition._vad_stream is resettable_stream
finally:
if recognition._end_of_turn_task is not None:
await aio.cancel_and_wait(recognition._end_of_turn_task)
await _close_test_session(recognition._session)
async def test_stt_eos_falls_back_to_update_vad_when_no_active_stream() -> None:
recognition = await _make_stt_eos_recognition()
recognition._speaking = True
recognition._vad_speech_started = True
recognition._vad = MagicMock()
recognition._vad_stream = None
try:
with patch.object(recognition, "_update_vad") as update_vad:
await recognition._on_stt_event(SpeechEvent(type=SpeechEventType.END_OF_SPEECH))
update_vad.assert_called_once_with(recognition._vad)
finally:
if recognition._end_of_turn_task is not None:
await aio.cancel_and_wait(recognition._end_of_turn_task)
await _close_test_session(recognition._session)
async def test_backchannel_boundary_releases_end_boundary_transcript() -> None:
actions = FakeActions()
session = create_session(
actions,
turn_handling={"interruption": {"backchannel_boundary": (0.0, 0.5)}},
)
recognition = AudioRecognition(
session,
hooks=_TestRecognitionHooks(),
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="manual",
)
recognition._interruption_enabled = True
recognition._interruption_ch = aio.Chan[inference.InterruptionDataFrameType]()
try:
recognition._on_start_of_agent_speech(started_at=8.0)
recognition._on_start_of_speech(started_at=8.1)
await recognition._on_stt_event(
_final_transcript_event(
text="before the boundary", start_time=0.0, end_time=0.0, created_at=9.0
)
)
await recognition._on_stt_event(
_final_transcript_event(
text="near the boundary",
start_time=10_000.0,
end_time=20_000.0,
created_at=9.75,
)
)
recognition._on_end_of_agent_speech(ended_at=10.0)
await recognition._on_stt_event(
_final_transcript_event(
text="after agent", start_time=0.0, end_time=0.0, created_at=10.1
)
)
assert recognition._hooks.final_transcripts == [ # type: ignore[attr-defined]
"near the boundary",
"after agent",
]
finally:
recognition._interruption_ch.close()
await _close_test_session(session)
async def test_interruption_detection_error_is_not_session_error() -> None:
actions = FakeActions()
session = create_session(actions)
activity = AgentActivity(MyAgent(), session)
fallback = Mock()
activity._fallback_to_vad_interruption = fallback
error_events: list[object] = []
session.on("error", error_events.append)
try:
recoverable = inference.InterruptionDetectionError(
label="test",
error=RuntimeError("temporary failure"),
recoverable=True,
)
activity._on_error(recoverable)
unrecoverable = inference.InterruptionDetectionError(
label="test",
error=RuntimeError("adaptive unavailable"),
recoverable=False,
)
activity._on_error(unrecoverable)
assert error_events == []
fallback.assert_called_once_with(unrecoverable)
finally:
await _close_test_session(session)
async def test_stt_errors_use_unrecoverable_error_tolerance() -> None:
from livekit.agents.voice.agent_session import SessionConnectOptions
session = create_session(
FakeActions(),
extra_kwargs={"conn_options": SessionConnectOptions(max_unrecoverable_errors=1)},
)
def _stt_error() -> STTError:
return STTError(
timestamp=time.time(),
label="test",
error=RuntimeError("stt unavailable"),
recoverable=False,
)
try:
# first unrecoverable error is tolerated, like llm/tts
session._on_error(_stt_error())
assert session._closing_task is None
assert session._stt_error_counts == 1
# exceeding the tolerance closes the session
session._on_error(_stt_error())
assert session._closing_task is not None
await session._closing_task
finally:
await _close_test_session(session)
async def test_reset_away_timer_restarts_the_full_timeout() -> None:
async with LiveSession(
vad=None, turn_handling={"turn_detection": None}, user_away_timeout=3.0
) as session:
user_states: list[str] = []
session.on("user_state_changed", lambda ev: user_states.append(ev.new_state))
await session.start(MyAgent())
for _ in range(2):
await asyncio.sleep(2.0)
session.reset_away_timer()
await asyncio.sleep(2.0)
assert session.user_state == "listening"
assert user_states == []
await asyncio.sleep(2.0)
assert session.user_state == "away"
assert user_states == ["away"]
@pytest.mark.parametrize("agent_state", ["listening", "speaking", "thinking"])
async def test_reset_away_timer_returns_away_user_to_listening(agent_state: AgentState) -> None:
async with LiveSession(
vad=None, turn_handling={"turn_detection": None}, user_away_timeout=3.0
) as session:
transitions: list[tuple[str, str]] = []
session.on(
"user_state_changed", lambda ev: transitions.append((ev.old_state, ev.new_state))
)
await session.start(MyAgent())
await asyncio.sleep(4.0)
assert session.user_state == "away"
session._update_agent_state(agent_state)
session.reset_away_timer()
assert session.user_state == "listening"
assert transitions == [("listening", "away"), ("away", "listening")]
await asyncio.sleep(2.0)
assert session.user_state == "listening"
await asyncio.sleep(2.0)
assert session.user_state == ("away" if agent_state == "listening" else "listening")
@pytest.mark.parametrize(
("user_state", "agent_state"),
[("speaking", "listening"), ("listening", "speaking"), ("listening", "thinking")],
)
async def test_reset_away_timer_preserves_active_turns(
user_state: UserState, agent_state: AgentState
) -> None:
async with LiveSession(
vad=None, turn_handling={"turn_detection": None}, user_away_timeout=3.0
) as session:
await session.start(MyAgent())
session._update_user_state(user_state)
session._update_agent_state(agent_state)
session.reset_away_timer()
await asyncio.sleep(4.0)
assert session.user_state == user_state
assert session.agent_state == agent_state
session._update_user_state("listening")
session._update_agent_state("listening")
await asyncio.sleep(4.0)
assert session.user_state == "away"
async def test_reset_away_timer_is_noop_when_disabled() -> None:
async with LiveSession(
vad=None, turn_handling={"turn_detection": None}, user_away_timeout=None
) as session:
await session.start(MyAgent())
session.reset_away_timer()
await asyncio.sleep(30.0)
assert session.user_state == "listening"
assert session._user_away_timer is None
async def test_reset_away_timer_is_noop_outside_session_lifetime() -> None:
async with LiveSession(
vad=None, turn_handling={"turn_detection": None}, user_away_timeout=3.0
) as session:
session.reset_away_timer()
assert session._user_away_timer is None
await session.start(MyAgent())
timer = session._user_away_timer
session.shutdown()
session.reset_away_timer()
assert session._user_away_timer is timer
await session.aclose()
session.reset_away_timer()
await asyncio.sleep(4.0)
assert session.user_state == "listening"
assert session._user_away_timer is None
async def test_final_transcript_resets_away_timer_when_not_speaking() -> None:
session = create_session(FakeActions(), extra_kwargs={"user_away_timeout": 15.0})
try:
session._agent_state = "listening"
session._user_state = "listening"
with patch.object(session, "_set_user_away_timer") as set_timer:
session._user_input_transcribed(
UserInputTranscribedEvent(transcript="hello", is_final=True)
)
set_timer.assert_called_once()
assert session.user_state == "listening"
with patch.object(session, "_set_user_away_timer") as set_timer:
session._user_input_transcribed(
UserInputTranscribedEvent(transcript="hello", is_final=False)
)
set_timer.assert_not_called()
session._user_state = "speaking"
with patch.object(session, "_set_user_away_timer") as set_timer:
session._user_input_transcribed(
UserInputTranscribedEvent(transcript="hello", is_final=True)
)
set_timer.assert_not_called()
finally:
await _close_test_session(session)
async def test_stt_error_count_resets_on_user_transcript() -> None:
from livekit.agents.voice.agent_session import SessionConnectOptions
session = create_session(
FakeActions(),
extra_kwargs={"conn_options": SessionConnectOptions(max_unrecoverable_errors=1)},
)
def _stt_error() -> STTError:
return STTError(
timestamp=time.time(),
label="test",
error=RuntimeError("stt unavailable"),
recoverable=False,
)
try:
session._on_error(_stt_error())
assert session._stt_error_counts == 1
# a real transcript means the stt recovered -> tolerance resets
session._user_input_transcribed(
UserInputTranscribedEvent(transcript="hello", is_final=True)
)
assert session._stt_error_counts == 0
# an empty placeholder transcript is not a recovery -> no reset
session._on_error(_stt_error())
session._user_input_transcribed(UserInputTranscribedEvent(transcript="", is_final=False))
assert session._stt_error_counts == 1
# tolerance still trips once the (reset) budget is exhausted again
session._on_error(_stt_error())
assert session._closing_task is not None
await session._closing_task
finally:
await _close_test_session(session)
async def test_stt_pipeline_recreates_stream_after_unrecoverable_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from livekit.agents.voice import audio_recognition
from livekit.agents.voice.audio_recognition import _STTPipeline
monkeypatch.setattr(audio_recognition, "_STT_RECONNECT_INTERVAL", 0.0)
attempts = 0
async def stt_node(audio, model_settings): # type: ignore[no-untyped-def]
nonlocal attempts
attempts += 1
if attempts == 1:
raise APIConnectionError("stt unavailable")
yield SpeechEvent(
type=SpeechEventType.FINAL_TRANSCRIPT,
alternatives=[SpeechData(text="recovered", language="en")],
)
# stay open like a live stream until the pipeline is closed
async for _ in audio:
pass
pipeline = _STTPipeline(stt_node)
try:
# the first stream dies on a connection error; the pump must recreate it
# and forward the transcript produced by the second stream
ev = await asyncio.wait_for(pipeline.event_ch.recv(), timeout=5)
assert ev.type == SpeechEventType.FINAL_TRANSCRIPT
assert ev.alternatives[0].text == "recovered"
assert ev.created_at > 0
assert attempts == 2
finally:
await pipeline.aclose()
async def test_stt_pipeline_does_not_recreate_on_non_connection_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from livekit.agents.voice import audio_recognition
from livekit.agents.voice.audio_recognition import _STTPipeline
monkeypatch.setattr(audio_recognition, "_STT_RECONNECT_INTERVAL", 0.0)
attempts = 0
async def stt_node(audio, model_settings): # type: ignore[no-untyped-def]
nonlocal attempts
attempts += 1
raise ValueError("bug in stt_node")
yield # pragma: no cover - makes this an async generator
# a non-connection error is not retried: the pump stops instead of looping
pipeline = _STTPipeline(stt_node)
try:
events: list[SpeechEvent] = []
async def _collect() -> None:
async for ev in pipeline.event_ch:
events.append(ev)
await asyncio.wait_for(_collect(), timeout=5)
assert events == []
assert attempts == 1
finally:
await pipeline.aclose()
async def test_stt_pipeline_does_not_recreate_stream_while_closing(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from livekit.agents.voice import audio_recognition
from livekit.agents.voice.audio_recognition import _STTPipeline
monkeypatch.setattr(audio_recognition, "_STT_RECONNECT_INTERVAL", 0.0)
attempts = 0
async def stt_node(audio, model_settings): # type: ignore[no-untyped-def]
nonlocal attempts
attempts += 1
if attempts == 1:
raise APIConnectionError("stt unavailable")
yield SpeechEvent(
type=SpeechEventType.FINAL_TRANSCRIPT,
alternatives=[SpeechData(text="recovered", language="en")],
)
# session already closing: the pump must not spawn a replacement stream
pipeline = _STTPipeline(stt_node, is_closing=lambda: True)
try:
events: list[SpeechEvent] = []
async def _collect() -> None:
async for ev in pipeline.event_ch:
events.append(ev)
await asyncio.wait_for(_collect(), timeout=5)
assert events == []
assert attempts == 1
finally:
await pipeline.aclose()
async def test_stt_pipeline_recreation_uses_rebound_node(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from livekit.agents.voice import audio_recognition
from livekit.agents.voice.audio_recognition import _STTPipeline
monkeypatch.setattr(audio_recognition, "_STT_RECONNECT_INTERVAL", 0.0)
started_old = asyncio.Event()
fail_old = asyncio.Event()
async def old_node(audio, model_settings): # type: ignore[no-untyped-def]
# the stream captured from the previous agent, still running at handoff
started_old.set()
await fail_old.wait()
raise APIConnectionError("stt unavailable")
yield # pragma: no cover - makes this an async generator
async def new_node(audio, model_settings): # type: ignore[no-untyped-def]
yield SpeechEvent(
type=SpeechEventType.FINAL_TRANSCRIPT,
alternatives=[SpeechData(text="recovered", language="en")],
)
async for _ in audio:
pass
# a handoff reuses the pipeline but rebinds it to the new agent's node; the
# recreation after the old stream fails must use that rebound node, not the
# previous agent's (whose activity would be torn down)
pipeline = _STTPipeline(old_node)
try:
await asyncio.wait_for(started_old.wait(), timeout=5)
pipeline._rebind_node(new_node)
fail_old.set()
ev = await asyncio.wait_for(pipeline.event_ch.recv(), timeout=5)
assert ev.type == SpeechEventType.FINAL_TRANSCRIPT
assert ev.alternatives[0].text == "recovered"
finally:
await pipeline.aclose()
async def test_vad_fallback_uses_next_vad_inference_event(
caplog: pytest.LogCaptureFixture,
) -> None:
actions = FakeActions()
session = create_session(actions)
activity = AgentActivity(MyAgent(), session)
error = inference.InterruptionDetectionError(
label="test",
error=RuntimeError("adaptive unavailable"),
recoverable=False,
)
audio_recognition = MagicMock()
current_speech = MagicMock()
current_speech.interrupted = False
current_speech.allow_interruptions = True
activity._audio_recognition = audio_recognition
activity._current_speech = current_speech
activity._interruption_detection_enabled = True
activity._interruption_by_audio_activity_enabled = False
activity._default_interruption_by_audio_activity_enabled = True
caplog.set_level(logging.INFO, logger="livekit.agents")
try:
activity._fallback_to_vad_interruption(error)
audio_recognition._update_interruption_detection.assert_called_once_with(None)
current_speech.interrupt.assert_not_called()
assert activity._interruption_detection_enabled is False
assert activity._interruption_by_audio_activity_enabled is True
activity.on_vad_inference_done(
vad.VADEvent(
type=vad.VADEventType.INFERENCE_DONE,
samples_index=0,
timestamp=time.time(),
speech_duration=session.options.interruption["min_duration"] - 0.01,
silence_duration=0.0,
speaking=True,
)
)
current_speech.interrupt.assert_not_called()
activity.on_vad_inference_done(
vad.VADEvent(
type=vad.VADEventType.INFERENCE_DONE,
samples_index=0,
timestamp=time.time(),
speech_duration=session.options.interruption["min_duration"],
silence_duration=0.0,
speaking=True,
)
)
current_speech.interrupt.assert_called_once_with(source="audio_activity")
assert any(
record.levelno == logging.INFO
and "falling back to VAD-based interruption" in record.message
for record in caplog.records
)
assert not [record for record in caplog.records if record.levelno >= logging.WARNING]
finally:
await _close_test_session(session)
async def test_flush_held_transcripts_emits_buffered_events() -> None:
actions = FakeActions()
session = create_session(actions)
hooks = _TestRecognitionHooks()
recognition = AudioRecognition(
session,
hooks=hooks,
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="manual",
)
recognition._transcript_buffer.append(
_final_transcript_event(text="held transcript", start_time=0.0, end_time=1.0)
)
try:
recognition._flush_held_transcripts()
assert hooks.final_transcripts == ["held transcript"]
assert not recognition._transcript_buffer
finally:
await _close_test_session(session)
async def test_held_final_transcript_cancels_timeout_on_arrival() -> None:
session = create_session(FakeActions())
hooks = _TestRecognitionHooks()
recognition = AudioRecognition(
session,
hooks=hooks,
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="manual",
)
recognition._transcript_gate_active = True
timeout_handle = asyncio.get_running_loop().call_later(60.0, lambda: None)
recognition._transcription_timeout_handle = timeout_handle
event = _final_transcript_event(text="held transcript", start_time=0.0, end_time=1.0)
try:
await recognition._on_stt_event(event)
assert timeout_handle.cancelled()
assert recognition._turn_transcript_received
assert list(recognition._transcript_buffer) == [event]
assert hooks.final_transcripts == []
recognition._flush_held_transcripts()
assert timeout_handle.cancelled()
assert recognition._turn_transcript_received
assert hooks.final_transcripts == ["held transcript"]
assert recognition._current_transcript == "held transcript"
finally:
timeout_handle.cancel()
await _close_test_session(session)
async def test_true_verdict_releases_late_transcripts() -> None:
session = create_session(FakeActions())
hooks = _TestRecognitionHooks()
recognition = AudioRecognition(
session,
hooks=hooks,
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="manual",
)
recognition._transcript_gate_active = True
recognition._agent_speaking = True
recognition._agent_speech_started_at = time.time() - 1.0
overlap_started_at = time.time() - 0.5
recognition._transcript_buffer.append(
_final_transcript_event(
text="already held",
start_time=0.0,
end_time=0.0,
created_at=overlap_started_at,
)
)
try:
event = inference.OverlappingSpeechEvent(
is_interruption=True,
overlap_started_at=overlap_started_at,
)
hooks.on_overlap_speech(event)
recognition._on_overlap_speech_event(event)
await recognition._on_stt_event(
_final_transcript_event(text="arrived later", start_time=0.0, end_time=0.0)
)
assert hooks.final_transcripts == ["already held", "arrived later"]
assert len(hooks.interruptions) == 1
assert not recognition._transcript_buffer
finally:
await _close_test_session(session)
async def test_preflight_transcript_does_not_cancel_transcription_timeout() -> None:
session = create_session(FakeActions())
hooks = _TestRecognitionHooks()
recognition = AudioRecognition(
session,
hooks=hooks,
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="manual",
)
timeout_handle = asyncio.get_running_loop().call_later(60.0, lambda: None)
recognition._transcription_timeout_handle = timeout_handle
event = SpeechEvent(
type=SpeechEventType.PREFLIGHT_TRANSCRIPT,
alternatives=[SpeechData(text="preflight transcript", language=LanguageCode(""))],
)
try:
await recognition._on_stt_event(event)
assert not timeout_handle.cancelled()
assert recognition._turn_transcript_received is False
finally:
timeout_handle.cancel()
await _close_test_session(session)
async def test_transcription_timeout_accounts_for_vad_endpointing_delay() -> None:
session = create_session(FakeActions(), extra_kwargs={"transcription_timeout": 2.0})
recognition = AudioRecognition(
session,
hooks=_TestRecognitionHooks(),
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="vad",
)
recognition._stt_pipeline = MagicMock()
recognition._vad_speech_started = True
event_loop = asyncio.get_running_loop()
try:
await recognition._on_vad_event(
vad.VADEvent(
type=vad.VADEventType.END_OF_SPEECH,
samples_index=0,
timestamp=time.time(),
speech_duration=1.0,
silence_duration=0.5,
inference_duration=0.25,
)
)
timeout_handle = recognition._transcription_timeout_handle
assert timeout_handle is not None
assert timeout_handle.when() - event_loop.time() == pytest.approx(1.25)
finally:
recognition._stt_pipeline = None
await recognition._aclose()
await _close_test_session(session)
async def test_late_vad_eos_after_committed_turn_does_not_arm_transcription_timeout() -> None:
session = create_session(FakeActions(), extra_kwargs={"transcription_timeout": 2.0})
recognition = AudioRecognition(
session,
hooks=_TestRecognitionHooks(),
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="stt",
)
recognition._stt_pipeline = MagicMock()
recognition._vad_speech_started = False
try:
await recognition._on_vad_event(
vad.VADEvent(
type=vad.VADEventType.END_OF_SPEECH,
samples_index=0,
timestamp=time.time(),
speech_duration=1.0,
silence_duration=0.5,
)
)
assert recognition._transcription_timeout_handle is None
finally:
recognition._stt_pipeline = None
await recognition._aclose()
await _close_test_session(session)
async def test_clear_user_turn_resets_transcription_timeout() -> None:
session = create_session(FakeActions(), extra_kwargs={"transcription_timeout": 1.0})
recognition = AudioRecognition(
session,
hooks=_TestRecognitionHooks(),
endpointing=BaseEndpointing(min_delay=0.1, max_delay=1.0),
stt=None,
vad=None,
interruption_detection=None,
turn_detection="vad",
)
timeout_handle = asyncio.get_running_loop().call_later(60.0, lambda: None)
recognition._transcription_timeout_handle = timeout_handle
recognition._turn_speech_duration = 2.0
recognition._turn_transcript_received = True
recognition._user_turn_start = time.time()
try:
recognition._clear_user_turn()
assert timeout_handle.cancelled()
assert recognition._transcription_timeout_handle is None
assert recognition._turn_speech_duration == 0.0
assert recognition._turn_transcript_received is False
assert recognition._user_turn_start is None
recognition._arm_transcription_timeout(1.0, delay=0.0)
assert recognition._transcription_timeout_handle is not None
finally:
await recognition._aclose()
await _close_test_session(session)
@pytest.mark.parametrize(
"preemptive_generation, expected_latency",
[
({"preemptive_tts": True}, 0.7),
({"preemptive_tts": False}, 0.8),
({"enabled": False}, 1.1),
],
)
async def test_preemptive_generation(preemptive_generation: dict, expected_latency: float) -> None:
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.0, "Hello, how are you?", stt_delay=0.1)
actions.add_llm("I'm doing great, thank you!", ttft=0.1, duration=0.3)
actions.add_tts(3.0, ttfb=0.3)
# preemptive_generation with TTS enabled: e2e latency is 0.1+0.3+0.3=0.7s
# preemptive_generation without TTS enabled: e2e latency is max(0.1+0.3, 0.5)+0.3=0.8s
# preemptive_generation disabled: e2e latency is 0.5+0.3+0.3=1.1s
session = create_session(
actions,
speed_factor=speed,
turn_handling={"preemptive_generation": preemptive_generation},
)
agent = MyAgent()
agent_state_events: list[AgentStateChangedEvent] = []
user_state_events: list[UserStateChangedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.on("user_state_changed", user_state_events.append)
await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
assert len(user_state_events) == 2
assert user_state_events[0].old_state == "listening"
assert user_state_events[0].new_state == "speaking"
assert user_state_events[1].new_state == "listening"
t_user_stop_speaking = user_state_events[1].created_at
assert len(agent_state_events) == 4
assert agent_state_events[0].old_state == "initializing"
assert agent_state_events[0].new_state == "listening"
assert agent_state_events[1].new_state == "thinking"
assert agent_state_events[2].new_state == "speaking"
t_agent_start_speaking = agent_state_events[2].created_at
check_timestamp(
t_agent_start_speaking - t_user_stop_speaking,
t_target=expected_latency,
speed_factor=speed,
max_abs_diff=0.2,
)
assert agent_state_events[3].new_state == "listening"
@pytest.mark.parametrize(
"preflight, final, expected",
[
("hello how are you", "Hello, how are you?", True),
("مرحبا كيف حالك", "مرحبا، كيف حالك؟", True),
("نعم أريد الحجز", "نعم، أريد الحجز؛", True),
("آپ کیسے ہیں", "آپ کیسے ہیں۔", True),
("आप कैसे हैं", "आप कैसे हैं।", True),
("你好 我很好", "你好,我很好。", True),
# different words must still invalidate the preemptive generation
("مرحبا كيف حالك", "مرحبا كيف حالكم؟", False),
],
)
def test_preemptive_transcripts_equivalent(preflight: str, final: str, expected: bool) -> None:
assert _transcripts_equivalent(preflight, final) is expected
@pytest.mark.parametrize(
"preemptive_generation, expected",
[
# bool form: the legacy on/off flag
(True, {"enabled": True, "preemptive_tts": False}),
(False, {"enabled": False, "preemptive_tts": False}),
# dict form: an options mapping, documented on the same kwarg (#7343)
({"enabled": False}, {"enabled": False, "preemptive_tts": False}),
({"enabled": True, "preemptive_tts": True}, {"enabled": True, "preemptive_tts": True}),
],
)
async def test_deprecated_preemptive_generation_kwarg(
preemptive_generation: bool | dict, expected: dict
) -> None:
session = LiveSession(preemptive_generation=preemptive_generation)
opts = session.options.preemptive_generation
assert {k: opts[k] for k in expected} == expected
assert isinstance(opts["enabled"], bool)
@pytest.mark.parametrize(
"session_preemptive, agent_preemptive, expected_latency",
[
# agent disables what the session enabled -> no preemptive generation (1.1s)
({"preemptive_tts": True}, {"enabled": False}, 1.1),
# agent enables (with TTS) what the session disabled -> fully preemptive (0.7s)
({"enabled": False}, {"enabled": True, "preemptive_tts": True}, 0.7),
],
)
async def test_preemptive_generation_on_agent(
session_preemptive: dict, agent_preemptive: dict, expected_latency: float
) -> None:
# preemptive generation set on the agent must override the session value
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.0, "Hello, how are you?", stt_delay=0.1)
actions.add_llm("I'm doing great, thank you!", ttft=0.1, duration=0.3)
actions.add_tts(3.0, ttfb=0.3)
# preemptive_generation with TTS enabled: e2e latency is 0.1+0.3+0.3=0.7s
# preemptive_generation disabled: e2e latency is 0.5+0.3+0.3=1.1s
session = create_session(
actions,
speed_factor=speed,
turn_handling={"preemptive_generation": session_preemptive},
)
agent = MyAgent(turn_handling={"preemptive_generation": agent_preemptive})
agent_state_events: list[AgentStateChangedEvent] = []
user_state_events: list[UserStateChangedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.on("user_state_changed", user_state_events.append)
await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
t_user_stop_speaking = user_state_events[1].created_at
t_agent_start_speaking = agent_state_events[2].created_at
check_timestamp(
t_agent_start_speaking - t_user_stop_speaking,
t_target=expected_latency,
speed_factor=speed,
max_abs_diff=0.2,
)
@pytest.mark.parametrize(
"preemptive_generation, on_user_turn_completed_delay",
[
(False, 0.0),
(False, 2.0),
(True, 0.0),
(True, 2.0),
],
)
async def test_interrupt_during_on_user_turn_completed(
preemptive_generation: bool, on_user_turn_completed_delay: float
) -> None:
"""
Test interrupt during preemptive generation and on_user_turn_completed.
"""
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.0, "Tell me a story", stt_delay=0.2)
actions.add_llm("Here is a story for you...", ttft=0.1, duration=0.3)
actions.add_tts(10.0, ttfb=1.0) # latency after end of turn: 1.3s
actions.add_user_speech(2.6, 3.2, "about a firefighter.") # interrupt before speaking
actions.add_llm("Here is a story about a firefighter...", ttft=0.1, duration=0.3)
actions.add_tts(10.0, ttfb=0.3)
session = create_session(
actions,
speed_factor=speed,
turn_handling={"preemptive_generation": {"enabled": preemptive_generation}},
)
agent = MyAgent(on_user_turn_completed_delay=on_user_turn_completed_delay / speed)
agent_state_events: list[AgentStateChangedEvent] = []
conversation_events: list[ConversationItemAddedEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.on("conversation_item_added", conversation_events.append)
await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
assert agent_state_events[0].old_state == "initializing"
assert agent_state_events[0].new_state == "listening"
if on_user_turn_completed_delay == 0.0:
# on_user_turn_completed already committed before interrupting
assert len(agent_state_events) == 6
assert agent_state_events[1].new_state == "thinking"
assert agent_state_events[2].new_state == "listening"
assert agent_state_events[3].new_state == "thinking"
assert agent_state_events[4].new_state == "speaking"
assert agent_state_events[5].new_state == "listening"
else:
assert len(agent_state_events) == 4
assert agent_state_events[1].new_state == "thinking"
assert agent_state_events[2].new_state == "speaking"
assert agent_state_events[3].new_state == "listening"
assert len(conversation_events) == 4
assert conversation_events[0].item.type == "agent_handoff"
assert conversation_events[1].item.type == "message"
assert conversation_events[1].item.role == "user"
assert conversation_events[1].item.text_content == "Tell me a story"
assert conversation_events[2].item.type == "message"
assert conversation_events[2].item.role == "user"
assert conversation_events[2].item.text_content == "about a firefighter."
assert conversation_events[3].item.type == "message"
assert conversation_events[3].item.role == "assistant"
assert conversation_events[3].item.text_content == "Here is a story about a firefighter..."
async def test_tool_internal_exception_returns_generic_error() -> None:
"""When a tool body raises a non-ToolError exception, the model receives
the generic "An internal error occurred" message so we don't leak internal
details. Validation-error path is tested separately."""
class _BrokenToolAgent(Agent):
def __init__(self) -> None:
super().__init__(instructions="You are a helpful assistant.")
@function_tool
async def get_weather(self, location: str) -> str:
"""Always blows up."""
raise RuntimeError("kaboom: secret database password leaked")
speed = 1
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "What's the weather in Tokyo?")
actions.add_llm(
content="",
tool_calls=[
FunctionToolCall(name="get_weather", arguments='{"location": "Tokyo"}', call_id="1"),
],
)
session = create_session(actions, speed_factor=speed)
agent = _BrokenToolAgent()
tool_executed_events: list[FunctionToolsExecutedEvent] = []
session.on("function_tools_executed", tool_executed_events.append)
await asyncio.wait_for(run_session(session, agent), timeout=SESSION_TIMEOUT)
assert len(tool_executed_events) == 1
output = tool_executed_events[0].function_call_outputs[0]
assert output is not None
assert output.is_error is True
# Generic message — the RuntimeError details must NOT leak to the model.
assert output.output == "An internal error occurred"
assert "kaboom" not in output.output
assert "secret" not in output.output
# helpers
class _TestRecognitionHooks:
def __init__(self) -> None:
self.interruptions: list[inference.OverlappingSpeechEvent] = []
self.final_transcripts: list[str] = []
self.interruption_by_audio_activity_enabled = False
def on_overlap_speech(self, ev: inference.OverlappingSpeechEvent) -> None:
if ev.is_interruption:
self.interruptions.append(ev)
def on_backchannel_confirmed(self) -> None:
pass
def on_start_of_speech(self, ev: object, speech_start_time: float) -> None:
pass
def on_vad_inference_done(self, ev: object) -> None:
pass
def on_end_of_speech(self, ev: object) -> None:
pass
def on_interim_transcript(self, ev: SpeechEvent, *, speaking: bool | None) -> None:
pass
def on_final_transcript(self, ev: SpeechEvent, *, speaking: bool | None = None) -> None:
self.final_transcripts.append(ev.alternatives[0].text)
def on_end_of_turn(self, info: _EndOfTurnInfo) -> bool:
return True
def on_preemptive_generation(self, info: object) -> None:
pass
def retrieve_chat_ctx(self) -> ChatContext:
return ChatContext.empty()
def _interruption_event() -> inference.OverlappingSpeechEvent:
return inference.OverlappingSpeechEvent(
type="overlapping_speech",
is_interruption=True,
overlap_started_at=time.time(),
detected_at=time.time(),
)
def _backchannel_event() -> inference.OverlappingSpeechEvent:
return inference.OverlappingSpeechEvent(
type="overlapping_speech",
is_interruption=False,
overlap_started_at=time.time(),
detected_at=time.time(),
)
def _final_transcript_event(
*, text: str, start_time: float, end_time: float, created_at: float | None = None
) -> SpeechEvent:
ev = SpeechEvent(
type=SpeechEventType.FINAL_TRANSCRIPT,
alternatives=[
SpeechData(
text=text,
language=LanguageCode(""),
start_time=start_time,
end_time=end_time,
)
],
)
if created_at is not None:
ev.created_at = created_at
return ev
async def _close_test_session(session: object) -> None:
await session.aclose()
audio_output = session.output.audio
synchronizer = getattr(audio_output, "_synchronizer", None)
if synchronizer is not None:
await synchronizer.aclose()
def check_timestamp(
t_event: float,
t_target: float,
*,
speed_factor: float = 1.0,
max_abs_diff: float = 0.75,
min_real_time_diff: float = 0.3,
) -> None:
"""
Check if the event timestamp is within the target timestamp +/- max_abs_diff.
The event timestamp is scaled by the speed factor.
``max_abs_diff`` is expressed in scaled time. A real-time floor of
``min_real_time_diff`` (wallclock seconds) is also applied so high
``speed_factor`` values don't compress the effective tolerance below the
scheduling-jitter noise floor on CI runners — without this, the real-time
tolerance is ``max_abs_diff / speed_factor``, which at speed=5 is only
150 ms and routinely flakes.
"""
t_event_scaled = t_event * speed_factor
effective_diff = max(max_abs_diff, min_real_time_diff * speed_factor)
print(
f"check_timestamp: t_event={t_event_scaled} (real {t_event:.3f}s), "
f"t_target={t_target}, effective_diff={effective_diff} "
f"(max_abs_diff={max_abs_diff}, min_real_time_diff={min_real_time_diff})"
)
assert abs(t_event_scaled - t_target) <= effective_diff, (
f"event timestamp {t_event_scaled} is not within {effective_diff} of target {t_target} "
f"(real-time tolerance {effective_diff / speed_factor:.3f}s)"
)
async def test_silent_tool_call_pause_state_does_not_leak_into_tool_reply() -> None:
speed = 1
actions = FakeActions()
actions.add_user_speech(0.1, 0.2, "What's the weather in Tokyo?", stt_delay=0.05)
# Silent tool-call step: no spoken preamble/audio before the function call.
actions.add_llm(
content="",
tool_calls=[
FunctionToolCall(
name="get_weather",
arguments='{"location": "Tokyo"}',
call_id="1",
)
],
ttft=0.05,
duration=1.0,
)
# VAD-only speech starts during the silent tool-call generation and remains
# active after the tool reply starts.
actions.add_user_speech(0.85, 2.0, "", stt_delay=0.05)
actions.add_llm(
content="The weather in Tokyo is sunny today.",
input="The weather in Tokyo is sunny today.",
ttft=0.0,
duration=0.0,
)
actions.add_tts(0.5, ttfb=0.0, duration=0.0)
session = create_session(
actions,
speed_factor=speed,
can_pause_audio=True,
turn_handling={"interruption": {"false_interruption_timeout": 0.2 / speed}},
)
agent = MyAgent()
agent_state_events: list[AgentStateChangedEvent] = []
false_interruption_events: list[AgentFalseInterruptionEvent] = []
session.on("agent_state_changed", agent_state_events.append)
session.on("agent_false_interruption", false_interruption_events.append)
await asyncio.wait_for(
run_session(session, agent, drain_delay=0.8 / speed),
timeout=SESSION_TIMEOUT,
)
transitions = [(ev.old_state, ev.new_state) for ev in agent_state_events]
silent_step_finished = transitions.index(("speaking", "listening"))
# Before the fix this is ("listening", "thinking") because the pause state
# captured during the silent tool-call step leaks into the tool reply.
assert transitions[silent_step_finished + 1] == ("listening", "speaking")
assert false_interruption_events
assert false_interruption_events[-1].resumed is True
async def test_default_vad_is_auto_provisioned() -> None:
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession()
try:
assert session.vad is not None
assert session._using_default_vad is True
finally:
await session.aclose()
async def test_explicit_vad_none_opts_out() -> None:
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(vad=None)
try:
assert session.vad is None
assert session._using_default_vad is False
finally:
await session.aclose()
async def test_user_supplied_vad_clears_default_flag() -> None:
from livekit.agents.voice.agent_session import LiveSession
from .fake_vad import FakeVAD
user_vad = FakeVAD(fake_user_speeches=[])
session = LiveSession(vad=user_vad)
try:
assert session.vad is user_vad
assert session._using_default_vad is False
finally:
await session.aclose()
async def test_default_turn_detection_builds_default_eot() -> None:
"""No turn_detection given → session auto-provisions a default TurnDetector."""
from livekit.agents.voice.agent_session import LiveSession
from livekit.agents.voice.turn import _StreamingTurnDetector
session = LiveSession()
try:
assert isinstance(session.turn_detection, _StreamingTurnDetector)
finally:
await session.aclose()
async def test_turn_detection_none_opts_out() -> None:
"""Explicit None opts out of turn detection (no default detector built)."""
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(turn_handling={"turn_detection": None})
try:
assert session.turn_detection is None
finally:
await session.aclose()
async def test_user_supplied_turn_detector_passes_through() -> None:
from livekit.agents import inference
from livekit.agents.voice.agent_session import LiveSession
user_detector = inference.TurnDetector(version="v1-mini")
session = LiveSession(turn_handling={"turn_detection": user_detector})
try:
assert session.turn_detection is user_detector
finally:
await session.aclose()
async def test_stt_context_options_defaults_forward_chat_context_on() -> None:
"""forward_chat_context is on by default in the resolved stt_context_options."""
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(vad=None)
try:
assert session._opts.stt_context_options["forward_chat_context"] is True
finally:
await session.aclose()
async def test_stt_context_options_passthrough() -> None:
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(
vad=None,
stt_context_options={"keyterms": ["LiveKit"], "forward_chat_context": False},
)
try:
opts = session._opts.stt_context_options
assert opts["keyterms"] == ["LiveKit"]
assert opts["forward_chat_context"] is False
finally:
await session.aclose()
async def test_deprecated_keyterms_options_maps_to_stt_context(caplog) -> None:
"""keyterms_options still works, maps onto stt_context_options, and warns."""
from livekit.agents.voice.agent_session import LiveSession
with caplog.at_level(logging.WARNING):
session = LiveSession(vad=None, keyterms_options={"keyterms": ["Acme"]})
try:
opts = session._opts.stt_context_options
assert opts["keyterms"] == ["Acme"]
assert opts["forward_chat_context"] is True # default still applies
assert "keyterms_options is deprecated" in caplog.text
finally:
await session.aclose()
async def test_stt_context_options_wins_over_keyterms_options() -> None:
"""When both are passed, stt_context_options takes precedence over the deprecated option."""
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(
vad=None,
stt_context_options={"keyterms": ["new"]},
keyterms_options={"keyterms": ["old"]},
)
try:
assert session._opts.stt_context_options["keyterms"] == ["new"]
finally:
await session.aclose()
async def test_streaming_detector_uses_streaming_endpointing_defaults() -> None:
"""Default session → streaming detector → tighter 0.3/2.5 endpointing defaults."""
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession()
try:
assert session._opts.endpointing["min_delay"] == 0.3
assert session._opts.endpointing["max_delay"] == 2.5
assert session._opts.endpointing_overrides == {}
finally:
await session.aclose()
async def test_non_streaming_detector_uses_legacy_endpointing_defaults() -> None:
"""A non-streaming mode keeps the legacy 0.5/3.0 defaults."""
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(turn_handling={"turn_detection": "vad"})
try:
assert session._opts.endpointing["min_delay"] == 0.5
assert session._opts.endpointing["max_delay"] == 3.0
finally:
await session.aclose()
async def test_explicit_endpointing_overrides_streaming_default_per_key() -> None:
"""An explicit delay is honored; the unset one still gets the streaming default."""
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(turn_handling={"endpointing": {"min_delay": 0.4}})
try:
assert session._opts.endpointing["min_delay"] == 0.4
assert session._opts.endpointing["max_delay"] == 2.5
assert session._opts.endpointing_overrides == {"min_delay": 0.4}
finally:
await session.aclose()
async def test_user_streaming_detector_uses_streaming_defaults() -> None:
"""A user-constructed streaming detector also triggers the streaming defaults."""
from livekit.agents import inference
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(
turn_handling={"turn_detection": inference.TurnDetector(version="v1-mini")}
)
try:
assert session._opts.endpointing["min_delay"] == 0.3
assert session._opts.endpointing["max_delay"] == 2.5
finally:
await session.aclose()
async def test_deprecated_turn_detection_vad_uses_legacy_defaults() -> None:
"""Deprecated turn_detection arg + no delays → legacy defaults (non-streaming)."""
from livekit.agents.voice.agent_session import LiveSession
session = LiveSession(turn_detection="vad")
try:
assert session._opts.endpointing["min_delay"] == 0.5
assert session._opts.endpointing["max_delay"] == 3.0
finally:
await session.aclose()
async def test_agent_turn_detection_override_resolves_endpointing_per_activity() -> None:
"""endpointing_opts uses the activity's resolved detector, not just the session's."""
from livekit.agents.voice.agent_session import LiveSession
from .fake_vad import FakeVAD
# session default → streaming detector; provide VAD so it validates
session = LiveSession(vad=FakeVAD(fake_user_speeches=[]))
try:
streaming_activity = AgentActivity(Agent(instructions="test"), session)
assert streaming_activity.endpointing_opts["min_delay"] == 0.3
assert streaming_activity.endpointing_opts["max_delay"] == 2.5
# an agent overriding to VAD falls back to legacy defaults for this activity
vad_activity = AgentActivity(Agent(instructions="test", turn_detection="vad"), session)
assert vad_activity.endpointing_opts["min_delay"] == 0.5
assert vad_activity.endpointing_opts["max_delay"] == 3.0
finally:
await session.aclose()
@pytest.mark.parametrize(
("session_min_delay", "agent_min_delay", "reply_held"),
[
pytest.param(0.2, 1.0, True, id="agent-holds-longer"),
pytest.param(1.0, 0.2, False, id="agent-releases-earlier"),
],
)
async def test_reply_holdoff_uses_agent_endpointing_delay(
session_min_delay: float, agent_min_delay: float, reply_held: bool
) -> None:
"""VAD silence uses the active agent's delay for pending reply hold-off."""
from livekit.agents.voice.agent_session import LiveSession
from .fake_vad import FakeVAD
session = LiveSession(
vad=FakeVAD(fake_user_speeches=[]),
turn_handling={
"turn_detection": "vad",
"endpointing": {"min_delay": session_min_delay},
},
)
try:
activity = AgentActivity(
Agent(
instructions="test",
turn_handling={"endpointing": {"min_delay": agent_min_delay}},
),
session,
)
assert activity.endpointing_opts["min_delay"] == agent_min_delay
activity.on_vad_inference_done(
vad.VADEvent(
type=vad.VADEventType.INFERENCE_DONE,
samples_index=0,
timestamp=0.0,
speech_duration=0.0,
silence_duration=0.25,
speaking=True,
raw_accumulated_silence=0.25,
)
)
assert activity._user_silence_event.is_set() == (not reply_held)
finally:
await session.aclose()
async def test_runtime_endpointing_opts_survive_handoff() -> None:
"""update_options changes are recorded as overrides, so a new activity keeps them."""
from livekit.agents.voice.agent_session import LiveSession
from .fake_vad import FakeVAD
session = LiveSession(vad=FakeVAD(fake_user_speeches=[]))
try:
session.update_options(endpointing_opts={"mode": "dynamic", "alpha": 0.5, "min_delay": 0.4})
# a fresh activity (as built on agent handoff) re-resolves from overrides
activity = AgentActivity(Agent(instructions="test"), session)
assert activity.endpointing_opts["mode"] == "dynamic"
assert activity.endpointing_opts["alpha"] == 0.5
assert activity.endpointing_opts["min_delay"] == 0.4
# untouched key still gets the streaming default
assert activity.endpointing_opts["max_delay"] == 2.5
finally:
await session.aclose()
class FlushMultiSegmentAgent(Agent):
"""Agent whose llm_node flushes the reply into two segments via FlushSentinel."""
def __init__(self) -> None:
super().__init__(instructions="You are a helpful assistant.")
async def llm_node(
self,
chat_ctx: ChatContext,
tools: list,
model_settings: ModelSettings,
) -> AsyncIterable[str | FlushSentinel]:
yield "Hello there. "
yield FlushSentinel()
yield "How are you?"