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

213 lines
8.1 KiB
Python
Raw Normal View History

2024-11-18 00:43:28 +03:00
"""Config flow for HA text AI integration."""
2024-11-22 01:34:47 +03:00
from typing import Any, Dict, Optional
2024-11-18 00:43:28 +03:00
import voluptuous as vol
2024-11-19 23:38:07 +03:00
import aiohttp
2024-11-19 12:45:26 +03:00
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
import logging
_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-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 00:36:58 +03:00
return self._show_provider_config(user_input["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-22 01:34:47 +03:00
def _show_provider_selection(self):
"""Show provider selection screen."""
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required("provider"): vol.In(API_PROVIDERS)
}),
description_placeholders={"providers": ", ".join(API_PROVIDERS)}
)
2024-11-21 18:55:11 +03:00
2024-11-22 01:34:47 +03:00
def _show_provider_config(self, provider):
"""Show configuration screen for selected provider."""
default_endpoint = DEFAULT_OPENAI_ENDPOINT if provider == API_PROVIDER_OPENAI else DEFAULT_ANTHROPIC_ENDPOINT
2024-11-14 18:34:38 +03:00
2024-11-23 00:36:58 +03:00
default_name = f"HA Text AI {len(self._async_current_entries()) + 1}"
2024-11-18 00:43:28 +03:00
return self.async_show_form(
step_id="user",
2024-11-22 01:34:47 +03:00
data_schema=vol.Schema({
2024-11-23 00:36:58 +03:00
vol.Required("name", default=default_name): str,
2024-11-22 01:34:47 +03:00
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)
),
}),
description_placeholders={"provider": provider}
2024-11-18 00:43:28 +03:00
)
2024-11-14 18:34:38 +03:00
2024-11-23 00:51:57 +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 00:51:57 +03:00
try:
# Генерируем уникальный идентификатор один раз
unique_id = f"{user_input[CONF_API_KEY]}_{user_input[CONF_MODEL]}"
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 00:51:57 +03:00
session = async_get_clientsession(self.hass)
2024-11-22 01:34:47 +03:00
2024-11-23 00:51:57 +03:00
# Minimal API key validation
headers = {
"Authorization": f"Bearer {user_input[CONF_API_KEY]}",
"Content-Type": "application/json"
}
# Adjust headers and endpoint based on provider
if user_input[CONF_API_PROVIDER] == API_PROVIDER_ANTHROPIC:
2024-11-22 01:34:47 +03:00
headers = {
2024-11-23 00:51:57 +03:00
"x-api-key": user_input[CONF_API_KEY],
"anthropic-version": "2023-06-01"
2024-11-22 01:34:47 +03:00
}
2024-11-23 00:51:57 +03:00
# Basic connection test
2024-11-23 00:36:58 +03:00
try:
2024-11-23 00:51:57 +03:00
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"
2024-11-23 00:36:58 +03:00
except Exception as e:
2024-11-23 00:51:57 +03:00
_LOGGER.error(f"Connection test failed: {e}")
errors["base"] = "cannot_connect"
2024-11-22 12:02:26 +03:00
2024-11-23 00:51:57 +03:00
if not errors:
return self.async_create_entry(
title=user_input.get("name", f"HA Text AI ({user_input[CONF_API_PROVIDER]})"),
data=user_input
)
except Exception as e:
_LOGGER.error(f"Unexpected error: {e}")
errors["base"] = "unknown"
# Return to provider config, preserving previous input
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)
),
}),
description_placeholders={"provider": user_input[CONF_API_PROVIDER]},
errors=errors
)
2024-11-22 01:34:47 +03:00
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
"""Create the options flow."""
return OptionsFlowHandler(config_entry)
2024-11-21 18:30:35 +03:00
2024-11-18 00:43:28 +03:00
class OptionsFlowHandler(config_entries.OptionsFlow):
2024-11-22 01:34:47 +03:00
"""Options flow handler."""
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
)