import asyncio import contextlib import gc import pytest from google.cloud.speech_v1.types import cloud_speech as cloud_speech_v1 from google.cloud.speech_v2.types import cloud_speech as cloud_speech_v2 from google.protobuf.duration_pb2 import Duration from livekit import rtc from livekit.agents import APIConnectionError, APIConnectOptions, LanguageCode from livekit.agents.stt import ( STT as BaseSTT, SpeechData, SpeechEvent, SpeechEventType, STTCapabilities, ) from livekit.agents.types import NOT_GIVEN, NotGivenOr, TranscriptChunk from livekit.agents.utils.aio import ChanClosed from livekit.plugins.google.stt import ( SpeechStream, STTOptions, _recognize_response_to_speech_event, # pyright: ignore[reportPrivateUsage] _streaming_recognize_response_to_speech_data, # pyright: ignore[reportPrivateUsage] ) pytestmark = pytest.mark.plugin("google") @pytest.fixture def mock_google_adc(monkeypatch): from livekit.plugins.google import stt as google_stt monkeypatch.setattr(google_stt, "gauth_default", lambda: (None, "test-project")) class _FakeSTT(BaseSTT): model = "default" provider = "Google Cloud Platform" def __init__(self) -> None: super().__init__(capabilities=STTCapabilities(streaming=True, interim_results=True)) async def _recognize_impl( self, buffer: list[rtc.AudioFrame] | rtc.AudioFrame, *, language: NotGivenOr[str] = NOT_GIVEN, conn_options: APIConnectOptions, ) -> SpeechEvent: raise NotImplementedError("only the Google streaming transport is under test") class _FakeStreamingCall: def __init__(self, requests): self._requests = requests self._consumer_task = asyncio.create_task(self._consume_requests()) self.awaiting_audio = asyncio.Event() self.consumer_done = asyncio.Event() async def _consume_requests(self): try: await self._requests.__anext__() self.awaiting_audio.set() await self._requests.__anext__() finally: self.consumer_done.set() def cancel(self): self._consumer_task.cancel() def __aiter__(self): return self async def __anext__(self): await self.awaiting_audio.wait() raise StopAsyncIteration class _FakeSpeechClient: def __init__(self): self.call: _FakeStreamingCall | None = None self.call_ready = asyncio.Event() async def streaming_recognize(self, *, requests, timeout=None, retry=None): self.call = _FakeStreamingCall(requests) self.call_ready.set() return self.call class _FakeConnectionPool: last_acquire_time = 0.0 last_connection_reused = False def __init__(self, client): self._client = client @contextlib.asynccontextmanager async def connection(self, *, conn_options): yield self._client def remove(self, _client): pass def _default_stt_options() -> STTOptions: return STTOptions( languages=[LanguageCode("en-US")], detect_language=True, interim_results=True, punctuate=True, spoken_punctuation=False, enable_word_time_offsets=True, enable_word_confidence=False, enable_voice_activity_events=False, model="default", sample_rate=16000, min_confidence_threshold=0.65, profanity_filter=False, ) async def test_google_stt_premature_peer_end_reports_failure_without_leaking_chanclosed(): client = _FakeSpeechClient() owner = _FakeSTT() errors = [] owner.on("error", errors.append) stream = SpeechStream( stt=owner, conn_options=APIConnectOptions(max_retry=0, connect_timeout=0.1, read_timeout=0.1), pool=_FakeConnectionPool(client), recognizer_cb=lambda _client: "", config=_default_stt_options(), ) loop = asyncio.get_running_loop() original_exception_handler = loop.get_exception_handler() contexts = [] loop.set_exception_handler(lambda _loop, context: contexts.append(context)) try: await asyncio.wait_for(client.call_ready.wait(), timeout=1) assert client.call is not None await asyncio.wait_for(client.call.awaiting_audio.wait(), timeout=1) # The peer ends while the user input remains open. The sole attempt owner # must report that as an error, and cancel the blocked SDK input consumer. with pytest.raises( APIConnectionError, match="before input and transcript completion" ) as error: await asyncio.wait_for(stream._task, timeout=1) assert error.value.retryable is False assert len(errors) == 1 assert errors[0].error is error.value assert errors[0].recoverable is False with pytest.raises(APIConnectionError) as public_error: await anext(stream) assert public_error.value is error.value await asyncio.wait_for(client.call.consumer_done.wait(), timeout=1) await stream.aclose() for _ in range(3): gc.collect() await asyncio.sleep(0) finally: await stream.aclose() loop.set_exception_handler(original_exception_handler) unhandled_chanclosed = [ context for context in contexts if context.get("message") == "Task exception was never retrieved" and isinstance(context.get("exception"), ChanClosed) ] assert unhandled_chanclosed == [] async def test_google_stt_stream_cancel_waits_for_cleanup_if_cancelled_twice(monkeypatch): from livekit.plugins.google import stt as google_stt client = _FakeSpeechClient() stream = SpeechStream( stt=_FakeSTT(), conn_options=APIConnectOptions(max_retry=0, connect_timeout=0.1, read_timeout=0.1), pool=_FakeConnectionPool(client), recognizer_cb=lambda _client: "", config=_default_stt_options(), ) cleanup_started = asyncio.Event() cleanup_release = asyncio.Event() cleanup_done = asyncio.Event() original_cancel_and_wait = google_stt.utils.aio.cancel_and_wait async def delayed_input_cleanup(*tasks, **kwargs): if any( isinstance(task, asyncio.Task) and task.get_coro().__qualname__ == "Chan.recv" for task in tasks ): cleanup_started.set() try: await cleanup_release.wait() return await original_cancel_and_wait(*tasks, **kwargs) finally: cleanup_done.set() return await original_cancel_and_wait(*tasks, **kwargs) monkeypatch.setattr(google_stt.utils.aio, "cancel_and_wait", delayed_input_cleanup) try: await asyncio.wait_for(client.call_ready.wait(), timeout=1) assert client.call is not None await asyncio.wait_for(client.call.awaiting_audio.wait(), timeout=1) await asyncio.wait_for(cleanup_started.wait(), timeout=1) client.call.cancel() await asyncio.sleep(0) cleanup_release.set() await asyncio.wait_for(cleanup_done.wait(), timeout=1) await asyncio.wait_for(client.call.consumer_done.wait(), timeout=1) finally: cleanup_release.set() await stream.aclose() async def test_streaming_recognize_response_to_speech_data_01(): srr = cloud_speech_v2.StreamingRecognizeResponse( results=[cloud_speech_v2.StreamingRecognitionResult()] ) assert ( _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=1.0, start_time_offset=0.0 ) is None ) srr = cloud_speech_v1.StreamingRecognizeResponse( results=[cloud_speech_v1.StreamingRecognitionResult()] ) assert ( _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=1.0, start_time_offset=0.0 ) is None ) async def test_streaming_recognize_response_to_speech_data_02(): # final result should be returned regardless of confidence srr = cloud_speech_v2.StreamingRecognizeResponse( results=[ cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative(confidence=0.0, transcript="test") ], is_final=True, language_code="te-ST", ) ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.0 ) assert type(result) is SpeechData assert result.text == "test" assert result.language == "te-ST" assert result.confidence == 0.0 srr = cloud_speech_v1.StreamingRecognizeResponse( results=[ cloud_speech_v1.StreamingRecognitionResult( alternatives=[ cloud_speech_v1.SpeechRecognitionAlternative(confidence=0.0, transcript="test") ], is_final=True, language_code="te-ST", ) ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.0 ) assert type(result) is SpeechData assert result.text == "test" assert result.language == "te-ST" assert result.confidence == 0.0 async def test_streaming_recognize_response_to_speech_data_03(): srr = cloud_speech_v2.StreamingRecognizeResponse( results=[ cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative(confidence=0.0, transcript="test") ], is_final=False, ) ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.0 ) assert result is None srr = cloud_speech_v1.StreamingRecognizeResponse( results=[ cloud_speech_v1.StreamingRecognitionResult( alternatives=[ cloud_speech_v1.SpeechRecognitionAlternative(confidence=0.0, transcript="test") ], is_final=False, ) ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.0 ) assert result is None async def test_streaming_recognize_response_to_speech_data_04(): srr = cloud_speech_v2.StreamingRecognizeResponse( results=[ cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative( confidence=1.0, transcript="test01" ) ], is_final=False, language_code="te-ST", ), cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative( confidence=1.0, transcript="test02" ) ], is_final=False, language_code="te-ST", ), ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.0 ) assert type(result) is SpeechData assert result.text == "test01test02" assert result.language == "te-ST" assert result.confidence == 1.0 async def test_streaming_recognize_response_to_speech_data_05(): srr = cloud_speech_v2.StreamingRecognizeResponse( results=[ cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative( confidence=1.0, transcript="test01" ) ], is_final=False, language_code="te-ST", ), cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative( confidence=1.0, transcript="test02" ) ], is_final=False, language_code="te-ST", ), cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative(confidence=1.0, transcript="best") ], is_final=True, language_code="te-ST", ), ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.0 ) assert type(result) is SpeechData assert result.text == "best" assert result.language == "te-ST" assert result.confidence == 1.0 async def test_streaming_recognize_response_to_speech_data_words(): srr = cloud_speech_v2.StreamingRecognizeResponse( results=[ cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative( confidence=1.0, transcript="test", words=[ cloud_speech_v2.WordInfo( word="test", start_offset=Duration(seconds=0), end_offset=Duration(seconds=1), confidence=1.0, ) ], ) ], is_final=True, ) ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.0 ) assert type(result) is SpeechData assert result.text == "test" assert result.confidence == 1.0 assert result.words == [ TranscriptChunk( text="test", start_time=0.0, end_time=1.0, start_time_offset=0.0, confidence=1.0 ) ] srr = cloud_speech_v1.StreamingRecognizeResponse( results=[ cloud_speech_v1.StreamingRecognitionResult( alternatives=[ cloud_speech_v1.SpeechRecognitionAlternative( confidence=1.0, transcript="test", words=[ cloud_speech_v1.WordInfo( word="test", start_time=Duration(seconds=0), end_time=Duration(seconds=1), confidence=1.0, ) ], ) ], is_final=True, ) ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.5, start_time_offset=0.1 ) assert type(result) is SpeechData assert result.text == "test" assert result.confidence == 1.0 assert result.words == [ TranscriptChunk( text="test", start_time=0.1, end_time=1.1, start_time_offset=0.1, confidence=1.0 ) ] @pytest.mark.parametrize("is_final", [True, False]) async def test_a_result_without_word_offsets_reports_unknown_timing(is_final: bool): """chirp_3 forces ``enable_word_time_offsets=False``: its results carry no words, and their timing must stay 0 rather than the stream offset, or ``turn_detection="stt"`` reads the offset as the provider's end of speech and freezes the end-of-turn anchor.""" srr = cloud_speech_v2.StreamingRecognizeResponse( results=[ cloud_speech_v2.StreamingRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative( confidence=0.8, transcript="hello world" ) ], is_final=is_final, ) ] ) result = _streaming_recognize_response_to_speech_data( srr, min_confidence_threshold=0.0, start_time_offset=12.5 ) assert result is not None and result.text == "hello world" assert (result.start_time, result.end_time) == (0.0, 0.0) assert not result.words async def test_recognize_response_to_speech_event_words(): resp = cloud_speech_v2.RecognizeResponse( results=[ cloud_speech_v2.SpeechRecognitionResult( alternatives=[ cloud_speech_v2.SpeechRecognitionAlternative( confidence=1.0, transcript="test", words=[ cloud_speech_v2.WordInfo( word="test", start_offset=Duration(seconds=0), end_offset=Duration(seconds=1), confidence=1.0, ) ], ) ], language_code="te-ST", ) ] ) result = _recognize_response_to_speech_event(resp) assert type(result) is SpeechEvent assert result.type == SpeechEventType.FINAL_TRANSCRIPT assert result.alternatives == [ SpeechData( language=LanguageCode("te-ST"), start_time=0.0, end_time=1.0, text="test", confidence=1.0, words=[ TranscriptChunk( text="test", start_time=0.0, end_time=1.0, start_time_offset=0.0, confidence=1.0 ) ], ) ] resp = cloud_speech_v1.RecognizeResponse( results=[ cloud_speech_v1.SpeechRecognitionResult( alternatives=[ cloud_speech_v1.SpeechRecognitionAlternative( confidence=1.0, transcript="test", words=[ cloud_speech_v1.WordInfo( word="test", start_time=Duration(seconds=0), end_time=Duration(seconds=1), confidence=1.0, ) ], ) ], language_code="te-ST", ) ] ) result = _recognize_response_to_speech_event(resp) assert type(result) is SpeechEvent assert result.type == SpeechEventType.FINAL_TRANSCRIPT assert result.alternatives == [ SpeechData( language=LanguageCode("te-ST"), start_time=0.0, end_time=1.0, text="test", confidence=1.0, words=[ TranscriptChunk( text="test", start_time=0.0, end_time=1.0, start_time_offset=0.0, confidence=1.0 ) ], ) ] async def test_custom_prompt_config_update_options(mock_google_adc): """Test custom_prompt_config can be updated dynamically, and new values are ignored for models other than chirp_3.""" from livekit.agents.types import NOT_GIVEN from livekit.plugins.google import STT stt = STT(model="chirp_3") custom_prompt_config = cloud_speech_v2.CustomPromptConfig(custom_prompt="answer briefly") stt.update_options(custom_prompt_config=custom_prompt_config) assert stt._config.custom_prompt_config == custom_prompt_config # switching the model away from chirp_3 must drop the now-invalid prompt stt.update_options(model="long") assert stt._config.custom_prompt_config is NOT_GIVEN other_custom_prompt_config = cloud_speech_v2.CustomPromptConfig(custom_prompt="be verbose") stt.update_options(custom_prompt_config=other_custom_prompt_config) assert stt._config.custom_prompt_config is NOT_GIVEN async def test_custom_prompt_config_cleared_on_model_switch_from_chirp_3(mock_google_adc): """Test that switching from chirp_3 to another V2 model clears a previously configured custom_prompt_config, so it is not forwarded to a rebuilt non-streaming RecognitionConfig.""" from livekit.agents.types import NOT_GIVEN from livekit.plugins.google import STT custom_prompt_config = cloud_speech_v2.CustomPromptConfig(custom_prompt="answer briefly") stt = STT(model="chirp_3", custom_prompt_config=custom_prompt_config) assert stt._config.custom_prompt_config == custom_prompt_config stt.update_options(model="telephony") assert stt._config.custom_prompt_config is NOT_GIVEN config = stt._build_recognition_config(sample_rate=16000, num_channels=1) assert not config.features.custom_prompt_config.custom_prompt async def test_custom_prompt_config_cleared_on_stream_model_switch_from_chirp_3(mock_google_adc): """Test that SpeechStream.update_options also clears a previously configured custom_prompt_config when the model moves away from chirp_3, so an active stream's rebuilt StreamingRecognitionConfig no longer carries the stale prompt.""" from livekit.agents.types import NOT_GIVEN client = _FakeSpeechClient() custom_prompt_config = cloud_speech_v2.CustomPromptConfig(custom_prompt="answer briefly") options = _default_stt_options() options.model = "chirp_3" options.custom_prompt_config = custom_prompt_config stream = SpeechStream( stt=_FakeSTT(), conn_options=APIConnectOptions(max_retry=0, connect_timeout=0.1, read_timeout=0.1), pool=_FakeConnectionPool(client), recognizer_cb=lambda _client: "", config=options, ) try: assert stream._config.custom_prompt_config == custom_prompt_config stream.update_options(model="telephony") assert stream._config.custom_prompt_config is NOT_GIVEN streaming_config = stream._build_streaming_config() assert not streaming_config.config.features.custom_prompt_config.custom_prompt finally: await stream.aclose() async def test_custom_prompt_config_in_recognition_config(mock_google_adc): """Test custom_prompt_config is wired into the built RecognitionConfig.""" from livekit.plugins.google import STT custom_prompt_config = cloud_speech_v2.CustomPromptConfig(custom_prompt="answer briefly") stt = STT(model="chirp_3", custom_prompt_config=custom_prompt_config) config = stt._build_recognition_config(sample_rate=16000, num_channels=1) assert config.features.custom_prompt_config.custom_prompt == "answer briefly"