From 662def3bbe5732e17e16c68cede4c28003ee04c6 Mon Sep 17 00:00:00 2001 From: Denis Shulyaka Date: Tue, 1 Dec 2026 20:06:45 +0300 Subject: [PATCH] Add OpenAI Ultrafast Mode (#195836) --- .../openai_conversation/config_flow.py | 6 +- .../components/openai_conversation/const.py | 6 ++ .../components/openai_conversation/entity.py | 9 +++ .../openai_conversation/strings.json | 3 +- .../snapshots/test_conversation.ambr | 2 +- .../openai_conversation/test_config_flow.py | 20 +++++-- .../openai_conversation/test_conversation.py | 57 ++++++++++++------- 7 files changed, 74 insertions(+), 29 deletions(-) diff --git a/homeassistant/components/openai_conversation/config_flow.py b/homeassistant/components/openai_conversation/config_flow.py index d2215080ecde..993de2792ea3 100644 --- a/homeassistant/components/openai_conversation/config_flow.py +++ b/homeassistant/components/openai_conversation/config_flow.py @@ -99,6 +99,7 @@ from .const import ( RECOMMENDED_WEB_SEARCH_CONTEXT_SIZE, RECOMMENDED_WEB_SEARCH_INLINE_CITATIONS, RECOMMENDED_WEB_SEARCH_USER_LOCATION, + ULTRAFAST_SERVICE_TIERS_MODELS, UNSUPPORTED_CODE_INTERPRETER_MODELS, UNSUPPORTED_FLEX_SERVICE_TIERS_MODELS, UNSUPPORTED_IMAGE_MODELS, @@ -509,7 +510,7 @@ class OpenAISubentryFlowHandler(ConfigSubentryFlow): options.pop(CONF_REASONING_SUMMARY) service_tiers = self._get_service_tiers(model) - if "flex" in service_tiers or "priority" in service_tiers: + if service_tiers != ["auto", "default"]: step_schema[ probatio.Optional( CONF_SERVICE_TIER, @@ -677,6 +678,9 @@ class OpenAISubentryFlowHandler(ConfigSubentryFlow): if not model.startswith(tuple(UNSUPPORTED_PRIORITY_SERVICE_TIERS_MODELS)): service_tiers.append("priority") + if model.startswith(tuple(ULTRAFAST_SERVICE_TIERS_MODELS)): + service_tiers.append("ultrafast") + return service_tiers async def _get_location_data(self) -> dict[str, str]: diff --git a/homeassistant/components/openai_conversation/const.py b/homeassistant/components/openai_conversation/const.py index fe9b377c6b65..b9c7035deaa3 100644 --- a/homeassistant/components/openai_conversation/const.py +++ b/homeassistant/components/openai_conversation/const.py @@ -162,3 +162,9 @@ UNSUPPORTED_PRIORITY_SERVICE_TIERS_MODELS: list[str] = [ "o3-mini", "codex-mini", ] +ULTRAFAST_SERVICE_TIERS_MODELS: list[str] = [ + "gpt-6-astra", + "gpt-6.1-sol", + "gpt-6.2-astra", + "gpt-6.2-sol", +] diff --git a/homeassistant/components/openai_conversation/entity.py b/homeassistant/components/openai_conversation/entity.py index d41b77346b10..86b589f4b2f3 100644 --- a/homeassistant/components/openai_conversation/entity.py +++ b/homeassistant/components/openai_conversation/entity.py @@ -727,6 +727,15 @@ class OpenAIBaseLLMEntity(Entity): ) model_args["service_tier"] = "default" continue + if ( + model_args["service_tier"] == "ultrafast" + and err.code == "rate_limit_exceeded" + ): + LOGGER.info( + "Ultrafast tier rate limited, retrying with priority tier" + ) + model_args["service_tier"] = "priority" + continue # pylint: disable-next=home-assistant-log-and-raise LOGGER.error("Rate limited by OpenAI: %s", err) raise HomeAssistantError("Rate limited or insufficient funds") from err diff --git a/homeassistant/components/openai_conversation/strings.json b/homeassistant/components/openai_conversation/strings.json index ce484791409e..c1c9143bd86f 100644 --- a/homeassistant/components/openai_conversation/strings.json +++ b/homeassistant/components/openai_conversation/strings.json @@ -263,7 +263,8 @@ "auto": "[%key:common::state::auto%]", "default": "Standard", "flex": "Flex", - "priority": "Priority" + "priority": "Priority", + "ultrafast": "Ultrafast" } }, "verbosity": { diff --git a/tests/components/openai_conversation/snapshots/test_conversation.ambr b/tests/components/openai_conversation/snapshots/test_conversation.ambr index defc45cae525..e7d31d979142 100644 --- a/tests/components/openai_conversation/snapshots/test_conversation.ambr +++ b/tests/components/openai_conversation/snapshots/test_conversation.ambr @@ -617,7 +617,7 @@ 'reasoning': dict({ 'effort': 'high', }), - 'service_tier': 'auto', + 'service_tier': 'ultrafast', 'store': False, 'stream': True, 'text': dict({ diff --git a/tests/components/openai_conversation/test_config_flow.py b/tests/components/openai_conversation/test_config_flow.py index ff1968d8dfb9..9e391161db86 100644 --- a/tests/components/openai_conversation/test_config_flow.py +++ b/tests/components/openai_conversation/test_config_flow.py @@ -54,6 +54,8 @@ from homeassistant.const import CONF_API_KEY, CONF_LLM_HASS_API, CONF_PROMPT from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType +ALL_SERVICE_TIERS = ["auto", "flex", "default", "priority", "ultrafast"] + async def test_form(hass: HomeAssistant) -> None: """Test we get the form.""" @@ -512,6 +514,13 @@ async def test_subentry_reasoning_summary_default_sanitized_on_model_switch( @pytest.mark.parametrize( ("model", "service_tier_options"), [ + pytest.param("gpt-6.2-astra", ALL_SERVICE_TIERS, id="gpt-6.2-astra"), + pytest.param("gpt-6.2-sol", ALL_SERVICE_TIERS, id="gpt-6.2-sol"), + pytest.param("gpt-6-astra", ALL_SERVICE_TIERS, id="gpt-6-astra"), + pytest.param("gpt-6.1-sol", ALL_SERVICE_TIERS, id="gpt-6.1-sol"), + pytest.param( + "gpt-6.1-terra", ["auto", "flex", "default", "priority"], id="terra" + ), ("gpt-5.6", ["auto", "flex", "default", "priority"]), ("gpt-5.5", ["auto", "flex", "default", "priority"]), ("gpt-5.4", ["auto", "flex", "default", "priority"]), @@ -538,12 +547,12 @@ async def test_subentry_reasoning_summary_default_sanitized_on_model_switch( ("o3-mini", []), ], ) +@pytest.mark.usefixtures("mock_init_component") async def test_subentry_service_tier_list( hass: HomeAssistant, - mock_config_entry, - mock_init_component, - model, - service_tier_options, + mock_config_entry: MockConfigEntry, + model: str, + service_tier_options: list[str], ) -> None: """Test the list of service tier options.""" subentry = next(iter(mock_config_entry.subentries.values())) @@ -1148,6 +1157,7 @@ async def test_form_invalid_auth( CONF_REASONING_SUMMARY: "detailed", CONF_PRO_MODE: True, CONF_VERBOSITY: "low", + CONF_SERVICE_TIER: "ultrafast", }, ), { @@ -1162,7 +1172,7 @@ async def test_form_invalid_auth( CONF_REASONING_SUMMARY: "detailed", CONF_PRO_MODE: True, CONF_VERBOSITY: "low", - CONF_SERVICE_TIER: "auto", + CONF_SERVICE_TIER: "ultrafast", CONF_WEB_SEARCH: False, CONF_WEB_SEARCH_CONTEXT_SIZE: "medium", CONF_WEB_SEARCH_USER_LOCATION: False, diff --git a/tests/components/openai_conversation/test_conversation.py b/tests/components/openai_conversation/test_conversation.py index 5d3eaa67618a..6f54fadcb294 100644 --- a/tests/components/openai_conversation/test_conversation.py +++ b/tests/components/openai_conversation/test_conversation.py @@ -890,32 +890,43 @@ async def test_code_interpreter( assert mock_create_stream.mock_calls[1][2]["input"][2]["status"] == status -async def test_flex_tier_retry( +@pytest.mark.parametrize( + ("mock_conversation_subentry_data", "message", "body", "fallback_tier"), + [ + pytest.param( + {CONF_SERVICE_TIER: "flex"}, + "Resource Unavailable", + None, + "default", + id="flex", + ), + pytest.param( + {CONF_CHAT_MODEL: "gpt-6-astra", CONF_SERVICE_TIER: "ultrafast"}, + "Rate limit reached for tokens per minute", + {"type": "tokens", "code": "rate_limit_exceeded"}, + "priority", + id="ultrafast", + ), + ], +) +@pytest.mark.usefixtures("mock_init_component") +async def test_service_tier_retry( hass: HomeAssistant, - mock_config_entry: MockConfigEntry, - mock_init_component, - mock_create_stream, + mock_create_stream: AsyncMock, + mock_conversation_subentry_data: dict[str, str], + message: str, + body: dict[str, str] | None, + fallback_tier: str, ) -> None: - """Test retry with default tier if flex tier unavailable.""" - subentry = next(iter(mock_config_entry.subentries.values())) - hass.config_entries.async_update_subentry( - mock_config_entry, - subentry, - data={ - **subentry.data, - CONF_SERVICE_TIER: "flex", - }, - ) - await hass.config_entries.async_reload(mock_config_entry.entry_id) - + """Test retrying on the fallback tier when the configured tier is rate limited.""" mock_create_stream.return_value = [ RateLimitError( response=httpx2.Response( status_code=429, request=httpx2.Request("POST", "https://api.openai.com/v1/responses"), ), - body=None, - message="Resource Unavailable", + body=body, + message=message, ), create_message_item(id="msg_A", text="How can I assist?", output_index=0), ] @@ -928,13 +939,16 @@ async def test_flex_tier_retry( agent_id="conversation.openai_conversation", ) - assert mock_create_stream.call_count == 2 assert result.response.response_type is intent.IntentResponseType.ACTION_DONE assert result.response.speech["plain"]["speech"] == "How can I assist?", ( result.response.speech ) - assert mock_create_stream.mock_calls[0][2]["service_tier"] == "flex" - assert mock_create_stream.mock_calls[1][2]["service_tier"] == "default" + assert [ + call.kwargs["service_tier"] for call in mock_create_stream.await_args_list + ] == [ + mock_conversation_subentry_data[CONF_SERVICE_TIER], + fallback_tier, + ] @pytest.mark.parametrize( @@ -963,6 +977,7 @@ async def test_flex_tier_retry( CONF_CHAT_MODEL: "gpt-6-astra", CONF_REASONING_EFFORT: "high", CONF_REASONING_SUMMARY: "off", + CONF_SERVICE_TIER: "ultrafast", CONF_VERBOSITY: "high", }, {CONF_CHAT_MODEL: "gpt-6-luna"},