From a1165f4dcb6aaf7fe1007fb93bcbb9c84bbb2233 Mon Sep 17 00:00:00 2001 From: Niko Savola Date: Wed, 21 Oct 2026 22:05:22 +0300 Subject: [PATCH] Route Gemini Interactions-API-only STT models through `interactions.create` (#180410) Co-authored-by: Joost Lekkerkerker --- .../google_generative_ai_conversation/stt.py | 75 ++++- .../conftest.py | 29 ++ .../test_stt.py | 291 +++++++++++++++++- 3 files changed, 388 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/google_generative_ai_conversation/stt.py b/homeassistant/components/google_generative_ai_conversation/stt.py index 9a0c5f43cba3..dffce67c7c10 100644 --- a/homeassistant/components/google_generative_ai_conversation/stt.py +++ b/homeassistant/components/google_generative_ai_conversation/stt.py @@ -1,9 +1,15 @@ """Speech to text support for Google Generative AI.""" from collections.abc import AsyncIterable -from typing import override +import io +from typing import cast, override from google.genai.errors import APIError, ClientError +from google.genai.interactions import ( + AudioContentMimeType, + AudioContentParam, + TranscriptionConfigParam, +) from google.genai.types import Part from homeassistant.components import stt @@ -17,6 +23,17 @@ from .entity import GoogleGenerativeAILLMBaseEntity from .helpers import convert_to_wav +def _model_requires_interactions_api(model: str) -> bool: + """Return whether a model is only reachable through the Interactions API. + + Neither the SDK nor Google's model listing API documents a way to + detect this from the model itself, so this is a name-based heuristic + matched as a substring (not just a suffix) so dated/preview variants + like "gemini-3.5-transcribe-preview" are covered too. + """ + return "-transcribe" in model.rsplit("/", maxsplit=1)[-1] + + async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, @@ -238,6 +255,13 @@ class GoogleGenerativeAISttEntity( f"audio/L{metadata.bit_rate.value};rate={metadata.sample_rate.value}", ) + model = self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_STT_MODEL) + + if _model_requires_interactions_api(model): + return await self._async_transcribe_via_interactions( + model, audio_data, metadata + ) + prompt = self.subentry.data.get(CONF_PROMPT, DEFAULT_STT_PROMPT) if metadata.language: prompt = ( @@ -248,7 +272,7 @@ class GoogleGenerativeAISttEntity( try: response = await self._genai_client.aio.models.generate_content( - model=self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_STT_MODEL), + model=model, contents=[ prompt, Part.from_bytes( @@ -285,3 +309,50 @@ class GoogleGenerativeAISttEntity( ) return stt.SpeechResult(None, stt.SpeechResultState.ERROR) + + async def _async_transcribe_via_interactions( + self, + model: str, + audio_data: bytes, + metadata: stt.SpeechMetadata, + ) -> stt.SpeechResult: + """Transcribe audio through the Interactions API. + + Used for models only served this way (not generateContent), like + gemini-3.5-transcribe. This API doesn't accept a system prompt or + sampling/safety options, so those are skipped. + """ + if self.subentry.data.get(CONF_PROMPT): + LOGGER.debug("Ignoring configured STT prompt: not supported by %s", model) + + audio_content: AudioContentParam = { + "type": "audio", + "data": io.BytesIO(audio_data), + "mime_type": cast(AudioContentMimeType, f"audio/{metadata.format.value}"), + } + transcription_config: TranscriptionConfigParam = {} + if metadata.language: + transcription_config["language_codes"] = [metadata.language] + + try: + interaction = await self._genai_client.aio.interactions.create( + model=model, + store=False, + stream=False, + input=[audio_content], + generation_config={"transcription_config": transcription_config}, + ) + except Exception as err: # noqa: BLE001 + # This API has no public exception type to catch narrowly. + LOGGER.error("Error during STT: %s", err) + return stt.SpeechResult(None, stt.SpeechResultState.ERROR) + + # mypy can't narrow create()'s return type here (an SDK typing gap); + # the streaming variant can't happen since stream=False. + output_text = interaction.output_text # type: ignore[union-attr] + if output_text: + return stt.SpeechResult(output_text, stt.SpeechResultState.SUCCESS) + + status = interaction.status # type: ignore[union-attr] + LOGGER.error("STT response contained no text (status=%s)", status) + return stt.SpeechResult(None, stt.SpeechResultState.ERROR) diff --git a/tests/components/google_generative_ai_conversation/conftest.py b/tests/components/google_generative_ai_conversation/conftest.py index a1171bfd007b..e32415d2e6c1 100644 --- a/tests/components/google_generative_ai_conversation/conftest.py +++ b/tests/components/google_generative_ai_conversation/conftest.py @@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, Mock, patch from google.genai._api_client import HttpRequest, HttpResponse from google.genai.types import HttpOptionsOrDict +import httpx import pytest from pytest_homeassistant.common import MockConfigEntry @@ -185,3 +186,31 @@ def mock_genai_transport() -> Generator[AsyncMock]: mock.side_effect = request with patch("google.genai._api_client.BaseApiClient._async_request", mock): yield mock + + +@pytest.fixture +def mock_genai_interactions_transport() -> Generator[Mock]: + """Capture real SDK Interactions request construction, without HTTP requests.""" + mock = Mock() + + async def send( + self: httpx.AsyncClient, request: httpx.Request, **kwargs: object + ) -> httpx.Response: + mock(request) + return httpx.Response( + 200, + json={ + "id": "interaction-id", + "status": "completed", + "steps": [ + { + "type": "model_output", + "content": [{"type": "text", "text": "Done"}], + } + ], + }, + request=request, + ) + + with patch("httpx.AsyncClient.send", send): + yield mock diff --git a/tests/components/google_generative_ai_conversation/test_stt.py b/tests/components/google_generative_ai_conversation/test_stt.py index ad7768947209..77ba76673996 100644 --- a/tests/components/google_generative_ai_conversation/test_stt.py +++ b/tests/components/google_generative_ai_conversation/test_stt.py @@ -1,9 +1,11 @@ """Tests for the Google Generative AI Conversation STT entity.""" +import base64 from collections.abc import AsyncIterable, Generator -from unittest.mock import AsyncMock, Mock, patch +import json +from unittest.mock import AsyncMock, Mock, call, patch -from google.genai import types +from google.genai import interactions, types import pytest from pytest_homeassistant.common import MockConfigEntry @@ -15,6 +17,9 @@ from homeassistant.components.google_generative_ai_conversation.const import ( DOMAIN, RECOMMENDED_STT_MODEL, ) +from homeassistant.components.google_generative_ai_conversation.stt import ( + _model_requires_interactions_api, +) from homeassistant.config_entries import ConfigSubentry from homeassistant.const import CONF_API_KEY, CONF_PROMPT from homeassistant.core import HomeAssistant @@ -22,9 +27,23 @@ from homeassistant.core import HomeAssistant from . import API_ERROR_500, CLIENT_ERROR_BAD_REQUEST TEST_CHAT_MODEL = "models/gemini-3.1-flash-lite" +TEST_INTERACTIONS_MODEL = "models/gemini-3.5-transcribe" TEST_PROMPT = "Please transcribe the audio." +def _interaction_with_text(text: str) -> interactions.Interaction: + """Build an Interaction whose output_text resolves to the given text.""" + return interactions.Interaction( + status="completed", + steps=[ + { + "type": "model_output", + "content": [{"type": "text", "text": text}], + } + ], + ) + + async def _async_get_audio_stream(data: bytes) -> AsyncIterable[bytes]: """Yield the audio data.""" yield data @@ -47,6 +66,9 @@ def mock_genai_client() -> Generator[AsyncMock]: ] ) ) + client.aio.interactions.create = AsyncMock( + return_value=_interaction_with_text("This is a test transcription.") + ) with patch( "homeassistant.components.google_generative_ai_conversation.Client", return_value=client, @@ -58,8 +80,14 @@ def mock_genai_client() -> Generator[AsyncMock]: async def setup_integration( hass: HomeAssistant, mock_genai_client: AsyncMock, + request: pytest.FixtureRequest, ) -> None: - """Set up the test environment.""" + """Set up the test environment. + + The chat model defaults to TEST_CHAT_MODEL; override it by indirectly + parametrizing this fixture. + """ + model = getattr(request, "param", TEST_CHAT_MODEL) config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_API_KEY: "bla"}, version=2, minor_version=1 ) @@ -67,7 +95,7 @@ async def setup_integration( sub_entry = ConfigSubentry( data={ - CONF_CHAT_MODEL: TEST_CHAT_MODEL, + CONF_CHAT_MODEL: model, CONF_PROMPT: TEST_PROMPT, }, subentry_type="stt", @@ -99,6 +127,24 @@ async def test_stt_entity_properties(hass: HomeAssistant) -> None: assert stt.AudioChannels.CHANNEL_MONO in entity.supported_channels +@pytest.mark.parametrize( + ("model", "expected"), + [ + pytest.param("models/gemini-3.5-transcribe", True, id="exact"), + pytest.param( + "models/gemini-3.5-transcribe-preview", True, id="preview_variant" + ), + pytest.param("models/gemini-3.5-transcribe-001", True, id="dated_variant"), + pytest.param("gemini-3.5-transcribe", True, id="no_models_prefix"), + pytest.param(TEST_CHAT_MODEL, False, id="regular_chat_model"), + pytest.param(RECOMMENDED_STT_MODEL, False, id="recommended_stt_model"), + ], +) +def test_model_requires_interactions_api(model: str, expected: bool) -> None: + """Test the Interactions-API-only model heuristic.""" + assert _model_requires_interactions_api(model) is expected + + @pytest.mark.parametrize( ("audio_format", "call_convert_to_wav"), [ @@ -143,6 +189,7 @@ async def test_stt_process_audio_stream_success( mock_convert_to_wav.assert_not_called() mock_genai_client.aio.models.generate_content.assert_called_once() + mock_genai_client.aio.interactions.create.assert_not_called() call_args = mock_genai_client.aio.models.generate_content.call_args assert call_args.kwargs["model"] == TEST_CHAT_MODEL @@ -251,6 +298,192 @@ async def test_stt_process_audio_stream_no_text_response( assert expected_log in caplog.text +@pytest.mark.parametrize( + ("setup_integration", "language", "expected_transcription_config"), + [ + pytest.param( + TEST_INTERACTIONS_MODEL, + "en-US", + {"language_codes": ["en-US"]}, + id="with_language", + ), + pytest.param(TEST_INTERACTIONS_MODEL, "", {}, id="without_language"), + ], + indirect=["setup_integration"], +) +@pytest.mark.usefixtures("setup_integration") +async def test_stt_process_audio_stream_interactions_success( + hass: HomeAssistant, + mock_genai_client: AsyncMock, + language: str, + expected_transcription_config: dict[str, list[str]], +) -> None: + """Test Interactions-API-only models are routed through interactions.create.""" + entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt") + + metadata = stt.SpeechMetadata( + language=language, + format=stt.AudioFormats.OGG, + codec=stt.AudioCodecs.OPUS, + bit_rate=stt.AudioBitRates.BITRATE_16, + sample_rate=stt.AudioSampleRates.SAMPLERATE_16000, + channel=stt.AudioChannels.CHANNEL_MONO, + ) + audio_stream = _async_get_audio_stream(b"test_audio_bytes") + + result = await entity.async_process_audio_stream(metadata, audio_stream) + + assert result.result == stt.SpeechResultState.SUCCESS + assert result.text == "This is a test transcription." + + mock_genai_client.aio.models.generate_content.assert_not_called() + mock_genai_client.aio.interactions.create.assert_called_once() + call_kwargs = mock_genai_client.aio.interactions.create.call_args.kwargs + + assert call_kwargs["model"] == TEST_INTERACTIONS_MODEL + assert "system_instruction" not in call_kwargs + assert call_kwargs["store"] is False + assert call_kwargs["stream"] is False + + [audio_content] = call_kwargs["input"] + assert audio_content["type"] == "audio" + assert audio_content["data"].read() == b"test_audio_bytes" + assert audio_content["mime_type"] == "audio/ogg" + assert "sample_rate" not in audio_content + assert "channels" not in audio_content + + assert ( + call_kwargs["generation_config"]["transcription_config"] + == expected_transcription_config + ) + + +@pytest.mark.parametrize( + ("audio_format", "expected_convert_calls", "expected_data"), + [ + pytest.param( + stt.AudioFormats.WAV, + [call(b"test_audio_bytes", "audio/L16;rate=16000")], + b"converted_wav_bytes", + id="wav", + ), + pytest.param( + stt.AudioFormats.OGG, + [], + b"test_audio_bytes", + id="ogg", + ), + ], +) +@pytest.mark.parametrize( + "setup_integration", + [pytest.param(TEST_INTERACTIONS_MODEL, id="interactions_model")], + indirect=True, +) +@pytest.mark.usefixtures("setup_integration") +async def test_stt_process_audio_stream_interactions_audio_format( + hass: HomeAssistant, + mock_genai_client: AsyncMock, + audio_format: stt.AudioFormats, + expected_convert_calls: list[call], + expected_data: bytes, +) -> None: + """Test Interactions-API audio content reflects WAV conversion like generateContent.""" + entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt") + + metadata = stt.SpeechMetadata( + language="en-US", + format=audio_format, + codec=stt.AudioCodecs.PCM, + bit_rate=stt.AudioBitRates.BITRATE_16, + sample_rate=stt.AudioSampleRates.SAMPLERATE_16000, + channel=stt.AudioChannels.CHANNEL_MONO, + ) + audio_stream = _async_get_audio_stream(b"test_audio_bytes") + + with patch( + "homeassistant.components.google_generative_ai_conversation.stt.convert_to_wav", + return_value=b"converted_wav_bytes", + ) as mock_convert_to_wav: + result = await entity.async_process_audio_stream(metadata, audio_stream) + + assert result.result == stt.SpeechResultState.SUCCESS + assert mock_convert_to_wav.call_args_list == expected_convert_calls + + call_kwargs = mock_genai_client.aio.interactions.create.call_args.kwargs + [audio_content] = call_kwargs["input"] + assert audio_content["mime_type"] == f"audio/{audio_format.value}" + assert audio_content["data"].read() == expected_data + + +@pytest.mark.parametrize( + "setup_integration", + [pytest.param(TEST_INTERACTIONS_MODEL, id="interactions_model")], + indirect=True, +) +@pytest.mark.usefixtures("setup_integration") +async def test_stt_process_audio_stream_interactions_error( + hass: HomeAssistant, + mock_genai_client: AsyncMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test STT logs and returns an error when interactions.create raises.""" + entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt") + mock_genai_client.aio.interactions.create.side_effect = RuntimeError( + "Interactions API unavailable" + ) + + metadata = stt.SpeechMetadata( + language="en-US", + format=stt.AudioFormats.OGG, + codec=stt.AudioCodecs.OPUS, + bit_rate=stt.AudioBitRates.BITRATE_16, + sample_rate=stt.AudioSampleRates.SAMPLERATE_16000, + channel=stt.AudioChannels.CHANNEL_MONO, + ) + audio_stream = _async_get_audio_stream(b"test_audio_bytes") + + result = await entity.async_process_audio_stream(metadata, audio_stream) + + assert result.result == stt.SpeechResultState.ERROR + assert result.text is None + assert "Error during STT" in caplog.text + + +@pytest.mark.parametrize( + "setup_integration", + [pytest.param(TEST_INTERACTIONS_MODEL, id="interactions_model")], + indirect=True, +) +@pytest.mark.usefixtures("setup_integration") +async def test_stt_process_audio_stream_interactions_no_text( + hass: HomeAssistant, + mock_genai_client: AsyncMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test STT logs the interaction status when there is no output text.""" + entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt") + mock_genai_client.aio.interactions.create.return_value = interactions.Interaction( + status="failed", steps=[] + ) + + metadata = stt.SpeechMetadata( + language="en-US", + format=stt.AudioFormats.OGG, + codec=stt.AudioCodecs.OPUS, + bit_rate=stt.AudioBitRates.BITRATE_16, + sample_rate=stt.AudioSampleRates.SAMPLERATE_16000, + channel=stt.AudioChannels.CHANNEL_MONO, + ) + audio_stream = _async_get_audio_stream(b"test_audio_bytes") + + result = await entity.async_process_audio_stream(metadata, audio_stream) + + assert result.result == stt.SpeechResultState.ERROR + assert result.text is None + assert "STT response contained no text (status=failed)" in caplog.text + + @pytest.mark.usefixtures("mock_genai_client") async def test_stt_uses_default_prompt( hass: HomeAssistant, @@ -368,7 +601,6 @@ async def test_stt_uses_default_model( ("gemini-3.1-flash-lite", True), ("gemini-3.8-flash", False), ("gemini-flash-latest", False), - ("gemini-3.5-transcribe", False), ], ) async def test_stt_wire_parameters( @@ -409,3 +641,52 @@ async def test_stt_wire_parameters( } assert "en-US" in body["contents"][0]["parts"][0]["text"] assert body["contents"][0]["parts"][1]["inlineData"]["mime_type"] == "audio/ogg" + + +@pytest.mark.usefixtures("mock_init_component") +async def test_stt_interactions_wire_parameters( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_interactions_transport: Mock, +) -> None: + """Run a loaded STT entity through real SDK Interactions request construction.""" + subentry = mock_config_entry.subentries["ulid-stt"] + hass.config_entries.async_update_subentry( + mock_config_entry, + subentry, + data={**subentry.data, CONF_CHAT_MODEL: "gemini-3.5-transcribe"}, + ) + await hass.async_block_till_done() + entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt") + metadata = stt.SpeechMetadata( + language="en-US", + format=stt.AudioFormats.OGG, + codec=stt.AudioCodecs.OPUS, + bit_rate=stt.AudioBitRates.BITRATE_16, + sample_rate=stt.AudioSampleRates.SAMPLERATE_16000, + channel=stt.AudioChannels.CHANNEL_MONO, + ) + result = await entity.async_process_audio_stream( + metadata, _async_get_audio_stream(b"audio") + ) + assert result.result is stt.SpeechResultState.SUCCESS + assert result.text == "Done" + [request] = mock_genai_interactions_transport.call_args.args + body = json.loads(request.content) + assert body["model"] == "gemini-3.5-transcribe" + assert body["generation_config"] == { + "transcription_config": {"language_codes": ["en-US"]} + } + assert "system_instruction" not in body + assert body["input"] == [ + { + "type": "user_input", + "content": [ + { + "type": "audio", + "mime_type": "audio/ogg", + "data": base64.b64encode(b"audio").decode(), + } + ], + } + ]