Files
ha-text-ai/custom_components/ha_text_ai/config_flow.py
T

225 lines
8.7 KiB
Python
Raw Normal View History

2024-11-18 00:43:28 +03:00
"""Config flow for HA text AI integration."""
2024-11-23 23:42:33 +03:00
import logging
2024-11-22 01:34:47 +03:00
from typing import Any, Dict, Optional
2024-11-19 12:45:26 +03:00
2024-11-23 23:42:33 +03:00
import voluptuous as vol
2024-11-18 00:43:28 +03:00
from homeassistant import config_entries
2024-11-23 00:36:58 +03:00
from homeassistant.const import CONF_API_KEY
2024-11-18 00:43:28 +03:00
from homeassistant.core import callback
2024-11-19 23:30:28 +03:00
from homeassistant.data_entry_flow import FlowResult
2024-11-19 23:38:07 +03:00
from homeassistant.helpers.aiohttp_client import async_get_clientsession
2024-11-14 18:34:38 +03:00
2024-11-18 00:43:28 +03:00
from .const import (
DOMAIN,
CONF_MODEL,
CONF_TEMPERATURE,
CONF_MAX_TOKENS,
CONF_API_ENDPOINT,
CONF_REQUEST_INTERVAL,
2024-11-22 01:34:47 +03:00
CONF_API_PROVIDER,
API_PROVIDER_OPENAI,
API_PROVIDER_ANTHROPIC,
API_PROVIDERS,
2024-11-18 00:43:28 +03:00
DEFAULT_MODEL,
DEFAULT_TEMPERATURE,
DEFAULT_MAX_TOKENS,
DEFAULT_REQUEST_INTERVAL,
2024-11-22 01:34:47 +03:00
DEFAULT_OPENAI_ENDPOINT,
DEFAULT_ANTHROPIC_ENDPOINT,
2024-11-20 01:02:27 +03:00
MIN_TEMPERATURE,
MAX_TEMPERATURE,
MIN_MAX_TOKENS,
MAX_MAX_TOKENS,
MIN_REQUEST_INTERVAL,
2024-11-18 00:43:28 +03:00
)
2024-11-14 18:34:38 +03:00
2024-11-19 14:00:33 +03:00
_LOGGER = logging.getLogger(__name__)
2024-11-19 12:45:26 +03:00
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
2024-11-18 00:43:28 +03:00
"""Handle a config flow for HA text AI."""
2024-11-14 18:34:38 +03:00
2024-11-18 00:43:28 +03:00
VERSION = 1
2024-11-14 18:34:38 +03:00
2024-11-23 02:21:10 +03:00
def __init__(self) -> None:
"""Initialize flow."""
super().__init__()
self.provider = None
2024-11-23 03:02:35 +03:00
def _show_provider_selection(self) -> FlowResult:
"""Show the provider selection form."""
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required("provider"): vol.In(API_PROVIDERS),
}),
)
def _show_provider_config(self, provider: str) -> FlowResult:
"""Show the configuration form for the selected provider."""
default_endpoint = (
DEFAULT_OPENAI_ENDPOINT if provider == API_PROVIDER_OPENAI
else DEFAULT_ANTHROPIC_ENDPOINT
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required("name", default=f"HA Text AI {len(self._async_current_entries()) + 1}"): str,
vol.Required(CONF_API_PROVIDER): vol.In([provider]),
vol.Required(CONF_API_KEY): str,
vol.Required(CONF_MODEL, default=DEFAULT_MODEL): str,
vol.Optional(CONF_API_ENDPOINT, default=default_endpoint): str,
vol.Optional(CONF_TEMPERATURE, default=DEFAULT_TEMPERATURE): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
),
vol.Optional(CONF_MAX_TOKENS, default=DEFAULT_MAX_TOKENS): vol.All(
vol.Coerce(int),
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
),
vol.Optional(CONF_REQUEST_INTERVAL, default=DEFAULT_REQUEST_INTERVAL): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_REQUEST_INTERVAL)
),
})
)
2024-11-22 01:34:47 +03:00
async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
2024-11-18 00:43:28 +03:00
"""Handle the initial step."""
2024-11-22 01:34:47 +03:00
if user_input is None:
return self._show_provider_selection()
2024-11-14 18:34:38 +03:00
2024-11-22 01:34:47 +03:00
if "provider" in user_input:
2024-11-23 02:21:10 +03:00
self.provider = user_input["provider"]
return self._show_provider_config(self.provider)
2024-11-21 18:30:35 +03:00
2024-11-22 01:34:47 +03:00
return await self._process_configuration(user_input)
2024-11-19 15:10:06 +03:00
2024-11-23 01:09:38 +03:00
async def _process_configuration(self, user_input):
"""Validate and process user configuration."""
errors = {}
2024-11-14 18:34:38 +03:00
2024-11-23 01:09:38 +03:00
try:
2024-11-23 19:51:21 +03:00
# Создаем уникальный идентификатор, включающий имя экземпляра
instance_name = user_input.get("name", f"HA Text AI {len(self._async_current_entries()) + 1}")
unique_id = f"{DOMAIN}_{instance_name}_{user_input[CONF_API_PROVIDER]}"
# Нормализуем уникальный идентификатор
unique_id = unique_id.lower().replace(" ", "_")
2024-11-23 01:09:38 +03:00
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()
2024-11-22 12:02:26 +03:00
2024-11-23 02:21:10 +03:00
# Проверяем подключение к API
2024-11-23 01:09:38 +03:00
session = async_get_clientsession(self.hass)
2024-11-23 02:21:10 +03:00
headers = self._get_api_headers(user_input)
2024-11-23 01:09:38 +03:00
try:
async with session.get(
f"{user_input[CONF_API_ENDPOINT]}/models",
headers=headers
) as response:
if response.status not in [200, 404]:
errors["base"] = "cannot_connect"
except Exception as e:
_LOGGER.error(f"Connection test failed: {e}")
errors["base"] = "cannot_connect"
if not errors:
return self.async_create_entry(
2024-11-23 19:51:21 +03:00
title=instance_name,
2024-11-23 02:21:10 +03:00
data={
2024-11-23 19:51:21 +03:00
"name": instance_name,
**user_input,
"unique_id": unique_id # Сохраняем уникальный идентификатор в данных
2024-11-23 02:21:10 +03:00
}
2024-11-23 01:09:38 +03:00
)
2024-11-23 00:36:58 +03:00
except Exception as e:
2024-11-23 01:09:38 +03:00
_LOGGER.error(f"Unexpected error: {e}")
errors["base"] = "unknown"
2024-11-22 12:02:26 +03:00
2024-11-23 02:21:10 +03:00
return self._show_configuration_form(user_input, errors)
def _get_api_headers(self, user_input):
"""Get API headers based on provider."""
if user_input[CONF_API_PROVIDER] == API_PROVIDER_ANTHROPIC:
return {
"x-api-key": user_input[CONF_API_KEY],
"anthropic-version": "2023-06-01"
}
return {
"Authorization": f"Bearer {user_input[CONF_API_KEY]}",
"Content-Type": "application/json"
}
def _show_configuration_form(self, user_input, errors=None):
"""Show the configuration form to edit location data."""
2024-11-23 01:09:38 +03:00
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): 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
else DEFAULT_ANTHROPIC_ENDPOINT)): str,
vol.Optional(CONF_TEMPERATURE, default=user_input.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
),
vol.Optional(CONF_MAX_TOKENS, default=user_input.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)): vol.All(
vol.Coerce(int),
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
),
vol.Optional(CONF_REQUEST_INTERVAL, default=user_input.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_REQUEST_INTERVAL)
),
}),
2024-11-23 02:21:10 +03:00
errors=errors or {}
2024-11-23 01:09:38 +03:00
)
2024-11-23 00:51:57 +03:00
2024-11-23 03:02:35 +03:00
2024-11-18 00:43:28 +03:00
class OptionsFlowHandler(config_entries.OptionsFlow):
2024-11-23 02:21:10 +03:00
"""Handle options flow."""
2024-11-14 18:34:38 +03:00
2024-11-19 12:45:26 +03:00
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
2024-11-18 00:43:28 +03:00
"""Initialize options flow."""
self.config_entry = config_entry
2024-11-14 18:34:38 +03:00
2024-11-22 01:34:47 +03:00
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
"""Manage the options."""
2024-11-18 00:43:28 +03:00
if user_input is not None:
2024-11-22 01:34:47 +03:00
return self.async_create_entry(title="", data=user_input)
current_data = self.config_entry.data
2024-11-21 18:30:35 +03:00
return self.async_show_form(
step_id="init",
2024-11-22 01:34:47 +03:00
data_schema=vol.Schema({
vol.Optional(
CONF_TEMPERATURE,
default=current_data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
),
vol.Optional(
CONF_MAX_TOKENS,
default=current_data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
): vol.All(
vol.Coerce(int),
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
),
vol.Optional(
CONF_REQUEST_INTERVAL,
default=current_data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_REQUEST_INTERVAL)
),
})
2024-11-21 18:30:35 +03:00
)