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

227 lines
8.1 KiB
Python
Raw Normal View History

2024-11-19 14:35:45 +03:00
"""The HA Text AI integration."""
2024-11-18 00:43:28 +03:00
import logging
2024-11-19 18:53:51 +03:00
from typing import Any, Dict, Optional
2024-11-14 18:32:41 +03:00
2024-11-18 00:43:28 +03:00
from homeassistant.config_entries import ConfigEntry
2024-11-19 12:45:26 +03:00
from homeassistant.const import CONF_API_KEY
2024-11-19 18:53:51 +03:00
from homeassistant.core import HomeAssistant, ServiceCall, callback
2024-11-19 14:35:45 +03:00
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client
2024-11-19 16:25:44 +03:00
from homeassistant.helpers import config_validation as cv
2024-11-14 18:32:41 +03:00
2024-11-19 18:53:51 +03:00
from .coordinator import HATextAICoordinator
2024-11-19 17:48:00 +03:00
2024-11-19 16:25:44 +03:00
from .const import (
DOMAIN,
PLATFORMS,
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-14 18:32:41 +03:00
2024-11-18 00:43:28 +03:00
_LOGGER = logging.getLogger(__name__)
2024-11-14 18:32:41 +03:00
2024-11-19 16:25:44 +03:00
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
2024-11-18 11:35:23 +03:00
async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool:
2024-11-19 14:35:45 +03:00
"""Set up the HA Text AI component."""
2024-11-18 00:43:28 +03:00
hass.data.setdefault(DOMAIN, {})
return True
2024-11-18 11:35:23 +03:00
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
2024-11-19 14:35:45 +03:00
"""Set up HA Text AI from a config entry."""
2024-11-18 11:35:23 +03:00
try:
2024-11-19 14:35:45 +03:00
session = aiohttp_client.async_get_clientsession(hass)
2024-11-18 11:35:23 +03:00
coordinator = HATextAICoordinator(
hass,
api_key=entry.data[CONF_API_KEY],
2024-11-19 16:25:44 +03:00
endpoint=entry.data.get(CONF_API_ENDPOINT, DEFAULT_API_ENDPOINT),
model=entry.data.get(CONF_MODEL, DEFAULT_MODEL),
temperature=entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
max_tokens=entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
request_interval=entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL),
2024-11-19 14:35:45 +03:00
session=session,
2024-11-18 11:35:23 +03:00
)
2024-11-19 14:35:45 +03:00
try:
await coordinator.async_config_entry_first_refresh()
except Exception as refresh_ex:
_LOGGER.error("Failed to refresh coordinator: %s", str(refresh_ex))
2024-11-19 18:53:51 +03:00
raise ConfigEntryNotReady from refresh_ex
2024-11-19 14:35:45 +03:00
if not coordinator.last_update_success:
2024-11-19 18:53:51 +03:00
raise ConfigEntryNotReady("Failed to communicate with OpenAI API")
2024-11-19 14:35:45 +03:00
2024-11-18 11:35:23 +03:00
hass.data[DOMAIN][entry.entry_id] = coordinator
2024-11-19 18:53:51 +03:00
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
async def async_ask_question(call: ServiceCall) -> None:
"""Handle the ask_question service call."""
question = call.data.get("question", "")
if not question:
_LOGGER.error("No question provided in service call")
return
# Собираем все опциональные параметры
request_params = {}
# Обработка system_prompt
system_prompt = call.data.get("system_prompt")
if system_prompt is not None:
request_params["system_prompt"] = system_prompt
# Обработка model
model = call.data.get("model")
if model is not None:
request_params["model"] = model
# Обработка temperature
temperature = call.data.get("temperature")
if temperature is not None:
try:
request_params["temperature"] = float(temperature)
except ValueError:
_LOGGER.error("Invalid temperature value: %s", temperature)
return
# Обработка max_tokens
max_tokens = call.data.get("max_tokens")
if max_tokens is not None:
try:
request_params["max_tokens"] = int(max_tokens)
except ValueError:
_LOGGER.error("Invalid max_tokens value: %s", max_tokens)
return
try:
await coordinator.async_ask_question(question, **request_params)
except Exception as err:
_LOGGER.error("Error asking question: %s", str(err))
async def async_clear_history(call: ServiceCall) -> None:
"""Handle the clear_history service call."""
try:
coordinator._responses.clear()
await coordinator.async_refresh()
_LOGGER.info("History cleared successfully")
except Exception as err:
_LOGGER.error("Error clearing history: %s", str(err))
async def async_get_history(call: ServiceCall) -> dict:
"""Handle the get_history service call."""
try:
limit = call.data.get("limit", 10)
filter_model = call.data.get("filter_model", "")
responses = coordinator._responses
# Применяем фильтрацию по модели
if filter_model:
filtered_responses = {
k: v for k, v in responses.items()
if v.get("model") == filter_model
}
else:
filtered_responses = responses.copy()
# Сортируем по времени и ограничиваем количество
sorted_responses = dict(
sorted(
filtered_responses.items(),
key=lambda x: x[1]["timestamp"],
reverse=True
)[:limit]
)
return sorted_responses
except Exception as err:
_LOGGER.error("Error getting history: %s", str(err))
return {}
async def async_set_system_prompt(call: ServiceCall) -> None:
"""Handle the set_system_prompt service call."""
prompt = call.data.get("prompt", "")
if prompt:
try:
coordinator.system_prompt = prompt
_LOGGER.info("System prompt updated successfully")
except Exception as err:
_LOGGER.error("Error setting system prompt: %s", str(err))
else:
_LOGGER.error("No prompt provided in service call")
# Регистрация сервисов
hass.services.async_register(
DOMAIN,
"ask_question",
async_ask_question
)
hass.services.async_register(
DOMAIN,
"clear_history",
async_clear_history
)
hass.services.async_register(
DOMAIN,
"get_history",
async_get_history
)
hass.services.async_register(
DOMAIN,
"set_system_prompt",
async_set_system_prompt
)
2024-11-19 14:35:45 +03:00
_LOGGER.info(
"Successfully set up HA Text AI with model: %s",
2024-11-19 16:25:44 +03:00
entry.data.get(CONF_MODEL, DEFAULT_MODEL)
2024-11-19 14:35:45 +03:00
)
return True
2024-11-18 11:35:23 +03:00
except Exception as ex:
2024-11-19 14:35:45 +03:00
_LOGGER.exception("Unexpected error setting up entry: %s", str(ex))
2024-11-19 18:53:51 +03:00
raise ConfigEntryNotReady from ex
2024-11-18 11:35:23 +03:00
2024-11-18 00:43:28 +03:00
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
2024-11-19 14:35:45 +03:00
try:
if entry.entry_id not in hass.data.get(DOMAIN, {}):
return True
2024-11-19 14:00:33 +03:00
2024-11-19 18:53:51 +03:00
# Удаляем все сервисы при выгрузке интеграции
services = ["ask_question", "clear_history", "get_history", "set_system_prompt"]
for service in services:
hass.services.async_remove(DOMAIN, service)
2024-11-19 14:35:45 +03:00
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
coordinator = hass.data[DOMAIN].pop(entry.entry_id)
await coordinator.async_shutdown()
2024-11-18 00:43:28 +03:00
2024-11-19 14:35:45 +03:00
return unload_ok
2024-11-18 11:35:23 +03:00
2024-11-19 14:35:45 +03:00
except Exception as ex:
_LOGGER.exception("Error unloading entry: %s", str(ex))
return False
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
try:
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
except Exception as ex:
2024-11-19 18:53:51 +03:00
_LOGGER.exception("Error reloading entry: %s", str(ex)) # убрано лишнее двоеточие