mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 12:21:04 -04:00
Use deprecation information for Anthropic models from the API (#186887)
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
"""The Anthropic integration."""
|
||||
|
||||
from anthropic.resources.messages.messages import DEPRECATED_MODELS
|
||||
from functools import partial
|
||||
|
||||
from homeassistant.config_entries import ConfigSubentry
|
||||
from homeassistant.const import CONF_API_KEY, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers import (
|
||||
config_validation as cv,
|
||||
device_registry as dr,
|
||||
@@ -36,9 +36,24 @@ async def async_setup_entry(hass: HomeAssistant, entry: AnthropicConfigEntry) ->
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
entry.async_on_unload(entry.add_update_listener(async_update_options))
|
||||
entry.async_on_unload(
|
||||
coordinator.async_add_listener(
|
||||
partial(_async_check_model_lifecycle, hass, entry)
|
||||
)
|
||||
)
|
||||
_async_check_model_lifecycle(hass, entry)
|
||||
|
||||
|
||||
@callback
|
||||
def _async_check_model_lifecycle(
|
||||
hass: HomeAssistant, entry: AnthropicConfigEntry
|
||||
) -> None:
|
||||
"""Create a repair for models deprecated or retired by the API."""
|
||||
for subentry in entry.subentries.values():
|
||||
if (model := subentry.data.get(CONF_CHAT_MODEL)) and model in DEPRECATED_MODELS:
|
||||
if not (model := subentry.data.get(CONF_CHAT_MODEL)):
|
||||
continue
|
||||
model_info, found = entry.runtime_data.get_model_info(model)
|
||||
if found and model_info.lifecycle in ("deprecated", "retired"):
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
|
||||
@@ -444,6 +444,9 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow):
|
||||
err.message if isinstance(err, anthropic.APIError) else str(err)
|
||||
)
|
||||
|
||||
if not errors and self.model_info.lifecycle == "retired":
|
||||
errors[CONF_CHAT_MODEL] = "model_retired"
|
||||
|
||||
if not errors:
|
||||
return await self.async_step_model()
|
||||
|
||||
@@ -622,6 +625,8 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow):
|
||||
value=model_alias(model_info.id),
|
||||
)
|
||||
for model_info in coordinator.data or []
|
||||
if coordinator.get_model_info(model_alias(model_info.id))[0].lifecycle
|
||||
!= "retired"
|
||||
]
|
||||
|
||||
async def _get_location_data(self) -> dict[str, str]:
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
import datetime as dt
|
||||
from functools import partial
|
||||
from typing import override
|
||||
import re
|
||||
from typing import Literal, override
|
||||
|
||||
import anthropic
|
||||
from anthropic.resources.messages.messages import DEPRECATED_MODELS
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
@@ -12,11 +14,29 @@ from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.httpx_client import get_async_client
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .const import DOMAIN, LOGGER
|
||||
|
||||
UPDATE_INTERVAL_CONNECTED = dt.timedelta(hours=12)
|
||||
UPDATE_INTERVAL_DISCONNECTED = dt.timedelta(minutes=1)
|
||||
SDK_DATE_PATTERN = re.compile(
|
||||
r"([A-Za-z]+) (\d{1,2})(?:st|nd|rd|th)?, (\d{4})" # codespell:ignore nd
|
||||
)
|
||||
SDK_DATE_MONTHS = (
|
||||
"january",
|
||||
"february",
|
||||
"march",
|
||||
"april",
|
||||
"may",
|
||||
"june",
|
||||
"july",
|
||||
"august",
|
||||
"september",
|
||||
"october",
|
||||
"november",
|
||||
"december",
|
||||
)
|
||||
|
||||
type AnthropicConfigEntry = ConfigEntry[AnthropicCoordinator]
|
||||
|
||||
@@ -43,6 +63,25 @@ def model_alias(model_id: str) -> str:
|
||||
return model_id
|
||||
|
||||
|
||||
def _parse_sdk_retirement_date(value: str) -> dt.datetime | None:
|
||||
"""Parse SDK retirement dates without relying on the process locale."""
|
||||
try:
|
||||
retires_at = dt_util.parse_datetime(value)
|
||||
except ValueError:
|
||||
retires_at = None
|
||||
if retires_at is not None:
|
||||
if retires_at.tzinfo is None:
|
||||
return retires_at.replace(tzinfo=dt.UTC)
|
||||
return retires_at.astimezone(dt.UTC)
|
||||
if not (match := SDK_DATE_PATTERN.fullmatch(value)):
|
||||
return None
|
||||
try:
|
||||
month = SDK_DATE_MONTHS.index(match[1].lower()) + 1
|
||||
return dt.datetime(int(match[3]), month, int(match[2]), tzinfo=dt.UTC)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class AnthropicCoordinator(DataUpdateCoordinator[list[anthropic.types.ModelInfo]]):
|
||||
"""Coordinator using different intervals after success and failure."""
|
||||
|
||||
@@ -60,6 +99,7 @@ class AnthropicCoordinator(DataUpdateCoordinator[list[anthropic.types.ModelInfo]
|
||||
update_method=self.async_update_data,
|
||||
always_update=False,
|
||||
)
|
||||
self._last_model_update: dt.datetime | None = None
|
||||
|
||||
@property
|
||||
def client(self) -> anthropic.AsyncAnthropic:
|
||||
@@ -73,19 +113,55 @@ class AnthropicCoordinator(DataUpdateCoordinator[list[anthropic.types.ModelInfo]
|
||||
self.hass, self.config_entry.data[CONF_API_KEY]
|
||||
)
|
||||
|
||||
@callback
|
||||
@override
|
||||
def async_set_updated_data(self, data: list[anthropic.types.ModelInfo]) -> None:
|
||||
"""Manually update data, notify listeners and update refresh interval."""
|
||||
self.update_interval = UPDATE_INTERVAL_CONNECTED
|
||||
super().async_set_updated_data(data)
|
||||
|
||||
async def async_update_data(self) -> list[anthropic.types.ModelInfo]:
|
||||
"""Fetch data from the API."""
|
||||
"""Fetch model list from the API.
|
||||
|
||||
Regular updates fetch active models.
|
||||
Deprecated and retired models are only fetched on first refresh,
|
||||
if the active models have changed, if a deprecation date has passed
|
||||
since the previous update, or if a deprecated model's retirement date is past.
|
||||
"""
|
||||
self.update_interval = UPDATE_INTERVAL_DISCONNECTED
|
||||
active_models = await self._async_get_models(["active"])
|
||||
models = self.data or []
|
||||
cached_active_models = [
|
||||
model for model in models if model.lifecycle == "active"
|
||||
]
|
||||
last_update = self._last_model_update
|
||||
now = dt_util.utcnow()
|
||||
if (
|
||||
last_update is None
|
||||
or active_models != cached_active_models
|
||||
or any(
|
||||
model.retires_at is not None and model.retires_at <= now
|
||||
for model in models
|
||||
if model.lifecycle == "deprecated"
|
||||
)
|
||||
or any(
|
||||
last_update < model.deprecated_at <= now
|
||||
for model in models
|
||||
if model.deprecated_at is not None
|
||||
)
|
||||
):
|
||||
inactive_models = await self._async_get_models(["deprecated", "retired"])
|
||||
else:
|
||||
inactive_models = [model for model in models if model.lifecycle != "active"]
|
||||
# A model can change lifecycle between the two requests.
|
||||
inactive_ids = {model.id for model in inactive_models}
|
||||
models = [
|
||||
model for model in active_models if model.id not in inactive_ids
|
||||
] + inactive_models
|
||||
self._last_model_update = now
|
||||
self.update_interval = UPDATE_INTERVAL_CONNECTED
|
||||
return models
|
||||
|
||||
async def _async_get_models(
|
||||
self, lifecycle: list[Literal["active", "deprecated", "retired"]]
|
||||
) -> list[anthropic.types.ModelInfo]:
|
||||
"""Fetch all pages for the requested lifecycle stages."""
|
||||
try:
|
||||
self.update_interval = UPDATE_INTERVAL_DISCONNECTED
|
||||
result = await self.client.models.list(timeout=10.0)
|
||||
self.update_interval = UPDATE_INTERVAL_CONNECTED
|
||||
result = await self.client.models.list(lifecycle=lifecycle, timeout=10.0)
|
||||
return [model async for model in result]
|
||||
except anthropic.APITimeoutError as err:
|
||||
raise TimeoutError(err.message or str(err)) from err
|
||||
except anthropic.AuthenticationError as err:
|
||||
@@ -100,34 +176,57 @@ class AnthropicCoordinator(DataUpdateCoordinator[list[anthropic.types.ModelInfo]
|
||||
translation_key="api_error",
|
||||
translation_placeholders={"message": err.message},
|
||||
) from err
|
||||
return result.data
|
||||
|
||||
@callback
|
||||
def mark_connection_healthy(self) -> None:
|
||||
"""Restore connection health without changing catalogue polling."""
|
||||
if not self.last_update_success:
|
||||
self.last_update_success = True
|
||||
self.async_update_listeners()
|
||||
|
||||
def mark_connection_error(self) -> None:
|
||||
"""Mark the connection as having an error and reschedule background check."""
|
||||
reschedule_refresh = self.update_interval != UPDATE_INTERVAL_DISCONNECTED
|
||||
self.update_interval = UPDATE_INTERVAL_DISCONNECTED
|
||||
if self.last_update_success:
|
||||
self.last_update_success = False
|
||||
self.async_update_listeners()
|
||||
if self._listeners and not self.hass.is_stopping:
|
||||
self._schedule_refresh()
|
||||
if reschedule_refresh and self._listeners and not self.hass.is_stopping:
|
||||
self._schedule_refresh()
|
||||
|
||||
@callback
|
||||
def get_model_info(self, model_id: str) -> tuple[anthropic.types.ModelInfo, bool]:
|
||||
"""Get model info for a given model ID."""
|
||||
# First try: exact name match
|
||||
for model in self.data or []:
|
||||
if model.id == model_id:
|
||||
return model, True
|
||||
# Second try: match by alias
|
||||
alias = model_alias(model_id)
|
||||
for model in self.data or []:
|
||||
if model_alias(model.id) == alias:
|
||||
return model, True
|
||||
# Model not found, return safe defaults
|
||||
return anthropic.types.ModelInfo(
|
||||
type="model",
|
||||
id=model_id,
|
||||
lifecycle="retired",
|
||||
created_at=dt.datetime(1970, 1, 1, tzinfo=dt.UTC),
|
||||
display_name=alias,
|
||||
), False
|
||||
model = next((model for model in self.data or [] if model.id == model_id), None)
|
||||
if model is None:
|
||||
model = next(
|
||||
(model for model in self.data or [] if model_alias(model.id) == alias),
|
||||
None,
|
||||
)
|
||||
if model is None:
|
||||
return anthropic.types.ModelInfo(
|
||||
type="model",
|
||||
id=model_id,
|
||||
lifecycle="retired",
|
||||
created_at=dt.datetime(1970, 1, 1, tzinfo=dt.UTC),
|
||||
display_name=alias,
|
||||
), False
|
||||
if model.lifecycle != "active":
|
||||
return model, True
|
||||
|
||||
# The Models API can lag behind published SDK deprecations.
|
||||
retirement_date = DEPRECATED_MODELS.get(
|
||||
model_id, DEPRECATED_MODELS.get(model.id)
|
||||
)
|
||||
if retirement_date is None:
|
||||
return model, True
|
||||
retires_at = _parse_sdk_retirement_date(retirement_date)
|
||||
return model.model_copy(
|
||||
update={
|
||||
"lifecycle": "retired"
|
||||
if retires_at is not None and retires_at <= dt_util.utcnow()
|
||||
else "deprecated",
|
||||
"retires_at": retires_at or model.retires_at,
|
||||
}
|
||||
), True
|
||||
|
||||
@@ -1182,7 +1182,7 @@ class AnthropicBaseLLMEntity(CoordinatorEntity[AnthropicCoordinator]):
|
||||
) from err
|
||||
except anthropic.AnthropicError as err:
|
||||
# Non-connection error, mark connection as healthy
|
||||
coordinator.async_set_updated_data(coordinator.data)
|
||||
coordinator.mark_connection_healthy()
|
||||
# pylint: disable-next=home-assistant-log-and-raise
|
||||
LOGGER.error("Error while talking to Anthropic: %s", err)
|
||||
raise HomeAssistantError(
|
||||
@@ -1201,7 +1201,7 @@ class AnthropicBaseLLMEntity(CoordinatorEntity[AnthropicCoordinator]):
|
||||
"model_context_window_exceeded",
|
||||
"stop_sequence",
|
||||
) or (stop_reason == "pause_turn" and iteration == max_iterations - 1):
|
||||
coordinator.async_set_updated_data(coordinator.data)
|
||||
coordinator.mark_connection_healthy()
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key={
|
||||
@@ -1214,7 +1214,7 @@ class AnthropicBaseLLMEntity(CoordinatorEntity[AnthropicCoordinator]):
|
||||
)
|
||||
|
||||
if delta_stream.tool_args_error is not None:
|
||||
coordinator.async_set_updated_data(coordinator.data)
|
||||
coordinator.mark_connection_healthy()
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="tool_args_parse_error",
|
||||
@@ -1224,7 +1224,7 @@ class AnthropicBaseLLMEntity(CoordinatorEntity[AnthropicCoordinator]):
|
||||
continue
|
||||
|
||||
if not chat_log.unresponded_tool_results:
|
||||
coordinator.async_set_updated_data(coordinator.data)
|
||||
coordinator.mark_connection_healthy()
|
||||
break
|
||||
|
||||
|
||||
|
||||
@@ -46,63 +46,69 @@ class ModelDeprecatedRepairFlow(RepairsFlow):
|
||||
) -> RepairsFlowResult:
|
||||
"""Handle the steps of a fix flow."""
|
||||
if user_input and user_input.get(CONF_CHAT_MODEL):
|
||||
errors = {}
|
||||
description_placeholders = (
|
||||
self.cur_step["description_placeholders"] if self.cur_step else None
|
||||
) or {}
|
||||
try:
|
||||
await self._async_update_current_subentry(user_input)
|
||||
if not await self._async_update_current_subentry(user_input):
|
||||
errors[CONF_CHAT_MODEL] = "model_not_active"
|
||||
except anthropic.AnthropicError as err:
|
||||
if self.cur_step is None:
|
||||
raise
|
||||
errors[CONF_CHAT_MODEL] = "api_error"
|
||||
description_placeholders = {
|
||||
**description_placeholders,
|
||||
"message": err.message
|
||||
if isinstance(err, anthropic.APIError)
|
||||
else str(err),
|
||||
}
|
||||
if errors:
|
||||
assert self.cur_step is not None
|
||||
return self.async_show_form(
|
||||
step_id="init",
|
||||
step_id=self.cur_step["step_id"],
|
||||
data_schema=self.add_suggested_values_to_schema(
|
||||
cast(probatio.Schema, self.cur_step["data_schema"]), user_input
|
||||
),
|
||||
errors={CONF_CHAT_MODEL: "api_error"},
|
||||
description_placeholders={
|
||||
**(self.cur_step["description_placeholders"] or {}),
|
||||
"message": err.message
|
||||
if isinstance(err, anthropic.APIError)
|
||||
else str(err),
|
||||
},
|
||||
errors=errors,
|
||||
description_placeholders=description_placeholders,
|
||||
)
|
||||
|
||||
target = await self._async_next_target()
|
||||
if target is None:
|
||||
return self.async_create_entry(data={})
|
||||
|
||||
entry, subentry, model = target
|
||||
entry, subentry, model_info = target
|
||||
if self._model_list_cache is None:
|
||||
self._model_list_cache = {}
|
||||
if entry.entry_id not in self._model_list_cache:
|
||||
client = entry.runtime_data.client
|
||||
try:
|
||||
models = (await client.models.list(timeout=10.0)).data
|
||||
result = await client.models.list(timeout=10.0)
|
||||
models = [model async for model in result]
|
||||
except anthropic.AnthropicError:
|
||||
models = []
|
||||
self._model_list_cache[entry.entry_id] = models
|
||||
active_models = [
|
||||
model
|
||||
for model in self._model_list_cache[entry.entry_id]
|
||||
if model.lifecycle == "active"
|
||||
and model_alias(model.id) not in DEPRECATED_MODELS
|
||||
and model.id not in DEPRECATED_MODELS
|
||||
]
|
||||
model_list = [
|
||||
SelectOptionDict(
|
||||
label=model_info.display_name,
|
||||
value=model_alias(model_info.id),
|
||||
label=model.display_name,
|
||||
value=model_alias(model.id),
|
||||
)
|
||||
for model_info in self._model_list_cache[entry.entry_id]
|
||||
if model_alias(model_info.id) not in DEPRECATED_MODELS
|
||||
for model in active_models
|
||||
]
|
||||
|
||||
family = (
|
||||
model.removeprefix("claude-")
|
||||
.removesuffix("-preview")
|
||||
.translate(str.maketrans("", "", "0123456789-."))
|
||||
or "haiku"
|
||||
)
|
||||
|
||||
suggested_model = next(
|
||||
(
|
||||
model_option["value"]
|
||||
for model_option in sorted(
|
||||
(m for m in model_list if f"claude-{family}" in m["value"]),
|
||||
key=lambda x: x["value"],
|
||||
reverse=True,
|
||||
)
|
||||
model_alias(model.id)
|
||||
for model in active_models
|
||||
if model_info.line is not None and model.line == model_info.line
|
||||
),
|
||||
probatio.UNDEFINED,
|
||||
)
|
||||
@@ -119,17 +125,28 @@ class ModelDeprecatedRepairFlow(RepairsFlow):
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="init",
|
||||
step_id="retired" if model_info.lifecycle == "retired" else "init",
|
||||
data_schema=schema,
|
||||
description_placeholders={
|
||||
"entry_name": entry.title,
|
||||
"model": model,
|
||||
"model": model_info.id,
|
||||
"subentry_name": subentry.title,
|
||||
"subentry_type": self._format_subentry_type(subentry.subentry_type),
|
||||
"retirement_date": DEPRECATED_MODELS[model],
|
||||
"deprecation_date": model_info.deprecated_at.date().isoformat()
|
||||
if model_info.deprecated_at
|
||||
else "—",
|
||||
"retirement_date": model_info.retires_at.date().isoformat()
|
||||
if model_info.retires_at
|
||||
else "—",
|
||||
},
|
||||
)
|
||||
|
||||
async def async_step_retired(
|
||||
self, user_input: dict[str, str] | None
|
||||
) -> RepairsFlowResult:
|
||||
"""Replace a retired model."""
|
||||
return await self.async_step_init(user_input)
|
||||
|
||||
def _iter_deprecated_subentries(self) -> Iterator[tuple[str, str]]:
|
||||
"""Yield entry/subentry pairs that use deprecated models."""
|
||||
for entry in self.hass.config_entries.async_entries(DOMAIN):
|
||||
@@ -137,12 +154,15 @@ class ModelDeprecatedRepairFlow(RepairsFlow):
|
||||
continue
|
||||
for subentry in entry.subentries.values():
|
||||
model = subentry.data.get(CONF_CHAT_MODEL)
|
||||
if model and model in DEPRECATED_MODELS:
|
||||
if not model:
|
||||
continue
|
||||
model_info, found = entry.runtime_data.get_model_info(model)
|
||||
if found and model_info.lifecycle in ("deprecated", "retired"):
|
||||
yield entry.entry_id, subentry.subentry_id
|
||||
|
||||
async def _async_next_target(
|
||||
self,
|
||||
) -> tuple[AnthropicConfigEntry, ConfigSubentry, str] | None:
|
||||
) -> tuple[AnthropicConfigEntry, ConfigSubentry, anthropic.types.ModelInfo] | None:
|
||||
"""Return the next deprecated subentry target."""
|
||||
if self._subentry_iter is None:
|
||||
self._subentry_iter = self._iter_deprecated_subentries()
|
||||
@@ -164,15 +184,18 @@ class ModelDeprecatedRepairFlow(RepairsFlow):
|
||||
continue
|
||||
|
||||
model = subentry.data.get(CONF_CHAT_MODEL)
|
||||
if not model or model not in DEPRECATED_MODELS:
|
||||
if not model:
|
||||
continue
|
||||
model_info, found = entry.runtime_data.get_model_info(model)
|
||||
if not found or model_info.lifecycle not in ("deprecated", "retired"):
|
||||
continue
|
||||
|
||||
self._current_entry_id = entry_id
|
||||
self._current_subentry_id = subentry_id
|
||||
return entry, subentry, model
|
||||
return entry, subentry, model_info
|
||||
|
||||
async def _async_update_current_subentry(self, user_input: dict[str, str]) -> None:
|
||||
"""Update the currently selected subentry."""
|
||||
async def _async_update_current_subentry(self, user_input: dict[str, str]) -> bool:
|
||||
"""Update the subentry if the replacement model is active."""
|
||||
if (
|
||||
self._current_entry_id is None
|
||||
or self._current_subentry_id is None
|
||||
@@ -205,6 +228,13 @@ class ModelDeprecatedRepairFlow(RepairsFlow):
|
||||
model_info = await entry.runtime_data.client.models.retrieve(
|
||||
user_input[CONF_CHAT_MODEL], timeout=10.0
|
||||
)
|
||||
if (
|
||||
model_info.lifecycle != "active"
|
||||
or user_input[CONF_CHAT_MODEL] in DEPRECATED_MODELS
|
||||
or model_info.id in DEPRECATED_MODELS
|
||||
or model_alias(model_info.id) in DEPRECATED_MODELS
|
||||
):
|
||||
return False
|
||||
reconcile_model_options(updated_data, model_info)
|
||||
|
||||
self.hass.config_entries.async_update_subentry(
|
||||
@@ -212,6 +242,7 @@ class ModelDeprecatedRepairFlow(RepairsFlow):
|
||||
subentry,
|
||||
data=updated_data,
|
||||
)
|
||||
return True
|
||||
|
||||
def _format_subentry_type(self, subentry_type: str) -> str:
|
||||
"""Return a user-friendly subentry type label."""
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
"error": {
|
||||
"api_error": "[%key:component::anthropic::config_subentries::conversation::error::api_error%]",
|
||||
"model_not_found": "[%key:component::anthropic::config_subentries::conversation::error::model_not_found%]",
|
||||
"model_retired": "[%key:component::anthropic::config_subentries::conversation::error::model_retired%]",
|
||||
"thinking_budget_too_large": "[%key:component::anthropic::config_subentries::conversation::error::thinking_budget_too_large%]"
|
||||
},
|
||||
"initiate_flow": {
|
||||
@@ -114,6 +115,7 @@
|
||||
"error": {
|
||||
"api_error": "Unable to get model info: {message}",
|
||||
"model_not_found": "Model not found",
|
||||
"model_retired": "This model is retired. Select another model.",
|
||||
"thinking_budget_too_large": "Thinking budget must be less than the Maximum tokens."
|
||||
},
|
||||
"initiate_flow": {
|
||||
@@ -237,7 +239,8 @@
|
||||
"model_deprecated": {
|
||||
"fix_flow": {
|
||||
"error": {
|
||||
"api_error": "[%key:component::anthropic::config_subentries::conversation::error::api_error%]"
|
||||
"api_error": "[%key:component::anthropic::config_subentries::conversation::error::api_error%]",
|
||||
"model_not_active": "Select an active model."
|
||||
},
|
||||
"step": {
|
||||
"init": {
|
||||
@@ -247,8 +250,18 @@
|
||||
"data_description": {
|
||||
"chat_model": "Select the new model to use."
|
||||
},
|
||||
"description": "You are updating {subentry_name} ({subentry_type}) in {entry_name}. The current model {model} is deprecated and will reach end-of-life on {retirement_date}. Select a supported model to continue.",
|
||||
"description": "You are updating {subentry_name} ({subentry_type}) in {entry_name}. The current model {model} is deprecated. Select an active model to continue.\n\nDeprecation date: {deprecation_date}\nRetirement date: {retirement_date}",
|
||||
"title": "Update model"
|
||||
},
|
||||
"retired": {
|
||||
"data": {
|
||||
"chat_model": "[%key:common::generic::model%]"
|
||||
},
|
||||
"data_description": {
|
||||
"chat_model": "[%key:component::anthropic::issues::model_deprecated::fix_flow::step::init::data_description::chat_model%]"
|
||||
},
|
||||
"description": "You are updating {subentry_name} ({subentry_type}) in {entry_name}. The current model {model} is retired and can no longer be used. Select an active model to continue.\n\nDeprecation date: {deprecation_date}\nRetirement date: {retirement_date}",
|
||||
"title": "[%key:component::anthropic::issues::model_deprecated::fix_flow::step::init::title%]"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from collections.abc import AsyncGenerator, Generator, Iterable
|
||||
import datetime as dt
|
||||
from typing import Unpack
|
||||
from typing import Literal, Unpack
|
||||
from unittest.mock import DEFAULT, AsyncMock, MagicMock, patch
|
||||
|
||||
from anthropic import AsyncStream
|
||||
@@ -11,6 +11,7 @@ from anthropic.types import (
|
||||
Container,
|
||||
Message,
|
||||
MessageDeltaUsage,
|
||||
ModelInfo,
|
||||
RawContentBlockStartEvent,
|
||||
RawMessageDeltaEvent,
|
||||
RawMessageStartEvent,
|
||||
@@ -83,18 +84,38 @@ def mock_config_entry_with_assist(
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def mock_init_component(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry
|
||||
) -> AsyncGenerator[None]:
|
||||
"""Initialize integration."""
|
||||
def mock_model_list() -> Generator[AsyncMock]:
|
||||
"""Mock the catalogue with the API's lifecycle filtering."""
|
||||
|
||||
def models_list(
|
||||
*,
|
||||
lifecycle: list[Literal["active", "deprecated", "retired"]] | None = None,
|
||||
timeout: float = 10.0,
|
||||
) -> AsyncPage[ModelInfo]:
|
||||
"""Return models matching the requested lifecycle stages."""
|
||||
lifecycles = lifecycle if lifecycle is not None else ["active", "deprecated"]
|
||||
return AsyncPage(
|
||||
data=[model for model in model_list if model.lifecycle in lifecycles],
|
||||
has_more=False,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"anthropic.resources.models.AsyncModels.list",
|
||||
new_callable=AsyncMock,
|
||||
return_value=AsyncPage(data=model_list),
|
||||
):
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
yield
|
||||
side_effect=models_list,
|
||||
) as mock_list:
|
||||
yield mock_list
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def mock_init_component(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
) -> None:
|
||||
"""Initialize integration."""
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@@ -864,7 +864,15 @@ async def test_model_list(
|
||||
mock_config_entry: MockConfigEntry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test fetching and processing the list of models."""
|
||||
"""Test the model selector excludes retired models from the catalogue."""
|
||||
mock_config_entry.runtime_data.async_set_updated_data(
|
||||
[
|
||||
*model_list,
|
||||
model_list[0].model_copy(
|
||||
update={"id": "retired-model", "lifecycle": "retired"}
|
||||
),
|
||||
]
|
||||
)
|
||||
subentry = next(iter(mock_config_entry.subentries.values()))
|
||||
options_flow = await mock_config_entry.start_subentry_reconfigure_flow(
|
||||
hass, subentry.subentry_id
|
||||
@@ -883,6 +891,119 @@ async def test_model_list(
|
||||
assert options["data_schema"].schema["chat_model"].config["options"] == snapshot
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
@pytest.mark.freeze_time("2026-10-16T12:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
("sdk_dates", "expected_values"),
|
||||
[
|
||||
pytest.param(
|
||||
{"sdk-model-20260101": "October 15th, 2026"},
|
||||
["active-model"],
|
||||
id="sdk_retired",
|
||||
),
|
||||
pytest.param(
|
||||
{"sdk-model-20260101": "October 17th, 2026"},
|
||||
["active-model", "sdk-model"],
|
||||
id="sdk_deprecated",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"sdk-model": "October 15th, 2026",
|
||||
"sdk-model-20260101": "October 17th, 2026",
|
||||
},
|
||||
["active-model"],
|
||||
id="submitted_alias_retired",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"sdk-model": "October 17th, 2026",
|
||||
"sdk-model-20260101": "October 15th, 2026",
|
||||
},
|
||||
["active-model", "sdk-model"],
|
||||
id="submitted_alias_deprecated",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_model_list_sdk_lifecycle(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
sdk_dates: dict[str, str],
|
||||
expected_values: list[str],
|
||||
) -> None:
|
||||
"""Filter models using the lifecycle of the alias submitted by the selector."""
|
||||
mock_config_entry.runtime_data.async_set_updated_data(
|
||||
[
|
||||
model_list[0].model_copy(update={"id": "active-model"}),
|
||||
model_list[0].model_copy(update={"id": "sdk-model-20260101"}),
|
||||
]
|
||||
)
|
||||
subentry = next(iter(mock_config_entry.subentries.values()))
|
||||
options_flow = await mock_config_entry.start_subentry_reconfigure_flow(
|
||||
hass, subentry.subentry_id
|
||||
)
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS",
|
||||
sdk_dates,
|
||||
clear=True,
|
||||
):
|
||||
options = await hass.config_entries.subentries.async_configure(
|
||||
options_flow["flow_id"],
|
||||
{CONF_RECOMMENDED: False},
|
||||
)
|
||||
|
||||
assert options["type"] is FlowResultType.FORM
|
||||
assert options["step_id"] == "additional"
|
||||
assert [
|
||||
option["value"]
|
||||
for option in options["data_schema"].schema[CONF_CHAT_MODEL].config["options"]
|
||||
] == expected_values
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
@pytest.mark.parametrize("cached_model_count", [0, 1], ids=["retrieved", "cached"])
|
||||
async def test_retired_model(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
cached_model_count: int,
|
||||
) -> None:
|
||||
"""Reject retired models entered as a custom model ID."""
|
||||
retired_model = model_list[0].model_copy(
|
||||
update={"id": "retired-model", "lifecycle": "retired"}
|
||||
)
|
||||
mock_config_entry.runtime_data.async_set_updated_data(
|
||||
[retired_model][:cached_model_count]
|
||||
)
|
||||
result = await hass.config_entries.subentries.async_init(
|
||||
(mock_config_entry.entry_id, "conversation"),
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
)
|
||||
result = await hass.config_entries.subentries.async_configure(
|
||||
result["flow_id"], {CONF_NAME: "Claude", CONF_RECOMMENDED: False}
|
||||
)
|
||||
with patch(
|
||||
"anthropic.resources.models.AsyncModels.retrieve", return_value=retired_model
|
||||
):
|
||||
result = await hass.config_entries.subentries.async_configure(
|
||||
result["flow_id"], {CONF_CHAT_MODEL: retired_model.id}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "additional"
|
||||
assert result["errors"] == {CONF_CHAT_MODEL: "model_retired"}
|
||||
|
||||
with patch(
|
||||
"anthropic.resources.models.AsyncModels.retrieve", return_value=model_list[0]
|
||||
):
|
||||
result = await hass.config_entries.subentries.async_configure(
|
||||
result["flow_id"], {CONF_CHAT_MODEL: model_list[0].id}
|
||||
)
|
||||
assert result["step_id"] == "model"
|
||||
result = await hass.config_entries.subentries.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_CHAT_MODEL] == model_list[0].id
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
async def test_invalid_model(
|
||||
hass: HomeAssistant,
|
||||
@@ -1428,7 +1549,7 @@ async def setup_api_key_entry(
|
||||
with patch(
|
||||
"anthropic.resources.models.AsyncModels.list",
|
||||
new_callable=AsyncMock,
|
||||
return_value=AsyncPage(data=model_list),
|
||||
return_value=AsyncPage(data=model_list, has_more=False),
|
||||
):
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
@@ -1485,7 +1606,7 @@ async def test_update_api_key(
|
||||
patch(
|
||||
"anthropic.resources.models.AsyncModels.list",
|
||||
new_callable=AsyncMock,
|
||||
return_value=AsyncPage(data=model_list),
|
||||
return_value=AsyncPage(data=model_list, has_more=False),
|
||||
),
|
||||
patch.object(
|
||||
hass.config_entries, "async_reload", wraps=hass.config_entries.async_reload
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
"""Tests for the Anthropic integration."""
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
from typing import Literal
|
||||
from unittest.mock import AsyncMock, call, patch
|
||||
|
||||
from anthropic import APITimeoutError, AuthenticationError, RateLimitError
|
||||
from freezegun import freeze_time
|
||||
from anthropic.pagination import AsyncPage
|
||||
from anthropic.types import ModelInfo
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from httpx2 import URL, Request, Response
|
||||
import pytest
|
||||
|
||||
@@ -12,13 +17,17 @@ from homeassistant.components.anthropic.const import DOMAIN
|
||||
from homeassistant.components.anthropic.coordinator import (
|
||||
UPDATE_INTERVAL_CONNECTED,
|
||||
UPDATE_INTERVAL_DISCONNECTED,
|
||||
AnthropicCoordinator,
|
||||
model_alias,
|
||||
)
|
||||
from homeassistant.config_entries import SOURCE_REAUTH
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.helpers import intent
|
||||
from homeassistant.helpers import intent, issue_registry as ir
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import create_content_block, model_list
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
@@ -41,7 +50,682 @@ def test_model_alias(model_id: str, expected_alias: str) -> None:
|
||||
assert model_alias(model_id) == expected_alias
|
||||
|
||||
|
||||
@patch("anthropic.resources.models.AsyncModels.list", new_callable=AsyncMock)
|
||||
@pytest.mark.freeze_time("2026-10-16T12:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
("model_id", "cached_id", "deprecated_id"),
|
||||
[
|
||||
pytest.param(
|
||||
"claude-haiku-5-5-20261007",
|
||||
"claude-haiku-5-5-20261007",
|
||||
"claude-haiku-5-5-20261007",
|
||||
id="exact_model",
|
||||
),
|
||||
pytest.param(
|
||||
"claude-haiku-5-5",
|
||||
"claude-haiku-5-5-20261007",
|
||||
"claude-haiku-5-5",
|
||||
id="requested_alias_listed",
|
||||
),
|
||||
pytest.param(
|
||||
"claude-haiku-5-5",
|
||||
"claude-haiku-5-5-20261007",
|
||||
"claude-haiku-5-5-20261007",
|
||||
id="cached_version_listed",
|
||||
),
|
||||
pytest.param(
|
||||
"claude-haiku-5-5-20261007",
|
||||
"claude-haiku-5-5",
|
||||
"claude-haiku-5-5-20261007",
|
||||
id="requested_version_listed",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("sdk_date", "lifecycle", "retires_at"),
|
||||
[
|
||||
pytest.param(
|
||||
"November 1st, 2026",
|
||||
"deprecated",
|
||||
dt.datetime(2026, 11, 1, tzinfo=dt.UTC),
|
||||
id="ordinal_first_future",
|
||||
),
|
||||
pytest.param(
|
||||
"January 2nd, 2026",
|
||||
"retired",
|
||||
dt.datetime(2026, 1, 2, tzinfo=dt.UTC),
|
||||
id="ordinal_second_past",
|
||||
),
|
||||
pytest.param(
|
||||
"January 3rd, 2027",
|
||||
"deprecated",
|
||||
dt.datetime(2027, 1, 3, tzinfo=dt.UTC),
|
||||
id="ordinal_third_future",
|
||||
),
|
||||
pytest.param(
|
||||
"October 16th, 2026",
|
||||
"retired",
|
||||
dt.datetime(2026, 10, 16, tzinfo=dt.UTC),
|
||||
id="ordinal_today",
|
||||
),
|
||||
pytest.param(
|
||||
"2027-01-03",
|
||||
"deprecated",
|
||||
dt.datetime(2027, 1, 3, tzinfo=dt.UTC),
|
||||
id="iso_future",
|
||||
),
|
||||
pytest.param(
|
||||
"2026-01-02",
|
||||
"retired",
|
||||
dt.datetime(2026, 1, 2, tzinfo=dt.UTC),
|
||||
id="iso_past",
|
||||
),
|
||||
pytest.param(
|
||||
"2026-10-16",
|
||||
"retired",
|
||||
dt.datetime(2026, 10, 16, tzinfo=dt.UTC),
|
||||
id="iso_today",
|
||||
),
|
||||
pytest.param(
|
||||
"2026-10-16T13:00:00+00:00",
|
||||
"deprecated",
|
||||
dt.datetime(2026, 10, 16, 13, tzinfo=dt.UTC),
|
||||
id="iso_timestamp_future",
|
||||
),
|
||||
pytest.param(
|
||||
"2026-10-16T14:00:00+03:00",
|
||||
"retired",
|
||||
dt.datetime(2026, 10, 16, 11, tzinfo=dt.UTC),
|
||||
id="iso_timestamp_timezone",
|
||||
),
|
||||
pytest.param("not a date", "deprecated", None, id="unparseable_date"),
|
||||
pytest.param("", "deprecated", None, id="empty_date"),
|
||||
],
|
||||
)
|
||||
def test_active_model_sdk_deprecation_fallback(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
model_id: str,
|
||||
cached_id: str,
|
||||
deprecated_id: str,
|
||||
sdk_date: str,
|
||||
lifecycle: str,
|
||||
retires_at: dt.datetime | None,
|
||||
) -> None:
|
||||
"""Reconcile active API metadata with SDK dates without changing the cache."""
|
||||
cached_model = model_list[0].model_copy(update={"id": cached_id}, deep=True)
|
||||
original_metadata = cached_model.model_copy(deep=True)
|
||||
coordinator = AnthropicCoordinator(hass, mock_config_entry)
|
||||
coordinator.async_set_updated_data([cached_model])
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS",
|
||||
{deprecated_id: sdk_date},
|
||||
clear=True,
|
||||
):
|
||||
model_info, found = coordinator.get_model_info(model_id)
|
||||
|
||||
assert found
|
||||
assert model_info == original_metadata.model_copy(
|
||||
update={"lifecycle": lifecycle, "retires_at": retires_at}
|
||||
)
|
||||
assert model_info is not cached_model
|
||||
assert cached_model == original_metadata
|
||||
assert coordinator.data == [original_metadata]
|
||||
|
||||
|
||||
def test_invalid_sdk_retirement_preserves_api_date(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Keep an existing API retirement date when the SDK date cannot be parsed."""
|
||||
model = model_list[0].model_copy(
|
||||
update={"retires_at": dt.datetime(2027, 1, 1, tzinfo=dt.UTC)}
|
||||
)
|
||||
coordinator = AnthropicCoordinator(hass, mock_config_entry)
|
||||
coordinator.async_set_updated_data([model])
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS",
|
||||
{model.id: "not a date"},
|
||||
clear=True,
|
||||
):
|
||||
model_info, found = coordinator.get_model_info(model.id)
|
||||
|
||||
assert found
|
||||
assert model_info == model.model_copy(update={"lifecycle": "deprecated"})
|
||||
assert model.lifecycle == "active"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"lifecycle",
|
||||
[
|
||||
pytest.param("active", id="active"),
|
||||
pytest.param("deprecated", id="deprecated"),
|
||||
pytest.param("retired", id="retired"),
|
||||
],
|
||||
)
|
||||
def test_model_lifecycle_without_sdk_deprecation(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
lifecycle: str,
|
||||
) -> None:
|
||||
"""Return API metadata unchanged when the SDK has no deprecation entry."""
|
||||
model = model_list[0].model_copy(update={"lifecycle": lifecycle})
|
||||
coordinator = AnthropicCoordinator(hass, mock_config_entry)
|
||||
coordinator.async_set_updated_data([model])
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS", clear=True
|
||||
):
|
||||
model_info, found = coordinator.get_model_info(model.id)
|
||||
|
||||
assert found
|
||||
assert model_info is model
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T12:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
"lifecycle",
|
||||
[
|
||||
pytest.param("deprecated", id="deprecated"),
|
||||
pytest.param("retired", id="retired"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"sdk_date",
|
||||
[
|
||||
pytest.param("2020-01-01", id="past_sdk_date"),
|
||||
pytest.param("2030-01-01", id="future_sdk_date"),
|
||||
],
|
||||
)
|
||||
def test_inactive_api_model_takes_precedence_over_sdk(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
lifecycle: str,
|
||||
sdk_date: str,
|
||||
) -> None:
|
||||
"""Preserve authoritative API lifecycle and dates over SDK metadata."""
|
||||
model = model_list[0].model_copy(
|
||||
update={
|
||||
"lifecycle": lifecycle,
|
||||
"deprecated_at": dt.datetime(2026, 9, 1, tzinfo=dt.UTC),
|
||||
"retires_at": dt.datetime(2027, 2, 1, tzinfo=dt.UTC),
|
||||
}
|
||||
)
|
||||
coordinator = AnthropicCoordinator(hass, mock_config_entry)
|
||||
coordinator.async_set_updated_data([model])
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS",
|
||||
{model.id: sdk_date},
|
||||
clear=True,
|
||||
):
|
||||
model_info, found = coordinator.get_model_info(model.id)
|
||||
|
||||
assert found
|
||||
assert model_info is model
|
||||
|
||||
|
||||
def test_unknown_sdk_deprecated_model_is_not_found(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""SDK deprecations do not turn an unknown model into a catalogue match."""
|
||||
coordinator = AnthropicCoordinator(hass, mock_config_entry)
|
||||
coordinator.async_set_updated_data(model_list)
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS",
|
||||
{"unknown-model": "January 1st, 2020"},
|
||||
clear=True,
|
||||
):
|
||||
model_info, found = coordinator.get_model_info("unknown-model")
|
||||
|
||||
assert not found
|
||||
assert model_info.id == "unknown-model"
|
||||
assert model_info.lifecycle == "retired"
|
||||
assert model_info.retires_at is None
|
||||
|
||||
|
||||
async def test_model_pagination(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
) -> None:
|
||||
"""Fetch every page of the active and inactive catalogues."""
|
||||
active_models = model_list[:2]
|
||||
inactive_models = [
|
||||
model_list[2].model_copy(update={"lifecycle": "deprecated"}, deep=True),
|
||||
model_list[3].model_copy(update={"lifecycle": "retired"}, deep=True),
|
||||
]
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=active_models[:1], has_more=True),
|
||||
AsyncPage(data=inactive_models[:1], has_more=True),
|
||||
]
|
||||
with (
|
||||
patch.object(
|
||||
AsyncPage, "has_next_page", side_effect=[True, False, True, False]
|
||||
),
|
||||
patch.object(
|
||||
AsyncPage,
|
||||
"get_next_page",
|
||||
side_effect=[
|
||||
AsyncPage(data=active_models[1:], has_more=False),
|
||||
AsyncPage(data=inactive_models[1:], has_more=False),
|
||||
],
|
||||
) as mock_next_page,
|
||||
):
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_model_list.await_args_list == [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
]
|
||||
assert mock_next_page.await_count == 2
|
||||
assert mock_config_entry.runtime_data.data == [*active_models, *inactive_models]
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
"lifecycle",
|
||||
[
|
||||
pytest.param("deprecated", id="deprecated"),
|
||||
pytest.param("retired", id="retired"),
|
||||
],
|
||||
)
|
||||
async def test_model_lifecycle_refresh(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
mock_create_stream: AsyncMock,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
lifecycle: Literal["deprecated", "retired"],
|
||||
) -> None:
|
||||
"""Successful conversations do not postpone catalogue polling or repairs."""
|
||||
active_model = model_list[0].model_copy(deep=True)
|
||||
hass.config_entries.async_update_subentry(
|
||||
mock_config_entry,
|
||||
next(iter(mock_config_entry.subentries.values())),
|
||||
data={"chat_model": active_model.id},
|
||||
)
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[], has_more=False),
|
||||
AsyncPage(data=[], has_more=False),
|
||||
AsyncPage(
|
||||
data=[active_model.model_copy(update={"lifecycle": lifecycle})],
|
||||
has_more=False,
|
||||
),
|
||||
]
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is None
|
||||
mock_create_stream.return_value = [create_content_block(0, ["Hello"])] * 2
|
||||
|
||||
freezer.tick(dt.timedelta(hours=4))
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
result = await conversation.async_converse(
|
||||
hass, "hello", None, Context(), agent_id="conversation.claude_conversation"
|
||||
)
|
||||
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
|
||||
|
||||
freezer.tick(dt.timedelta(hours=4))
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
result = await conversation.async_converse(
|
||||
hass, "hello", None, Context(), agent_id="conversation.claude_conversation"
|
||||
)
|
||||
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
|
||||
assert mock_model_list.await_count == 2
|
||||
|
||||
freezer.tick(dt.timedelta(hours=4))
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
mock_model_list.await_args_list
|
||||
== [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
]
|
||||
* 2
|
||||
)
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is not None
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
async def test_inactive_models_cached_until_active_metadata_changes(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
) -> None:
|
||||
"""Keep inactive metadata between polls and refresh it after an active change."""
|
||||
active_model = model_list[0]
|
||||
updated_active_model = active_model.model_copy(update={"max_tokens": 123456})
|
||||
deprecated_model = model_list[1].model_copy(update={"lifecycle": "deprecated"})
|
||||
retired_model = deprecated_model.model_copy(update={"lifecycle": "retired"})
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[deprecated_model], has_more=False),
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[updated_active_model], has_more=False),
|
||||
AsyncPage(data=[retired_model], has_more=False),
|
||||
]
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
coordinator = mock_config_entry.runtime_data
|
||||
assert coordinator.data == [active_model, deprecated_model]
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.data == [active_model, deprecated_model]
|
||||
assert mock_model_list.await_args_list == [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
]
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.data == [updated_active_model, retired_model]
|
||||
assert mock_model_list.await_args_list[3:] == [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
async def test_reactivated_model_replaces_cached_inactive_model(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
) -> None:
|
||||
"""Remove obsolete inactive metadata when a model becomes active again."""
|
||||
active_model = model_list[0]
|
||||
reactivated_model = model_list[1]
|
||||
retired_model = reactivated_model.model_copy(update={"lifecycle": "retired"})
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[retired_model], has_more=False),
|
||||
AsyncPage(data=[active_model, reactivated_model], has_more=False),
|
||||
AsyncPage(data=[], has_more=False),
|
||||
]
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.runtime_data.data == [active_model, reactivated_model]
|
||||
assert mock_config_entry.runtime_data.get_model_info(reactivated_model.id) == (
|
||||
reactivated_model,
|
||||
True,
|
||||
)
|
||||
assert (
|
||||
mock_model_list.await_args_list
|
||||
== [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
]
|
||||
* 2
|
||||
)
|
||||
|
||||
|
||||
async def test_later_inactive_metadata_takes_precedence(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
) -> None:
|
||||
"""Use the later response when a lifecycle changes between catalogue queries."""
|
||||
model = model_list[0]
|
||||
deprecated_model = model.model_copy(update={"lifecycle": "deprecated"})
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=[model], has_more=False),
|
||||
AsyncPage(data=[deprecated_model], has_more=False),
|
||||
]
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.runtime_data.data == [deprecated_model]
|
||||
assert mock_config_entry.runtime_data.get_model_info(model.id) == (
|
||||
deprecated_model,
|
||||
True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
async def test_empty_model_catalogue(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
) -> None:
|
||||
"""An empty successful catalogue does not refetch inactive models every poll."""
|
||||
mock_model_list.side_effect = None
|
||||
mock_model_list.return_value = AsyncPage(data=[], has_more=False)
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
coordinator = mock_config_entry.runtime_data
|
||||
assert coordinator.data == []
|
||||
assert coordinator.last_update_success
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.data == []
|
||||
assert coordinator.last_update_success
|
||||
assert mock_model_list.await_args_list == [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
("date_field", "event_offset", "extra_requests"),
|
||||
[
|
||||
pytest.param("deprecated_at", dt.timedelta(hours=-1), 0, id="deprecation_past"),
|
||||
pytest.param(
|
||||
"deprecated_at", dt.timedelta(), 0, id="deprecation_previous_success"
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated_at", dt.timedelta(hours=6), 1, id="deprecation_crossed"
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated_at", UPDATE_INTERVAL_CONNECTED, 1, id="deprecation_current_time"
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated_at", dt.timedelta(hours=13), 0, id="deprecation_future"
|
||||
),
|
||||
pytest.param("retires_at", dt.timedelta(hours=-1), 1, id="retirement_past"),
|
||||
pytest.param("retires_at", dt.timedelta(), 1, id="retirement_previous_success"),
|
||||
pytest.param("retires_at", dt.timedelta(hours=6), 1, id="retirement_crossed"),
|
||||
pytest.param(
|
||||
"retires_at", UPDATE_INTERVAL_CONNECTED, 1, id="retirement_current_time"
|
||||
),
|
||||
pytest.param("retires_at", dt.timedelta(hours=13), 0, id="retirement_future"),
|
||||
],
|
||||
)
|
||||
async def test_scheduled_lifecycle_refresh(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
date_field: str,
|
||||
event_offset: dt.timedelta,
|
||||
extra_requests: int,
|
||||
) -> None:
|
||||
"""Refresh after a crossed deprecation date or any passed retirement date."""
|
||||
active_model = model_list[0]
|
||||
inactive_model = model_list[1].model_copy(
|
||||
update={"lifecycle": "deprecated", date_field: dt_util.utcnow() + event_offset}
|
||||
)
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[inactive_model], has_more=False),
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[inactive_model], has_more=False),
|
||||
]
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
mock_model_list.reset_mock()
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.runtime_data.data == [active_model, inactive_model]
|
||||
assert mock_model_list.await_args_list == [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
*[call(lifecycle=["deprecated", "retired"], timeout=10.0)][:extra_requests],
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
async def test_passed_retirement_date_retries_until_model_is_retired(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
) -> None:
|
||||
"""Retry pending retirement and remove cached retired models on another trigger."""
|
||||
active_model = model_list[0]
|
||||
updated_active_model = active_model.model_copy(update={"max_tokens": 123456})
|
||||
deprecated_model = model_list[1].model_copy(
|
||||
update={
|
||||
"lifecycle": "deprecated",
|
||||
"retires_at": dt_util.utcnow() - dt.timedelta(days=1),
|
||||
}
|
||||
)
|
||||
retired_model = deprecated_model.model_copy(update={"lifecycle": "retired"})
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[deprecated_model], has_more=False),
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[deprecated_model], has_more=False),
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[retired_model], has_more=False),
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[updated_active_model], has_more=False),
|
||||
AsyncPage(data=[], has_more=False),
|
||||
]
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
coordinator = mock_config_entry.runtime_data
|
||||
assert coordinator.data == [active_model, deprecated_model]
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.data == [active_model, deprecated_model]
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.data == [active_model, retired_model]
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.data == [active_model, retired_model]
|
||||
assert mock_model_list.await_count == 7
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.data == [updated_active_model]
|
||||
assert mock_model_list.await_args_list == [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
] * 3 + [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
("active_model", "inactive_model"),
|
||||
[
|
||||
pytest.param(
|
||||
model_list[0].model_copy(update={"max_tokens": 123456}),
|
||||
model_list[1].model_copy(update={"lifecycle": "deprecated"}),
|
||||
id="active_metadata_changed",
|
||||
),
|
||||
pytest.param(
|
||||
model_list[0],
|
||||
model_list[1].model_copy(
|
||||
update={
|
||||
"lifecycle": "deprecated",
|
||||
"retires_at": dt.datetime(2026, 10, 16, 6, tzinfo=dt.UTC),
|
||||
}
|
||||
),
|
||||
id="scheduled_retirement_crossed",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_inactive_fetch_failure_retries_without_committing_partial_data(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
active_model: ModelInfo,
|
||||
inactive_model: ModelInfo,
|
||||
) -> None:
|
||||
"""Keep the old catalogue and retry inactive changes after an unsuccessful poll."""
|
||||
retired_model = inactive_model.model_copy(update={"lifecycle": "retired"})
|
||||
mock_model_list.side_effect = [
|
||||
AsyncPage(data=[model_list[0]], has_more=False),
|
||||
AsyncPage(data=[inactive_model], has_more=False),
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
APITimeoutError(request=Request("GET", "https://api.anthropic.com/v1/models")),
|
||||
AsyncPage(data=[active_model], has_more=False),
|
||||
AsyncPage(data=[retired_model], has_more=False),
|
||||
]
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
coordinator = mock_config_entry.runtime_data
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert not coordinator.last_update_success
|
||||
assert coordinator.update_interval == UPDATE_INTERVAL_DISCONNECTED
|
||||
assert coordinator.data == [model_list[0], inactive_model]
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_DISCONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert coordinator.last_update_success
|
||||
assert coordinator.update_interval == UPDATE_INTERVAL_CONNECTED
|
||||
assert coordinator.data == [active_model, retired_model]
|
||||
assert (
|
||||
mock_model_list.await_args_list
|
||||
== [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["deprecated", "retired"], timeout=10.0),
|
||||
]
|
||||
* 3
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
async def test_auth_error_handling(
|
||||
mock_model_list: AsyncMock,
|
||||
@@ -50,6 +734,7 @@ async def test_auth_error_handling(
|
||||
mock_create_stream: AsyncMock,
|
||||
) -> None:
|
||||
"""Test reauth after authentication error during conversation."""
|
||||
mock_model_list.reset_mock()
|
||||
# This is an assumption of the tests, not the main code:
|
||||
assert UPDATE_INTERVAL_DISCONNECTED < UPDATE_INTERVAL_CONNECTED
|
||||
|
||||
@@ -83,15 +768,16 @@ async def test_auth_error_handling(
|
||||
assert flow["context"]["entry_id"] == mock_config_entry.entry_id
|
||||
|
||||
|
||||
@freeze_time("2026-02-27 12:00:00")
|
||||
@patch("anthropic.resources.models.AsyncModels.list", new_callable=AsyncMock)
|
||||
@pytest.mark.freeze_time("2026-02-27T12:00:00Z")
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
async def test_connection_error_handling(
|
||||
mock_model_list: AsyncMock,
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_create_stream: AsyncMock,
|
||||
) -> None:
|
||||
"""Test making entity unavailable on connection error."""
|
||||
mock_model_list.reset_mock()
|
||||
mock_create_stream.side_effect = APITimeoutError(
|
||||
request=Request(method="POST", url=URL()),
|
||||
)
|
||||
@@ -140,19 +826,149 @@ async def test_connection_error_handling(
|
||||
assert state
|
||||
assert state.state == "2026-02-27T12:00:00+00:00"
|
||||
|
||||
# Verify the background check period
|
||||
test_time = dt_util.utcnow() + UPDATE_INTERVAL_DISCONNECTED
|
||||
async_fire_time_changed(hass, test_time)
|
||||
await hass.async_block_till_done()
|
||||
mock_model_list.assert_not_awaited()
|
||||
freezer.tick(dt.timedelta(seconds=20))
|
||||
mock_create_stream.side_effect = APITimeoutError(
|
||||
request=Request(method="POST", url=URL()),
|
||||
)
|
||||
await conversation.async_converse(
|
||||
hass, "hello", None, Context(), agent_id="conversation.claude_conversation"
|
||||
)
|
||||
freezer.tick(dt.timedelta(seconds=20))
|
||||
mock_create_stream.side_effect = RateLimitError(
|
||||
message=None,
|
||||
response=Response(status_code=429, request=Request(method="POST", url=URL())),
|
||||
body=None,
|
||||
)
|
||||
await conversation.async_converse(
|
||||
hass, "hello", None, Context(), agent_id="conversation.claude_conversation"
|
||||
)
|
||||
|
||||
test_time += UPDATE_INTERVAL_CONNECTED - UPDATE_INTERVAL_DISCONNECTED
|
||||
async_fire_time_changed(hass, test_time)
|
||||
# Connection recovery keeps the original pending catalogue check.
|
||||
freezer.tick(dt.timedelta(seconds=20))
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
mock_model_list.assert_awaited_once_with(lifecycle=["active"], timeout=10.0)
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_CONNECTED - UPDATE_INTERVAL_DISCONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
mock_model_list.assert_awaited_once()
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_DISCONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
assert mock_model_list.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
async def test_successful_conversation_preserves_queued_catalogue_refresh(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_model_list: AsyncMock,
|
||||
mock_create_stream: AsyncMock,
|
||||
) -> None:
|
||||
"""A healthy connection report does not cancel a queued debounced refresh."""
|
||||
mock_model_list.reset_mock()
|
||||
mock_create_stream.return_value = [create_content_block(0, ["Hello"])]
|
||||
with patch(
|
||||
"anthropic.resources.messages.AsyncMessages.create",
|
||||
side_effect=AuthenticationError(
|
||||
message="Invalid API key",
|
||||
response=Response(
|
||||
status_code=401, request=Request(method="POST", url=URL())
|
||||
),
|
||||
body=None,
|
||||
),
|
||||
):
|
||||
for _ in range(2):
|
||||
result = await conversation.async_converse(
|
||||
hass,
|
||||
"hello",
|
||||
None,
|
||||
Context(),
|
||||
agent_id="conversation.claude_conversation",
|
||||
)
|
||||
assert result.response.response_type is intent.IntentResponseType.ERROR
|
||||
mock_model_list.assert_awaited_once()
|
||||
|
||||
result = await conversation.async_converse(
|
||||
hass, "hello", None, Context(), agent_id="conversation.claude_conversation"
|
||||
)
|
||||
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
|
||||
|
||||
freezer.tick(dt.timedelta(seconds=10))
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_model_list.await_args_list == [
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
call(lifecycle=["active"], timeout=10.0),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T00:00:00Z")
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
async def test_successful_conversation_preserves_in_flight_catalogue_retry(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
mock_create_stream: AsyncMock,
|
||||
) -> None:
|
||||
"""Successful messages during a timed-out catalogue retry keep its short interval."""
|
||||
coordinator = mock_config_entry.runtime_data
|
||||
request_started = asyncio.Event()
|
||||
finish_request = asyncio.Event()
|
||||
|
||||
async def timeout_models_list(**_kwargs: object) -> AsyncPage[ModelInfo]:
|
||||
request_started.set()
|
||||
await finish_request.wait()
|
||||
raise APITimeoutError(
|
||||
request=Request("GET", "https://api.anthropic.com/v1/models")
|
||||
)
|
||||
|
||||
mock_model_list.reset_mock()
|
||||
mock_model_list.side_effect = timeout_models_list
|
||||
mock_create_stream.return_value = [create_content_block(0, ["Hello"])] * 2
|
||||
coordinator.mark_connection_error()
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_DISCONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
try:
|
||||
await request_started.wait()
|
||||
result = await conversation.async_converse(
|
||||
hass, "hello", None, Context(), agent_id="conversation.claude_conversation"
|
||||
)
|
||||
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
|
||||
assert coordinator.last_update_success
|
||||
assert coordinator.update_interval == UPDATE_INTERVAL_DISCONNECTED
|
||||
finally:
|
||||
finish_request.set()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert not coordinator.last_update_success
|
||||
assert coordinator.update_interval == UPDATE_INTERVAL_DISCONNECTED
|
||||
mock_model_list.assert_awaited_once()
|
||||
mock_model_list.side_effect = None
|
||||
mock_model_list.return_value = AsyncPage(data=model_list, has_more=False)
|
||||
|
||||
result = await conversation.async_converse(
|
||||
hass, "hello", None, Context(), agent_id="conversation.claude_conversation"
|
||||
)
|
||||
assert result.response.response_type is intent.IntentResponseType.ACTION_DONE
|
||||
assert coordinator.last_update_success
|
||||
assert coordinator.update_interval == UPDATE_INTERVAL_DISCONNECTED
|
||||
|
||||
freezer.tick(UPDATE_INTERVAL_DISCONNECTED)
|
||||
async_fire_time_changed(hass, dt_util.utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_model_list.await_count == 2
|
||||
assert coordinator.last_update_success
|
||||
assert coordinator.update_interval == UPDATE_INTERVAL_CONNECTED
|
||||
|
||||
|
||||
@patch("anthropic.resources.models.AsyncModels.list", new_callable=AsyncMock)
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
async def test_connection_check_reauth(
|
||||
mock_model_list: AsyncMock,
|
||||
@@ -160,6 +976,7 @@ async def test_connection_check_reauth(
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test authentication error during background availability check."""
|
||||
mock_model_list.reset_mock()
|
||||
mock_model_list.side_effect = APITimeoutError(
|
||||
request=Request(method="POST", url=URL()),
|
||||
)
|
||||
@@ -216,7 +1033,6 @@ async def test_connection_check_reauth(
|
||||
assert flow["context"]["entry_id"] == mock_config_entry.entry_id
|
||||
|
||||
|
||||
@patch("anthropic.resources.models.AsyncModels.list", new_callable=AsyncMock)
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
async def test_connection_restore(
|
||||
mock_model_list: AsyncMock,
|
||||
@@ -224,6 +1040,7 @@ async def test_connection_restore(
|
||||
mock_create_stream: AsyncMock,
|
||||
) -> None:
|
||||
"""Test background availability check restore on non-connectivity error."""
|
||||
mock_model_list.reset_mock()
|
||||
mock_create_stream.side_effect = APITimeoutError(
|
||||
request=Request(method="POST", url=URL()),
|
||||
)
|
||||
@@ -261,6 +1078,7 @@ async def test_connection_restore(
|
||||
|
||||
# Now make the background check succeed
|
||||
mock_model_list.side_effect = None
|
||||
mock_model_list.return_value = AsyncPage(data=model_list, has_more=False)
|
||||
test_time += UPDATE_INTERVAL_DISCONNECTED
|
||||
async_fire_time_changed(hass, test_time)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""Tests for the Anthropic integration."""
|
||||
|
||||
from typing import TypedDict
|
||||
from unittest.mock import patch
|
||||
from datetime import UTC, datetime
|
||||
from functools import partial
|
||||
from typing import Literal, TypedDict
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from anthropic import (
|
||||
APIConnectionError,
|
||||
@@ -10,13 +12,19 @@ from anthropic import (
|
||||
AuthenticationError,
|
||||
BadRequestError,
|
||||
)
|
||||
from anthropic.pagination import AsyncPage
|
||||
from anthropic.types import ModelInfo
|
||||
import attr
|
||||
import httpx2
|
||||
from httpx2 import URL, Request, Response
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.anthropic.config_flow import AnthropicConfigFlow
|
||||
from homeassistant.components.anthropic.const import DOMAIN
|
||||
from homeassistant.components.anthropic.const import (
|
||||
CONF_CHAT_MODEL,
|
||||
CONF_RECOMMENDED,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.config_entries import (
|
||||
ConfigEntryDisabler,
|
||||
ConfigEntryState,
|
||||
@@ -24,6 +32,7 @@ from homeassistant.config_entries import (
|
||||
)
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import (
|
||||
device_registry as dr,
|
||||
entity_registry as er,
|
||||
@@ -33,6 +42,8 @@ from homeassistant.helpers.device_registry import DeviceEntryDisabler
|
||||
from homeassistant.helpers.entity_registry import RegistryEntryDisabler
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import model_list
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
MINOR_VERSION = AnthropicConfigFlow.MINOR_VERSION
|
||||
@@ -47,6 +58,19 @@ class ConversationSubentryExpectation(TypedDict):
|
||||
device: int
|
||||
|
||||
|
||||
def _model_page(
|
||||
models: list[ModelInfo],
|
||||
*,
|
||||
lifecycle: list[Literal["active", "deprecated", "retired"]],
|
||||
timeout: float,
|
||||
) -> AsyncPage[ModelInfo]:
|
||||
"""Return models matching the requested lifecycle stages."""
|
||||
return AsyncPage(
|
||||
data=[model for model in models if model.lifecycle in lifecycle],
|
||||
has_more=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "error"),
|
||||
[
|
||||
@@ -109,23 +133,122 @@ async def test_init_auth_error(
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_init_component")
|
||||
@pytest.mark.parametrize(
|
||||
("lifecycle", "retires_at", "chat_model", "expected_issue"),
|
||||
[
|
||||
pytest.param("active", None, "claude-test-9", False, id="active"),
|
||||
pytest.param(
|
||||
"active",
|
||||
datetime(2025, 1, 1, tzinfo=UTC),
|
||||
"claude-test-9",
|
||||
False,
|
||||
id="active_with_past_retirement_date",
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated",
|
||||
datetime(2030, 1, 1, tzinfo=UTC),
|
||||
"claude-test-9",
|
||||
True,
|
||||
id="deprecated",
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated",
|
||||
datetime(2025, 1, 1, tzinfo=UTC),
|
||||
"claude-test-9",
|
||||
True,
|
||||
id="deprecated_with_overdue_retirement",
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated", None, "claude-test-9", True, id="no_retirement_date"
|
||||
),
|
||||
pytest.param(
|
||||
"retired",
|
||||
datetime(2025, 1, 1, tzinfo=UTC),
|
||||
"claude-test-9",
|
||||
True,
|
||||
id="retired",
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated",
|
||||
None,
|
||||
"claude-test-9-20261001",
|
||||
True,
|
||||
id="dated_model",
|
||||
),
|
||||
pytest.param(
|
||||
"deprecated", None, "claude-unknown-model", False, id="missing_model"
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_init_repair_issue(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
lifecycle: Literal["active", "deprecated", "retired"],
|
||||
retires_at: datetime | None,
|
||||
chat_model: str,
|
||||
expected_issue: bool,
|
||||
) -> None:
|
||||
"""Test that repair issue is created on deprecated model."""
|
||||
"""Use API lifecycle rather than model names or retirement dates for repairs."""
|
||||
model_info = model_list[0].model_copy(
|
||||
update={
|
||||
"id": "claude-test-9",
|
||||
"lifecycle": lifecycle,
|
||||
"deprecated_at": datetime(2024, 1, 1, tzinfo=UTC),
|
||||
"retires_at": retires_at,
|
||||
}
|
||||
)
|
||||
hass.config_entries.async_update_subentry(
|
||||
mock_config_entry,
|
||||
next(iter(mock_config_entry.subentries.values())),
|
||||
data={
|
||||
"chat_model": "claude-opus-4-20250514",
|
||||
},
|
||||
data={"chat_model": chat_model},
|
||||
)
|
||||
mock_model_list.side_effect = partial(_model_page, [model_info])
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated")
|
||||
assert (
|
||||
issue_registry.async_get_issue(DOMAIN, "model_deprecated") is not None
|
||||
) is expected_issue
|
||||
|
||||
|
||||
async def test_reconfigure_deprecated_model_repair(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_model_list: AsyncMock,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
) -> None:
|
||||
"""Reconfiguring a subentry reloads its parent and creates a repair."""
|
||||
deprecated_model = model_list[0].model_copy(
|
||||
update={"id": "claude-test-deprecated", "lifecycle": "deprecated"}
|
||||
)
|
||||
mock_model_list.side_effect = partial(_model_page, [*model_list, deprecated_model])
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
coordinator = mock_config_entry.runtime_data
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is None
|
||||
|
||||
subentry = next(iter(mock_config_entry.subentries.values()))
|
||||
result = await mock_config_entry.start_subentry_reconfigure_flow(
|
||||
hass, subentry.subentry_id
|
||||
)
|
||||
result = await hass.config_entries.subentries.async_configure(
|
||||
result["flow_id"], {CONF_RECOMMENDED: False}
|
||||
)
|
||||
result = await hass.config_entries.subentries.async_configure(
|
||||
result["flow_id"], {CONF_CHAT_MODEL: deprecated_model.id}
|
||||
)
|
||||
assert result["step_id"] == "model"
|
||||
result = await hass.config_entries.subentries.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reconfigure_successful"
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
assert mock_config_entry.runtime_data is not coordinator
|
||||
assert subentry.data[CONF_CHAT_MODEL] == deprecated_model.id
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is not None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_setup_entry")
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""Tests for the Anthropic repairs flow."""
|
||||
|
||||
import datetime
|
||||
from functools import partial
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, call
|
||||
from unittest.mock import AsyncMock, MagicMock, call, patch
|
||||
|
||||
from anthropic import (
|
||||
APIConnectionError,
|
||||
@@ -11,7 +13,7 @@ from anthropic import (
|
||||
NotFoundError,
|
||||
)
|
||||
from anthropic.pagination import AsyncPage
|
||||
from anthropic.types import ModelInfo
|
||||
from anthropic.types import ModelInfo, ModelLine
|
||||
from httpx2 import Request, Response
|
||||
import pytest
|
||||
|
||||
@@ -33,7 +35,10 @@ from homeassistant.components.anthropic.const import (
|
||||
CONF_WEB_SEARCH_USER_LOCATION,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.components.anthropic.coordinator import model_alias
|
||||
from homeassistant.components.anthropic.coordinator import (
|
||||
AnthropicCoordinator,
|
||||
model_alias,
|
||||
)
|
||||
from homeassistant.config_entries import (
|
||||
ConfigEntryState,
|
||||
ConfigSubentry,
|
||||
@@ -62,6 +67,41 @@ WEB_SEARCH_OPTIONS = {
|
||||
SERVER_TOOL_OPTIONS = {CONF_CODE_EXECUTION: True, **WEB_SEARCH_OPTIONS}
|
||||
|
||||
|
||||
def _deprecated_model(
|
||||
model_id: str, line: ModelLine, retires_at: datetime.datetime
|
||||
) -> ModelInfo:
|
||||
"""Return synthetic metadata for an obsolete model."""
|
||||
return ModelInfo(
|
||||
id=model_id,
|
||||
type="model",
|
||||
display_name=model_id,
|
||||
created_at=datetime.datetime(2024, 1, 1, tzinfo=datetime.UTC),
|
||||
deprecated_at=datetime.datetime(2025, 8, 13, tzinfo=datetime.UTC),
|
||||
retires_at=retires_at,
|
||||
lifecycle="deprecated",
|
||||
line=line,
|
||||
)
|
||||
|
||||
|
||||
DEPRECATED_MODEL_LIST = [
|
||||
_deprecated_model(
|
||||
"claude-3-5-haiku-20241022",
|
||||
"haiku",
|
||||
datetime.datetime(2026, 2, 19, tzinfo=datetime.UTC),
|
||||
),
|
||||
_deprecated_model(
|
||||
"claude-3-7-sonnet-20250219",
|
||||
"sonnet",
|
||||
datetime.datetime(2026, 2, 19, tzinfo=datetime.UTC),
|
||||
),
|
||||
_deprecated_model(
|
||||
"claude-3-opus-20240229",
|
||||
"opus",
|
||||
datetime.datetime(2026, 1, 5, tzinfo=datetime.UTC),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _copy_model_info(model_id: str) -> ModelInfo:
|
||||
"""Return an independent copy of the live model metadata."""
|
||||
return next(
|
||||
@@ -111,8 +151,14 @@ def _make_entry(
|
||||
object.__setattr__(entry, "state", ConfigEntryState.LOADED)
|
||||
entry.runtime_data = SimpleNamespace(
|
||||
client=MagicMock(
|
||||
models=MagicMock(list=AsyncMock(return_value=AsyncPage(data=model_list)))
|
||||
)
|
||||
models=MagicMock(
|
||||
list=AsyncMock(return_value=AsyncPage(data=model_list, has_more=False))
|
||||
)
|
||||
),
|
||||
data=[*model_list, *DEPRECATED_MODEL_LIST],
|
||||
)
|
||||
entry.runtime_data.get_model_info = partial(
|
||||
AnthropicCoordinator.get_model_info, entry.runtime_data
|
||||
)
|
||||
return entry
|
||||
|
||||
@@ -130,6 +176,16 @@ def _get_subentry(
|
||||
|
||||
|
||||
async def _setup_repairs(hass: HomeAssistant) -> None:
|
||||
"""Set up repairs and create an obsolete-model issue."""
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
"model_deprecated",
|
||||
is_fixable=True,
|
||||
is_persistent=False,
|
||||
severity=ir.IssueSeverity.WARNING,
|
||||
translation_key="model_deprecated",
|
||||
)
|
||||
hass.config.components.add(DOMAIN)
|
||||
assert await async_setup_component(hass, "repairs", {})
|
||||
|
||||
@@ -173,16 +229,6 @@ async def test_repair_flow_iterates_subentries(
|
||||
],
|
||||
)
|
||||
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
"model_deprecated",
|
||||
is_fixable=True,
|
||||
is_persistent=False,
|
||||
severity=ir.IssueSeverity.WARNING,
|
||||
translation_key="model_deprecated",
|
||||
)
|
||||
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
@@ -193,7 +239,7 @@ async def test_repair_flow_iterates_subentries(
|
||||
assert placeholders["entry_name"] == entry_one.title
|
||||
assert placeholders["subentry_name"] == "Conversation One"
|
||||
assert placeholders["subentry_type"] == "Conversation agent"
|
||||
assert placeholders["retirement_date"] == "February 19th, 2026"
|
||||
assert placeholders["retirement_date"] == "2026-02-19"
|
||||
|
||||
flow_id = result["flow_id"]
|
||||
|
||||
@@ -212,7 +258,7 @@ async def test_repair_flow_iterates_subentries(
|
||||
assert placeholders["entry_name"] == entry_one.title
|
||||
assert placeholders["subentry_name"] == "AI task One"
|
||||
assert placeholders["subentry_type"] == "AI task"
|
||||
assert placeholders["retirement_date"] == "February 19th, 2026"
|
||||
assert placeholders["retirement_date"] == "2026-02-19"
|
||||
|
||||
result = await process_repair_fix_flow(
|
||||
client,
|
||||
@@ -233,7 +279,7 @@ async def test_repair_flow_iterates_subentries(
|
||||
assert placeholders["entry_name"] == entry_two.title
|
||||
assert placeholders["subentry_name"] == "Conversation Two"
|
||||
assert placeholders["subentry_type"] == "Conversation agent"
|
||||
assert placeholders["retirement_date"] == "January 5th, 2026"
|
||||
assert placeholders["retirement_date"] == "2026-01-05"
|
||||
|
||||
result = await process_repair_fix_flow(
|
||||
client,
|
||||
@@ -269,16 +315,6 @@ async def test_repair_flow_no_deprecated_models(
|
||||
],
|
||||
)
|
||||
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
"model_deprecated",
|
||||
is_fixable=True,
|
||||
is_persistent=False,
|
||||
severity=ir.IssueSeverity.WARNING,
|
||||
translation_key="model_deprecated",
|
||||
)
|
||||
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
@@ -526,20 +562,11 @@ async def test_repair_flow_model_options(
|
||||
],
|
||||
)
|
||||
entry.runtime_data.client.models.list.return_value = AsyncPage(
|
||||
data=[model_info][:cached_model_count]
|
||||
data=[model_info][:cached_model_count], has_more=False
|
||||
)
|
||||
retrieve = entry.runtime_data.client.models.retrieve = AsyncMock(
|
||||
return_value=model_info
|
||||
)
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
"model_deprecated",
|
||||
is_fixable=True,
|
||||
is_persistent=False,
|
||||
severity=ir.IssueSeverity.WARNING,
|
||||
translation_key="model_deprecated",
|
||||
)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
@@ -646,20 +673,11 @@ async def test_repair_flow_server_tool_options(
|
||||
],
|
||||
)
|
||||
entry.runtime_data.client.models.list.return_value = AsyncPage(
|
||||
data=[model_info][:cached_model_count]
|
||||
data=[model_info][:cached_model_count], has_more=False
|
||||
)
|
||||
retrieve = entry.runtime_data.client.models.retrieve = AsyncMock(
|
||||
return_value=model_info
|
||||
)
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
"model_deprecated",
|
||||
is_fixable=True,
|
||||
is_persistent=False,
|
||||
severity=ir.IssueSeverity.WARNING,
|
||||
translation_key="model_deprecated",
|
||||
)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
@@ -747,7 +765,9 @@ async def test_repair_flow_model_lookup_error(
|
||||
},
|
||||
],
|
||||
)
|
||||
entry.runtime_data.client.models.list.return_value = AsyncPage(data=[])
|
||||
entry.runtime_data.client.models.list.return_value = AsyncPage(
|
||||
data=[], has_more=False
|
||||
)
|
||||
retrieve = entry.runtime_data.client.models.retrieve = AsyncMock(
|
||||
side_effect=[
|
||||
error,
|
||||
@@ -755,15 +775,6 @@ async def test_repair_flow_model_lookup_error(
|
||||
_copy_model_info("claude-haiku-4-5"),
|
||||
]
|
||||
)
|
||||
ir.async_create_issue(
|
||||
hass,
|
||||
DOMAIN,
|
||||
"model_deprecated",
|
||||
is_fixable=True,
|
||||
is_persistent=False,
|
||||
severity=ir.IssueSeverity.WARNING,
|
||||
translation_key="model_deprecated",
|
||||
)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
@@ -807,7 +818,8 @@ async def test_repair_flow_model_lookup_error(
|
||||
"model": "claude-3-5-haiku-20241022",
|
||||
"subentry_name": "AI task",
|
||||
"subentry_type": "AI task",
|
||||
"retirement_date": "February 19th, 2026",
|
||||
"retirement_date": "2026-02-19",
|
||||
"deprecation_date": "2025-08-13",
|
||||
}
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "claude-opus-5-5",
|
||||
@@ -831,3 +843,520 @@ async def test_repair_flow_model_lookup_error(
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is None
|
||||
assert retrieve.await_count == 3
|
||||
retrieve.assert_awaited_with("claude-haiku-4-5", timeout=10.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model_info", "expected_step", "deprecation_date", "retirement_date"),
|
||||
[
|
||||
pytest.param(
|
||||
DEPRECATED_MODEL_LIST[0].model_copy(update={"id": "custom-obsolete"}),
|
||||
"init",
|
||||
"2025-08-13",
|
||||
"2026-02-19",
|
||||
id="deprecated_with_past_retirement_date",
|
||||
),
|
||||
pytest.param(
|
||||
DEPRECATED_MODEL_LIST[0].model_copy(
|
||||
update={"id": "custom-obsolete", "lifecycle": "retired"}
|
||||
),
|
||||
"retired",
|
||||
"2025-08-13",
|
||||
"2026-02-19",
|
||||
id="retired",
|
||||
),
|
||||
pytest.param(
|
||||
DEPRECATED_MODEL_LIST[0].model_copy(
|
||||
update={
|
||||
"id": "custom-obsolete",
|
||||
"deprecated_at": None,
|
||||
"retires_at": None,
|
||||
}
|
||||
),
|
||||
"init",
|
||||
"—",
|
||||
"—",
|
||||
id="missing_dates",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_repair_flow_lifecycle_metadata(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
model_info: ModelInfo,
|
||||
expected_step: str,
|
||||
deprecation_date: str,
|
||||
retirement_date: str,
|
||||
) -> None:
|
||||
"""Use API lifecycle and dates for custom models."""
|
||||
entry = _make_entry(
|
||||
hass,
|
||||
title="Claude",
|
||||
api_key="key",
|
||||
subentries_data=[
|
||||
{
|
||||
"data": {CONF_CHAT_MODEL: "custom-obsolete"},
|
||||
"subentry_type": "conversation",
|
||||
"title": "Conversation",
|
||||
"unique_id": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
entry.runtime_data.data = [model_info]
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == expected_step
|
||||
assert result["description_placeholders"] == {
|
||||
"entry_name": entry.title,
|
||||
"model": "custom-obsolete",
|
||||
"subentry_name": "Conversation",
|
||||
"subentry_type": "Conversation agent",
|
||||
"deprecation_date": deprecation_date,
|
||||
"retirement_date": retirement_date,
|
||||
}
|
||||
|
||||
result = await process_repair_fix_flow(
|
||||
client,
|
||||
result["flow_id"],
|
||||
json={CONF_CHAT_MODEL: "claude-haiku-5-5"},
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "claude-haiku-5-5"
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"metadata",
|
||||
[
|
||||
pytest.param(
|
||||
[
|
||||
DEPRECATED_MODEL_LIST[0].model_copy(
|
||||
update={"id": "claude-active-haiku", "lifecycle": "active"}
|
||||
)
|
||||
],
|
||||
id="active_model",
|
||||
),
|
||||
pytest.param([], id="unknown_model_retired_fallback"),
|
||||
],
|
||||
)
|
||||
async def test_repair_flow_skips_active_and_unknown_models(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
metadata: list[ModelInfo],
|
||||
) -> None:
|
||||
"""Only authoritative API deprecation or retirement metadata starts a repair."""
|
||||
entry = _make_entry(
|
||||
hass,
|
||||
title="Claude",
|
||||
api_key="key",
|
||||
subentries_data=[
|
||||
{
|
||||
"data": {CONF_CHAT_MODEL: "claude-active-haiku"},
|
||||
"subentry_type": "conversation",
|
||||
"title": "Conversation",
|
||||
"unique_id": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
entry.runtime_data.data = metadata
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
entry.runtime_data.client.models.list.assert_not_awaited()
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "claude-active-haiku"
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("line", "expected_model"),
|
||||
[
|
||||
pytest.param("haiku", "claude-opus-1", id="metadata_line"),
|
||||
pytest.param(None, None, id="no_line"),
|
||||
pytest.param("mythos", None, id="no_active_model_in_line"),
|
||||
],
|
||||
)
|
||||
async def test_repair_flow_model_selection(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
line: ModelLine | None,
|
||||
expected_model: str | None,
|
||||
) -> None:
|
||||
"""Use matching model lines in API order and offer only active models."""
|
||||
entry = _make_entry(
|
||||
hass,
|
||||
title="Claude",
|
||||
api_key="key",
|
||||
subentries_data=[
|
||||
{
|
||||
"data": {CONF_CHAT_MODEL: "claude-3-7-sonnet-20250219"},
|
||||
"subentry_type": "conversation",
|
||||
"title": "Conversation",
|
||||
"unique_id": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
entry.runtime_data.data = [
|
||||
DEPRECATED_MODEL_LIST[1].model_copy(update={"line": line})
|
||||
]
|
||||
entry.runtime_data.client.models.list.return_value = AsyncPage(
|
||||
data=[
|
||||
DEPRECATED_MODEL_LIST[0],
|
||||
DEPRECATED_MODEL_LIST[0].model_copy(
|
||||
update={"id": "retired-haiku", "lifecycle": "retired"}
|
||||
),
|
||||
_copy_model_info("claude-sonnet-5-5").model_copy(
|
||||
update={"id": "claude-haiku-99"}
|
||||
),
|
||||
_copy_model_info("claude-haiku-5-5").model_copy(
|
||||
update={"id": "claude-opus-1"}
|
||||
),
|
||||
_copy_model_info("claude-haiku-5-5").model_copy(
|
||||
update={"id": "claude-opus-99"}
|
||||
),
|
||||
],
|
||||
has_more=False,
|
||||
)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
model_field = next(
|
||||
field for field in result["data_schema"] if field["name"] == CONF_CHAT_MODEL
|
||||
)
|
||||
assert model_field.get("default") == expected_model
|
||||
assert model_field["selector"]["select"]["options"] == [
|
||||
{"label": "Claude Sonnet 5.5", "value": "claude-haiku-99"},
|
||||
{"label": "Claude Haiku 5.5", "value": "claude-opus-1"},
|
||||
{"label": "Claude Haiku 5.5", "value": "claude-opus-99"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T12:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
("sdk_key", "retirement_date", "submitted_model"),
|
||||
[
|
||||
pytest.param(
|
||||
"claude-sonnet-4-5-20250929",
|
||||
"November 30th, 2026",
|
||||
"claude-sonnet-4-5",
|
||||
id="deprecated_version",
|
||||
),
|
||||
pytest.param(
|
||||
"claude-sonnet-4-5",
|
||||
"November 30th, 2026",
|
||||
"claude-sonnet-4-5",
|
||||
id="deprecated_alias",
|
||||
),
|
||||
pytest.param(
|
||||
"claude-sonnet-4-5",
|
||||
"November 30th, 2026",
|
||||
"claude-sonnet-4-5-20250929",
|
||||
id="deprecated_alias_dated_submission",
|
||||
),
|
||||
pytest.param(
|
||||
"claude-sonnet-4-5-20250929",
|
||||
"October 15th, 2026",
|
||||
"claude-sonnet-4-5-20250929",
|
||||
id="retired_version",
|
||||
),
|
||||
pytest.param(
|
||||
"claude-sonnet-4-5-20250929",
|
||||
"unknown",
|
||||
"claude-sonnet-4-5",
|
||||
id="unknown_retirement_date",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_repair_flow_sdk_inactive_current_model(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
sdk_key: str,
|
||||
retirement_date: str,
|
||||
submitted_model: str,
|
||||
) -> None:
|
||||
"""Do not offer or accept the current model when only the SDK marks it inactive."""
|
||||
entry = _make_entry(
|
||||
hass,
|
||||
title="Claude",
|
||||
api_key="key",
|
||||
subentries_data=[
|
||||
{
|
||||
"data": {CONF_CHAT_MODEL: "claude-sonnet-4-5"},
|
||||
"subentry_type": "conversation",
|
||||
"title": "Conversation",
|
||||
"unique_id": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
current_model = _copy_model_info("claude-sonnet-4-5")
|
||||
active_model = _copy_model_info("claude-sonnet-5-5")
|
||||
entry.runtime_data.data = [current_model, active_model]
|
||||
entry.runtime_data.client.models.list.return_value = AsyncPage(
|
||||
data=[current_model, active_model], has_more=False
|
||||
)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS",
|
||||
{sdk_key: retirement_date},
|
||||
clear=True,
|
||||
):
|
||||
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
model_field = next(
|
||||
field for field in result["data_schema"] if field["name"] == CONF_CHAT_MODEL
|
||||
)
|
||||
assert model_field["default"] == "claude-sonnet-5-5"
|
||||
assert model_field["selector"]["select"]["options"] == [
|
||||
{"label": "Claude Sonnet 5.5", "value": "claude-sonnet-5-5"}
|
||||
]
|
||||
flow_id = result["flow_id"]
|
||||
step_id = result["step_id"]
|
||||
placeholders = result["description_placeholders"]
|
||||
|
||||
result = await process_repair_fix_flow(
|
||||
client, flow_id, json={CONF_CHAT_MODEL: submitted_model}
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["flow_id"] == flow_id
|
||||
assert result["step_id"] == step_id
|
||||
assert result["errors"] == {CONF_CHAT_MODEL: "model_not_active"}
|
||||
assert result["description_placeholders"] == placeholders
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "claude-sonnet-4-5"
|
||||
}
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is not None
|
||||
assert current_model.lifecycle == "active"
|
||||
entry.runtime_data.client.models.retrieve.assert_not_called()
|
||||
|
||||
result = await process_repair_fix_flow(
|
||||
client, flow_id, json={CONF_CHAT_MODEL: "claude-sonnet-5-5"}
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "claude-sonnet-5-5"
|
||||
}
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is None
|
||||
|
||||
|
||||
async def test_repair_flow_model_list_pagination(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
) -> None:
|
||||
"""Find replacement models beyond the first API response page."""
|
||||
entry = _make_entry(
|
||||
hass,
|
||||
title="Claude",
|
||||
api_key="key",
|
||||
subentries_data=[
|
||||
{
|
||||
"data": {CONF_CHAT_MODEL: "claude-3-5-haiku-20241022"},
|
||||
"subentry_type": "conversation",
|
||||
"title": "Conversation",
|
||||
"unique_id": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
entry.runtime_data.client.models.list.return_value = AsyncPage(
|
||||
data=[_copy_model_info("claude-sonnet-5-5")], has_more=True
|
||||
)
|
||||
second_page = AsyncPage(data=[_copy_model_info("claude-haiku-5-5")], has_more=False)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
with (
|
||||
patch.object(AsyncPage, "has_next_page", side_effect=[True, False]),
|
||||
patch.object(AsyncPage, "get_next_page", return_value=second_page) as next_page,
|
||||
):
|
||||
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
model_field = next(
|
||||
field for field in result["data_schema"] if field["name"] == CONF_CHAT_MODEL
|
||||
)
|
||||
assert model_field["default"] == "claude-haiku-5-5"
|
||||
next_page.assert_awaited_once()
|
||||
|
||||
result = await process_repair_fix_flow(
|
||||
client,
|
||||
result["flow_id"],
|
||||
json={CONF_CHAT_MODEL: "claude-haiku-5-5"},
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
entry.runtime_data.client.models.list.assert_awaited_once_with(timeout=10.0)
|
||||
entry.runtime_data.client.models.retrieve.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"lifecycle",
|
||||
[
|
||||
pytest.param("deprecated", id="deprecated_replacement"),
|
||||
pytest.param("retired", id="retired_replacement"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"current_lifecycle",
|
||||
[
|
||||
pytest.param("deprecated", id="deprecated_target"),
|
||||
pytest.param("retired", id="retired_target"),
|
||||
],
|
||||
)
|
||||
async def test_repair_flow_inactive_custom_model(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
lifecycle: str,
|
||||
current_lifecycle: str,
|
||||
) -> None:
|
||||
"""Keep the current repair available when a custom replacement is inactive."""
|
||||
entry = _make_entry(
|
||||
hass,
|
||||
title="Claude",
|
||||
api_key="key",
|
||||
subentries_data=[
|
||||
{
|
||||
"data": {CONF_CHAT_MODEL: "claude-3-5-haiku-20241022"},
|
||||
"subentry_type": "conversation",
|
||||
"title": "Conversation",
|
||||
"unique_id": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
entry.runtime_data.data = [
|
||||
DEPRECATED_MODEL_LIST[0].model_copy(update={"lifecycle": current_lifecycle})
|
||||
]
|
||||
inactive_model = _copy_model_info("claude-haiku-5-5").model_copy(
|
||||
update={"id": "custom-model", "lifecycle": lifecycle}
|
||||
)
|
||||
active_model = inactive_model.model_copy(update={"lifecycle": "active"})
|
||||
retrieve = entry.runtime_data.client.models.retrieve = AsyncMock(
|
||||
side_effect=[inactive_model, active_model]
|
||||
)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
|
||||
flow_id = result["flow_id"]
|
||||
step_id = result["step_id"]
|
||||
placeholders = result["description_placeholders"]
|
||||
result = await process_repair_fix_flow(
|
||||
client, flow_id, json={CONF_CHAT_MODEL: "custom-model"}
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["flow_id"] == flow_id
|
||||
assert result["step_id"] == step_id
|
||||
assert result["errors"] == {CONF_CHAT_MODEL: "model_not_active"}
|
||||
assert result["description_placeholders"] == placeholders
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "claude-3-5-haiku-20241022"
|
||||
}
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is not None
|
||||
retrieve.assert_awaited_once_with("custom-model", timeout=10.0)
|
||||
|
||||
result = await process_repair_fix_flow(
|
||||
client, flow_id, json={CONF_CHAT_MODEL: "custom-model"}
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "custom-model"
|
||||
}
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is None
|
||||
assert retrieve.await_args_list == [call("custom-model", timeout=10.0)] * 2
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2026-10-16T12:00:00Z")
|
||||
@pytest.mark.parametrize(
|
||||
("sdk_key", "submitted_model", "retirement_date"),
|
||||
[
|
||||
pytest.param(
|
||||
"custom-model",
|
||||
"custom-model",
|
||||
"November 30th, 2026",
|
||||
id="deprecated_alias",
|
||||
),
|
||||
pytest.param(
|
||||
"custom-model-20260101",
|
||||
"custom-model-20260101",
|
||||
"October 15th, 2026",
|
||||
id="retired_version",
|
||||
),
|
||||
pytest.param(
|
||||
"custom-model",
|
||||
"custom-model-20260101",
|
||||
"November 30th, 2026",
|
||||
id="deprecated_alias_dated_submission",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_repair_flow_sdk_inactive_custom_model(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
sdk_key: str,
|
||||
submitted_model: str,
|
||||
retirement_date: str,
|
||||
) -> None:
|
||||
"""Reject directly retrieved active API models deprecated or retired in the SDK."""
|
||||
entry = _make_entry(
|
||||
hass,
|
||||
title="Claude",
|
||||
api_key="key",
|
||||
subentries_data=[
|
||||
{
|
||||
"data": {CONF_CHAT_MODEL: "claude-3-5-haiku-20241022"},
|
||||
"subentry_type": "conversation",
|
||||
"title": "Conversation",
|
||||
"unique_id": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
custom_model = _copy_model_info("claude-haiku-5-5").model_copy(
|
||||
update={"id": "custom-model-20260101"}
|
||||
)
|
||||
retrieve = entry.runtime_data.client.models.retrieve = AsyncMock(
|
||||
return_value=custom_model
|
||||
)
|
||||
await _setup_repairs(hass)
|
||||
client = await hass_client()
|
||||
|
||||
with patch.dict(
|
||||
"homeassistant.components.anthropic.coordinator.DEPRECATED_MODELS",
|
||||
{sdk_key: retirement_date},
|
||||
clear=True,
|
||||
):
|
||||
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
|
||||
flow_id = result["flow_id"]
|
||||
placeholders = result["description_placeholders"]
|
||||
result = await process_repair_fix_flow(
|
||||
client, flow_id, json={CONF_CHAT_MODEL: submitted_model}
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["flow_id"] == flow_id
|
||||
assert result["errors"] == {CONF_CHAT_MODEL: "model_not_active"}
|
||||
assert result["description_placeholders"] == placeholders
|
||||
assert _get_subentry(entry, "conversation").data == {
|
||||
CONF_CHAT_MODEL: "claude-3-5-haiku-20241022"
|
||||
}
|
||||
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is not None
|
||||
assert custom_model.lifecycle == "active"
|
||||
retrieve.assert_awaited_once_with(submitted_model, timeout=10.0)
|
||||
|
||||
Reference in New Issue
Block a user