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

285 lines
10 KiB
Python
Raw Normal View History

2024-11-21 14:55:27 +03:00
"""The HA Text AI integration."""
from __future__ import annotations
import logging
2024-11-23 03:02:35 +03:00
import os
import shutil
2024-11-24 02:32:08 +03:00
from datetime import datetime, timedelta
2024-11-24 17:27:49 +03:00
from typing import Any, Dict
2024-11-23 23:42:33 +03:00
import voluptuous as vol
from async_timeout import timeout
2024-11-21 14:55:27 +03:00
from homeassistant.config_entries import ConfigEntry
2024-11-24 03:03:01 +03:00
from homeassistant.const import CONF_API_KEY, CONF_NAME, Platform
2024-11-24 17:27:49 +03:00
from homeassistant.core import HomeAssistant, ServiceCall
2024-11-21 18:00:33 +03:00
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
2024-11-23 23:42:33 +03:00
from homeassistant.helpers import config_validation as cv
2024-11-21 14:55:27 +03:00
from homeassistant.helpers import aiohttp_client
from .coordinator import HATextAICoordinator
from .const import (
DOMAIN,
PLATFORMS,
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,
2024-11-21 14:55:27 +03:00
DEFAULT_MODEL,
DEFAULT_TEMPERATURE,
DEFAULT_MAX_TOKENS,
2024-11-22 01:34:47 +03:00
DEFAULT_OPENAI_ENDPOINT,
DEFAULT_ANTHROPIC_ENDPOINT,
2024-11-21 14:55:27 +03:00
DEFAULT_REQUEST_INTERVAL,
API_TIMEOUT,
2024-11-21 15:35:52 +03:00
SERVICE_ASK_QUESTION,
SERVICE_CLEAR_HISTORY,
2024-11-23 18:50:48 +03:00
SERVICE_GET_HISTORY,
2024-11-21 15:35:52 +03:00
SERVICE_SET_SYSTEM_PROMPT,
2024-11-21 14:55:27 +03:00
)
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
2024-11-24 02:20:29 +03:00
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
vol.Required("instance"): cv.string,
vol.Required("question"): cv.string,
vol.Optional("system_prompt"): cv.string,
vol.Optional("model"): cv.string,
vol.Optional("temperature"): cv.positive_float,
vol.Optional("max_tokens"): cv.positive_int,
})
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
vol.Required("instance"): cv.string,
vol.Required("prompt"): cv.string,
})
SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
vol.Required("instance"): cv.string,
vol.Optional("limit"): cv.positive_int,
vol.Optional("filter_model"): cv.string,
})
2024-11-21 18:00:33 +03:00
2024-11-21 14:55:27 +03:00
async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
"""Set up the HA Text AI component."""
hass.data.setdefault(DOMAIN, {})
2024-11-21 16:17:51 +03:00
2024-11-23 18:50:48 +03:00
try:
source = os.path.join(os.path.dirname(__file__), 'icons', 'icon.svg')
dest_dir = os.path.join(hass.config.path('www'), 'icons')
os.makedirs(dest_dir, exist_ok=True)
dest = os.path.join(dest_dir, 'icon.svg')
if not os.path.exists(dest):
shutil.copyfile(source, dest)
except Exception as ex:
_LOGGER.warning("Failed to copy custom icon: %s", str(ex))
2024-11-21 16:17:51 +03:00
async def async_ask_question(call: ServiceCall) -> None:
"""Handle ask_question service."""
2024-11-24 02:20:29 +03:00
instance = call.data["instance"]
2024-11-24 17:27:49 +03:00
coordinator = hass.data[DOMAIN].get(instance)
if not coordinator:
2024-11-24 02:20:29 +03:00
raise HomeAssistantError(f"Instance {instance} not found")
2024-11-21 16:17:51 +03:00
try:
2024-11-24 02:20:29 +03:00
await coordinator.async_ask_question(
question=call.data["question"],
model=call.data.get("model"),
temperature=call.data.get("temperature"),
max_tokens=call.data.get("max_tokens"),
system_prompt=call.data.get("system_prompt"),
)
2024-11-21 16:17:51 +03:00
except Exception as err:
_LOGGER.error("Error asking question: %s", str(err))
2024-11-21 18:00:33 +03:00
raise HomeAssistantError(f"Failed to process question: {str(err)}")
2024-11-21 16:17:51 +03:00
async def async_clear_history(call: ServiceCall) -> None:
"""Handle clear_history service."""
2024-11-24 02:20:29 +03:00
instance = call.data["instance"]
2024-11-24 17:27:49 +03:00
coordinator = hass.data[DOMAIN].get(instance)
if not coordinator:
2024-11-24 02:20:29 +03:00
raise HomeAssistantError(f"Instance {instance} not found")
2024-11-21 18:00:33 +03:00
try:
2024-11-24 02:20:29 +03:00
await coordinator.async_clear_history()
2024-11-21 18:00:33 +03:00
except Exception as err:
_LOGGER.error("Error clearing history: %s", str(err))
raise HomeAssistantError(f"Failed to clear history: {str(err)}")
2024-11-21 16:17:51 +03:00
2024-11-23 18:50:48 +03:00
async def async_get_history(call: ServiceCall) -> None:
"""Handle get_history service."""
2024-11-24 02:20:29 +03:00
instance = call.data["instance"]
2024-11-24 17:27:49 +03:00
coordinator = hass.data[DOMAIN].get(instance)
if not coordinator:
2024-11-24 02:20:29 +03:00
raise HomeAssistantError(f"Instance {instance} not found")
2024-11-23 18:50:48 +03:00
try:
2024-11-24 02:20:29 +03:00
return await coordinator.async_get_history(
limit=call.data.get("limit"),
filter_model=call.data.get("filter_model"),
instance=instance
2024-11-23 18:50:48 +03:00
)
except Exception as err:
_LOGGER.error("Error getting history: %s", str(err))
raise HomeAssistantError(f"Failed to get history: {str(err)}")
2024-11-21 16:17:51 +03:00
async def async_set_system_prompt(call: ServiceCall) -> None:
"""Handle set_system_prompt service."""
2024-11-24 02:20:29 +03:00
instance = call.data["instance"]
2024-11-24 17:27:49 +03:00
coordinator = hass.data[DOMAIN].get(instance)
if not coordinator:
2024-11-24 02:20:29 +03:00
raise HomeAssistantError(f"Instance {instance} not found")
2024-11-21 18:00:33 +03:00
try:
2024-11-24 02:20:29 +03:00
await coordinator.async_set_system_prompt(call.data["prompt"])
2024-11-21 18:00:33 +03:00
except Exception as err:
_LOGGER.error("Error setting system prompt: %s", str(err))
raise HomeAssistantError(f"Failed to set system prompt: {str(err)}")
2024-11-22 18:59:10 +03:00
hass.services.async_register(
DOMAIN,
SERVICE_ASK_QUESTION,
async_ask_question,
2024-11-24 02:20:29 +03:00
schema=SERVICE_SCHEMA_ASK_QUESTION
2024-11-22 18:59:10 +03:00
)
hass.services.async_register(
DOMAIN,
SERVICE_CLEAR_HISTORY,
async_clear_history,
2024-11-24 02:20:29 +03:00
schema=vol.Schema({vol.Required("instance"): cv.string})
2024-11-22 18:59:10 +03:00
)
2024-11-23 18:50:48 +03:00
hass.services.async_register(
DOMAIN,
SERVICE_GET_HISTORY,
async_get_history,
2024-11-24 02:20:29 +03:00
schema=SERVICE_SCHEMA_GET_HISTORY
2024-11-23 18:50:48 +03:00
)
2024-11-22 18:59:10 +03:00
hass.services.async_register(
DOMAIN,
SERVICE_SET_SYSTEM_PROMPT,
async_set_system_prompt,
2024-11-24 02:20:29 +03:00
schema=SERVICE_SCHEMA_SET_SYSTEM_PROMPT
2024-11-21 16:17:51 +03:00
)
2024-11-21 14:55:27 +03:00
return True
2024-11-22 01:34:47 +03:00
async def async_check_api(session, endpoint: str, headers: dict, provider: str) -> bool:
2024-11-20 01:02:27 +03:00
"""Check API availability for different providers."""
try:
2024-11-22 01:34:47 +03:00
if provider == API_PROVIDER_ANTHROPIC:
2024-11-20 01:02:27 +03:00
check_url = f"{endpoint}/v1/models"
2024-11-22 01:34:47 +03:00
else: # OpenAI
check_url = f"{endpoint}/models"
2024-11-20 01:02:27 +03:00
async with timeout(API_TIMEOUT):
async with session.get(check_url, headers=headers) as response:
2024-11-22 01:34:47 +03:00
if response.status in [200, 404]:
2024-11-21 14:28:17 +03:00
return True
2024-11-20 01:02:27 +03:00
elif response.status == 401:
raise ConfigEntryNotReady("Invalid API key")
elif response.status == 429:
_LOGGER.warning("Rate limit exceeded during API check")
return False
else:
_LOGGER.error("API check failed with status: %d", response.status)
return False
except Exception as ex:
_LOGGER.error("API check error: %s", str(ex))
return False
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-22 01:34:47 +03:00
if CONF_API_PROVIDER not in entry.data:
_LOGGER.error("API provider not specified")
raise ConfigEntryNotReady("API provider is required")
2024-11-19 14:35:45 +03:00
session = aiohttp_client.async_get_clientsession(hass)
2024-11-22 01:34:47 +03:00
api_provider = entry.data.get(CONF_API_PROVIDER)
2024-11-20 01:02:27 +03:00
model = entry.data.get(CONF_MODEL, DEFAULT_MODEL)
2024-11-24 17:27:49 +03:00
endpoint = entry.data.get(
CONF_API_ENDPOINT,
2024-11-22 01:34:47 +03:00
DEFAULT_OPENAI_ENDPOINT if api_provider == API_PROVIDER_OPENAI
2024-11-24 17:27:49 +03:00
else DEFAULT_ANTHROPIC_ENDPOINT
).rstrip('/')
2024-11-21 14:28:17 +03:00
api_key = entry.data[CONF_API_KEY]
2024-11-24 02:20:29 +03:00
instance_name = entry.data.get(CONF_NAME, entry.entry_id)
2024-11-22 01:34:47 +03:00
is_anthropic = api_provider == API_PROVIDER_ANTHROPIC
2024-11-24 17:27:49 +03:00
2024-11-20 01:02:27 +03:00
headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
2024-11-22 01:34:47 +03:00
if is_anthropic:
2024-11-20 01:02:27 +03:00
headers["x-api-key"] = api_key
headers["anthropic-version"] = "2023-06-01"
2024-11-23 18:50:48 +03:00
else:
2024-11-20 01:02:27 +03:00
headers["Authorization"] = f"Bearer {api_key}"
2024-11-23 18:50:48 +03:00
if not await async_check_api(session, endpoint, headers, api_provider):
raise ConfigEntryNotReady("API connection failed")
2024-11-20 01:02:27 +03:00
2024-11-24 17:27:49 +03:00
# Создаем API клиент
api_client = {
"session": session,
"endpoint": endpoint,
"headers": headers,
"api_provider": api_provider,
"model": model,
}
2024-11-24 17:34:51 +03:00
# Получаем интервал обновления
2024-11-24 17:41:48 +03:00
update_interval = timedelta(
seconds=entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
)
2024-11-24 17:34:51 +03:00
2024-11-23 18:50:48 +03:00
coordinator = HATextAICoordinator(
2024-11-24 02:20:29 +03:00
hass=hass,
2024-11-24 17:27:49 +03:00
client=api_client,
2024-11-23 18:50:48 +03:00
model=model,
2024-11-24 17:46:39 +03:00
update_interval=entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL), # Передаем числовое значение
2024-11-24 02:20:29 +03:00
instance_name=instance_name,
2024-11-23 18:50:48 +03:00
max_tokens=entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
2024-11-24 02:20:29 +03:00
temperature=entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
is_anthropic=is_anthropic,
2024-11-23 18:50:48 +03:00
)
2024-11-18 11:35:23 +03:00
2024-11-24 17:27:49 +03:00
# Инициализация координатора
await coordinator.async_config_entry_first_refresh()
# Сохраняем координатор
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
2024-11-21 14:55:27 +03:00
2024-11-24 03:03:01 +03:00
# Загружаем платформы
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
2024-11-23 18:50:48 +03:00
return True
2024-11-21 16:17:51 +03:00
2024-11-21 18:05:45 +03:00
except Exception as ex:
_LOGGER.exception("Setup error: %s", str(ex))
raise ConfigEntryNotReady(f"Setup error: {str(ex)}") from ex
2024-11-21 16:17:51 +03:00
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
try:
2024-11-24 16:29:57 +03:00
if entry.entry_id in hass.data[DOMAIN]:
2024-11-24 17:27:49 +03:00
coordinator = hass.data[DOMAIN][entry.entry_id]
2024-11-21 16:17:51 +03:00
await coordinator.async_shutdown()
2024-11-24 16:29:57 +03:00
hass.data[DOMAIN].pop(entry.entry_id)
2024-11-21 16:17:51 +03:00
2024-11-24 02:20:29 +03:00
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
2024-11-21 16:17:51 +03:00
except Exception as ex:
_LOGGER.exception("Error unloading entry: %s", str(ex))
2024-11-23 18:50:48 +03:00
return False