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

339 lines
12 KiB
Python
Raw Normal View History

2024-11-18 00:43:28 +03:00
"""Config flow for HA text AI integration."""
2024-11-19 14:35:45 +03:00
from typing import Any, Dict, Optional, Tuple
2024-11-18 00:43:28 +03:00
import voluptuous as vol
2024-11-19 14:35:45 +03:00
import asyncio
2024-11-19 23:38:07 +03:00
import aiohttp
2024-11-19 14:35:45 +03:00
from async_timeout import timeout
2024-11-20 01:02:27 +03:00
from urllib.parse import urlparse, urljoin
2024-11-19 12:45:26 +03:00
2024-11-18 00:43:28 +03:00
from homeassistant import config_entries
2024-11-19 12:45:26 +03:00
from homeassistant.const import CONF_API_KEY
2024-11-18 00:43:28 +03:00
import homeassistant.helpers.config_validation as cv
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,
DEFAULT_MODEL,
DEFAULT_TEMPERATURE,
DEFAULT_MAX_TOKENS,
DEFAULT_API_ENDPOINT,
DEFAULT_REQUEST_INTERVAL,
2024-11-20 01:02:27 +03:00
MIN_TEMPERATURE,
MAX_TEMPERATURE,
MIN_MAX_TOKENS,
MAX_MAX_TOKENS,
MIN_REQUEST_INTERVAL,
API_VERSION,
API_MODELS_PATH,
ERROR_INVALID_API_KEY,
ERROR_CANNOT_CONNECT,
ERROR_UNKNOWN,
ERROR_INVALID_MODEL,
ERROR_RATE_LIMIT,
ERROR_API_ERROR,
ERROR_TIMEOUT,
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-21 18:24:39 +03:00
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_MODEL, default=DEFAULT_MODEL): cv.string,
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_API_ENDPOINT, default=DEFAULT_API_ENDPOINT): vol.All(
cv.string,
vol.Match(r'^https?://.+', msg="Must be a valid HTTP(S) URL")
),
vol.Optional(CONF_REQUEST_INTERVAL, default=DEFAULT_REQUEST_INTERVAL): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_REQUEST_INTERVAL)
)
}
)
2024-11-19 12:45:26 +03:00
2024-11-19 14:35:45 +03:00
async def validate_api_connection(
2024-11-19 23:21:54 +03:00
hass,
2024-11-19 14:35:45 +03:00
api_key: str,
endpoint: str,
model: str,
retry_count: int = 3,
retry_delay: float = 1.0
) -> Tuple[bool, str, list]:
2024-11-19 17:33:27 +03:00
"""Validate API connection with retry logic."""
2024-11-19 23:38:07 +03:00
session = async_get_clientsession(hass)
2024-11-20 12:07:30 +03:00
# Determine API type and configure headers
2024-11-19 23:38:07 +03:00
headers = {
2024-11-20 12:07:30 +03:00
"Content-Type": "application/json",
"Accept": "application/json"
2024-11-19 23:38:07 +03:00
}
2024-11-20 12:07:30 +03:00
# Configure endpoint and headers based on service type
if "vsegpt" in endpoint.lower():
headers["Authorization"] = f"Bearer {api_key}"
base_url = endpoint.rstrip('/')
2024-11-20 12:23:26 +03:00
if not base_url.endswith("/v1"):
base_url = f"{base_url}/v1"
models_url = f"{base_url}/models" # Using the correct v1/models endpoint
2024-11-20 12:07:30 +03:00
_LOGGER.debug("Using VSE GPT endpoint: %s", models_url)
2024-11-20 12:23:26 +03:00
# For VSE GPT, we might want to validate the model differently
supported_models = [
"anthropic/claude-3-5-haiku",
"anthropic/claude-3.5-sonnet",
# Add other supported VSE GPT models here
]
if model in supported_models:
return True, "", supported_models
2024-11-20 12:07:30 +03:00
elif any(m in model.lower() for m in ["claude", "anthropic"]):
headers["x-api-key"] = api_key
headers["anthropic-version"] = "2023-06-01"
base_url = endpoint.rstrip('/')
if not base_url.endswith("/v1"):
base_url = f"{base_url}/v1"
models_url = f"{base_url}/models"
_LOGGER.debug("Using Anthropic endpoint: %s", models_url)
else:
headers["Authorization"] = f"Bearer {api_key}"
base_url = endpoint.rstrip('/')
if not base_url.endswith(f"/{API_VERSION}"):
base_url = f"{base_url}/{API_VERSION}"
models_url = f"{base_url}/{API_MODELS_PATH}"
_LOGGER.debug("Using OpenAI endpoint: %s", models_url)
2024-11-19 23:38:07 +03:00
2024-11-19 17:33:27 +03:00
for attempt in range(retry_count):
try:
async with timeout(10):
2024-11-20 12:23:26 +03:00
# For VSE GPT, we'll skip the actual models endpoint check
if "vsegpt" in endpoint.lower():
# Instead, let's verify the API key with a simple request
test_url = f"{base_url}/models"
async with session.get(test_url, headers=headers) as response:
if response.status == 404:
# This is actually expected for VSE GPT
if model.startswith("anthropic/"):
return True, "", [model]
elif response.status == 401:
return False, ERROR_INVALID_API_KEY, []
elif response.status == 429:
return False, ERROR_RATE_LIMIT, []
return True, "", [model]
# For other APIs, proceed with normal validation
2024-11-19 23:38:07 +03:00
async with session.get(models_url, headers=headers) as response:
2024-11-20 12:07:30 +03:00
_LOGGER.debug("API response status: %s", response.status)
2024-11-19 23:38:07 +03:00
if response.status == 200:
data = await response.json()
2024-11-19 14:35:45 +03:00
2024-11-20 12:23:26 +03:00
if any(m in model.lower() for m in ["claude", "anthropic"]):
2024-11-20 12:07:30 +03:00
model_ids = [m["id"] for m in data.get("models", [])]
if model.startswith("anthropic/"):
model = model.split("/")[1]
if model in model_ids or any(m.endswith(model) for m in model_ids):
return True, "", model_ids
else: # OpenAI format
model_ids = [m["id"] for m in data.get("data", [])]
if model in model_ids:
return True, "", model_ids
_LOGGER.warning(
"Model %s not found in available models: %s",
model,
", ".join(model_ids)
)
return False, ERROR_INVALID_MODEL, model_ids
2024-11-19 23:38:07 +03:00
elif response.status == 401:
_LOGGER.error("Authentication failed")
2024-11-20 01:02:27 +03:00
return False, ERROR_INVALID_API_KEY, []
2024-11-19 23:38:07 +03:00
elif response.status == 429:
_LOGGER.error("Rate limit exceeded")
2024-11-20 12:07:30 +03:00
if attempt < retry_count - 1:
await asyncio.sleep(retry_delay * (2 ** attempt))
continue
2024-11-20 01:02:27 +03:00
return False, ERROR_RATE_LIMIT, []
2024-11-19 23:38:07 +03:00
else:
2024-11-20 01:02:27 +03:00
response_text = await response.text()
2024-11-19 23:38:07 +03:00
_LOGGER.error(
"API error: %s - %s",
response.status,
2024-11-20 01:02:27 +03:00
response_text
2024-11-19 23:38:07 +03:00
)
2024-11-20 12:07:30 +03:00
if attempt < retry_count - 1:
await asyncio.sleep(retry_delay)
continue
2024-11-20 01:02:27 +03:00
return False, ERROR_API_ERROR, []
2024-11-19 14:35:45 +03:00
2024-11-19 17:33:27 +03:00
except asyncio.TimeoutError:
_LOGGER.warning(
"Timeout during API validation (attempt %d/%d)",
attempt + 1,
retry_count
)
2024-11-20 12:07:30 +03:00
if attempt < retry_count - 1:
await asyncio.sleep(retry_delay)
continue
return False, ERROR_TIMEOUT, []
2024-11-19 14:35:45 +03:00
2024-11-19 23:38:07 +03:00
except aiohttp.ClientError as err:
_LOGGER.error("Connection error: %s", str(err))
2024-11-20 01:02:27 +03:00
return False, ERROR_CANNOT_CONNECT, []
2024-11-19 17:33:27 +03:00
except Exception as err:
_LOGGER.exception("Unexpected error during validation: %s", str(err))
2024-11-20 01:02:27 +03:00
return False, ERROR_UNKNOWN, []
2024-11-19 14:35:45 +03:00
2024-11-20 01:02:27 +03:00
return False, ERROR_UNKNOWN, []
2024-11-19 23:38:07 +03:00
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-19 12:45:26 +03:00
async def async_step_user(
self,
user_input: Optional[Dict[str, Any]] = None
2024-11-19 23:30:28 +03:00
) -> FlowResult:
2024-11-18 00:43:28 +03:00
"""Handle the initial step."""
2024-11-19 12:45:26 +03:00
errors: Dict[str, str] = {}
2024-11-14 18:34:38 +03:00
2024-11-18 00:43:28 +03:00
if user_input is not None:
2024-11-19 12:45:26 +03:00
try:
2024-11-19 15:10:06 +03:00
endpoint = user_input.get(CONF_API_ENDPOINT, DEFAULT_API_ENDPOINT)
try:
result = urlparse(endpoint)
if not all([result.scheme, result.netloc]):
errors["base"] = "invalid_url_format"
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors
)
except Exception as e:
_LOGGER.error("URL parsing error: %s", str(e))
errors["base"] = "invalid_url_format"
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors
)
2024-11-19 23:30:28 +03:00
validated_input = STEP_USER_DATA_SCHEMA(user_input)
2024-11-19 14:35:45 +03:00
is_valid, error_code, available_models = await validate_api_connection(
2024-11-19 23:21:54 +03:00
self.hass,
2024-11-19 23:30:28 +03:00
validated_input[CONF_API_KEY],
2024-11-19 15:10:06 +03:00
endpoint,
2024-11-19 23:30:28 +03:00
validated_input[CONF_MODEL]
2024-11-19 12:45:26 +03:00
)
2024-11-19 14:35:45 +03:00
if is_valid:
2024-11-19 23:30:28 +03:00
await self.async_set_unique_id(validated_input[CONF_API_KEY])
2024-11-19 14:00:33 +03:00
self._abort_if_unique_id_configured()
2024-11-19 12:45:26 +03:00
2024-11-19 14:00:33 +03:00
return self.async_create_entry(
2024-11-19 23:30:28 +03:00
title="HA Text AI",
data=validated_input
2024-11-19 14:00:33 +03:00
)
2024-11-19 12:45:26 +03:00
2024-11-19 14:35:45 +03:00
errors["base"] = error_code
2024-11-20 01:02:27 +03:00
if error_code == ERROR_INVALID_MODEL:
2024-11-19 14:35:45 +03:00
_LOGGER.warning(
"Selected model %s not found in available models: %s",
2024-11-19 23:30:28 +03:00
validated_input[CONF_MODEL],
2024-11-19 14:35:45 +03:00
", ".join(available_models)
)
except vol.Invalid as err:
_LOGGER.error("Validation error: %s", str(err))
errors["base"] = "invalid_input"
2024-11-14 18:34:38 +03:00
2024-11-18 00:43:28 +03:00
return self.async_show_form(
step_id="user",
2024-11-19 12:45:26 +03:00
data_schema=STEP_USER_DATA_SCHEMA,
2024-11-18 00:43:28 +03:00
errors=errors,
2024-11-19 14:00:33 +03:00
description_placeholders={
"default_model": DEFAULT_MODEL,
"default_endpoint": DEFAULT_API_ENDPOINT,
}
2024-11-18 00:43:28 +03:00
)
2024-11-14 18:34:38 +03:00
2024-11-18 00:43:28 +03:00
@staticmethod
@callback
2024-11-19 12:45:26 +03:00
def async_get_options_flow(
config_entry: config_entries.ConfigEntry,
) -> config_entries.OptionsFlow:
2024-11-18 00:43:28 +03:00
"""Get the options flow for this handler."""
return OptionsFlowHandler(config_entry)
2024-11-14 18:34:38 +03:00
2024-11-18 00:43:28 +03:00
class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle options flow for HA text AI."""
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-19 12:45:26 +03:00
async def async_step_init(
self,
user_input: Optional[Dict[str, Any]] = None
2024-11-19 23:30:28 +03:00
) -> FlowResult:
2024-11-18 00:43:28 +03:00
"""Handle options flow."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
2024-11-14 18:34:38 +03:00
2024-11-19 12:45:26 +03:00
options_schema = vol.Schema({
vol.Optional(
CONF_TEMPERATURE,
default=self.config_entry.options.get(
CONF_TEMPERATURE, DEFAULT_TEMPERATURE
),
2024-11-19 14:35:45 +03:00
): vol.All(
vol.Coerce(float),
2024-11-20 01:02:27 +03:00
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
2024-11-19 14:35:45 +03:00
),
2024-11-19 12:45:26 +03:00
vol.Optional(
CONF_MAX_TOKENS,
default=self.config_entry.options.get(
CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS
),
2024-11-19 14:35:45 +03:00
): vol.All(
vol.Coerce(int),
2024-11-20 01:02:27 +03:00
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
2024-11-19 14:35:45 +03:00
),
2024-11-19 12:45:26 +03:00
vol.Optional(
CONF_REQUEST_INTERVAL,
default=self.config_entry.options.get(
CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL
),
2024-11-19 14:35:45 +03:00
): vol.All(
vol.Coerce(float),
2024-11-20 01:02:27 +03:00
vol.Range(min=MIN_REQUEST_INTERVAL)
2024-11-19 14:35:45 +03:00
),
2024-11-19 12:45:26 +03:00
})
2024-11-18 00:43:28 +03:00
return self.async_show_form(
step_id="init",
2024-11-19 12:45:26 +03:00
data_schema=options_schema,
2024-11-18 00:43:28 +03:00
)