Release v2.0.0

This commit is contained in:
SMKRV
2024-11-23 00:36:58 +03:00
parent 13a9e1a5d7
commit d870cfbba6
6 changed files with 80 additions and 53 deletions
+27 -27
View File
@@ -4,7 +4,7 @@ import voluptuous as vol
import aiohttp
from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY, CONF_NAME
from homeassistant.const import CONF_API_KEY
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession
@@ -41,18 +41,13 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
def __init__(self):
"""Initialize the config flow."""
self._provider = None
async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
"""Handle the initial step."""
if user_input is None:
return self._show_provider_selection()
if "provider" in user_input:
self._provider = user_input["provider"]
return self._show_provider_config(self._provider)
return self._show_provider_config(user_input["provider"])
return await self._process_configuration(user_input)
@@ -70,10 +65,12 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Show configuration screen for selected provider."""
default_endpoint = DEFAULT_OPENAI_ENDPOINT if provider == API_PROVIDER_OPENAI else DEFAULT_ANTHROPIC_ENDPOINT
default_name = f"HA Text AI {len(self._async_current_entries()) + 1}"
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required(CONF_NAME): str, # Добавлено поле имени
vol.Required("name", default=default_name): str,
vol.Required(CONF_API_PROVIDER): vol.In([provider]),
vol.Required(CONF_API_KEY): str,
vol.Required(CONF_MODEL, default=DEFAULT_MODEL): str,
@@ -99,10 +96,8 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors = {}
try:
# Создаем уникальный идентификатор на основе имени и эндпоинта
unique_id = f"{user_input[CONF_NAME]}_{user_input[CONF_API_ENDPOINT]}"
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()
# Принудительная очистка существующих записей с тем же API-ключом
await self._async_cleanup_existing_entries(user_input[CONF_API_KEY])
session = async_get_clientsession(self.hass)
@@ -112,7 +107,7 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"Content-Type": "application/json"
}
# Adjust headers based on provider
# Adjust headers and endpoint based on provider
if user_input[CONF_API_PROVIDER] == API_PROVIDER_ANTHROPIC:
headers = {
"x-api-key": user_input[CONF_API_KEY],
@@ -132,8 +127,12 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors["base"] = "cannot_connect"
if not errors:
# Генерируем уникальный идентификатор на основе ключа
await self.async_set_unique_id(user_input[CONF_API_KEY])
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=user_input[CONF_NAME],
title=user_input.get("name", f"HA Text AI ({user_input[CONF_API_PROVIDER]})"), # Используем введенное имя
data=user_input
)
@@ -145,8 +144,9 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required("name", default=user_input.get("name", f"HA Text AI {len(self._async_current_entries()) + 1}")): str,
vol.Required(CONF_API_PROVIDER): vol.In([user_input[CONF_API_PROVIDER]]),
vol.Required(CONF_API_KEY, default=user_input.get(CONF_API_KEY, "")): str,
vol.Required(CONF_API_KEY): str,
vol.Required(CONF_MODEL, default=user_input.get(CONF_MODEL, DEFAULT_MODEL)): str,
vol.Optional(CONF_API_ENDPOINT, default=user_input.get(CONF_API_ENDPOINT,
DEFAULT_OPENAI_ENDPOINT if user_input[CONF_API_PROVIDER] == API_PROVIDER_OPENAI
@@ -168,19 +168,19 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors=errors
)
async def _async_cleanup_existing_entries(self, api_key):
"""Cleanup existing entries with the same API key."""
existing_entries = [
entry for entry in self.hass.config_entries.async_entries(DOMAIN)
if entry.data.get(CONF_API_KEY) == api_key
]
async def _async_cleanup_existing_entries(self, api_key):
"""Cleanup existing entries with the same API key."""
existing_entries = [
entry for entry in self.hass.config_entries.async_entries(DOMAIN)
if entry.data.get(CONF_API_KEY) == api_key
]
for entry in existing_entries:
try:
await self.hass.config_entries.async_remove(entry.entry_id)
_LOGGER.info(f"Removed existing entry with ID: {entry.entry_id}")
except Exception as e:
_LOGGER.warning(f"Could not remove existing entry: {e}")
for entry in existing_entries:
try:
await self.hass.config_entries.async_remove(entry.entry_id)
_LOGGER.info(f"Removed existing entry with ID: {entry.entry_id}")
except Exception as e:
_LOGGER.warning(f"Could not remove existing entry: {e}")
@staticmethod
@callback