2024-11-29 16:38:41 +03:00
|
|
|
"""
|
|
|
|
|
The HA Text AI integration.
|
|
|
|
|
|
2026-04-17 01:30:57 +03:00
|
|
|
@license: MIT (https://opensource.org/licenses/MIT)
|
2024-11-29 16:38:41 +03:00
|
|
|
@author: SMKRV
|
|
|
|
|
@github: https://github.com/smkrv/ha-text-ai
|
|
|
|
|
@source: https://github.com/smkrv/ha-text-ai
|
|
|
|
|
"""
|
2024-11-21 14:55:27 +03:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import logging
|
2026-04-17 01:58:16 +03:00
|
|
|
from typing import Any
|
2026-03-12 01:24:01 +03:00
|
|
|
|
|
|
|
|
import asyncio
|
2024-11-23 23:42:33 +03:00
|
|
|
|
|
|
|
|
import voluptuous as vol
|
2024-11-21 14:55:27 +03:00
|
|
|
|
|
|
|
|
from homeassistant.config_entries import ConfigEntry
|
2026-07-07 01:49:03 +03:00
|
|
|
from homeassistant.const import CONF_API_KEY, CONF_NAME, EVENT_HOMEASSISTANT_CLOSE
|
2026-03-12 01:24:01 +03:00
|
|
|
from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse
|
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
|
2026-03-12 01:26:31 +03:00
|
|
|
from homeassistant.util import dt as dt_util
|
2024-11-21 14:55:27 +03:00
|
|
|
|
|
|
|
|
from .coordinator import HATextAICoordinator
|
2024-11-24 23:14:48 +03:00
|
|
|
from .api_client import APIClient
|
2026-04-17 01:58:16 +03:00
|
|
|
from .utils import create_pinned_session, normalize_name, safe_log_data, validate_endpoint
|
2026-03-12 00:55:59 +03:00
|
|
|
from .providers import get_default_endpoint, get_default_model, build_auth_headers
|
2024-11-21 14:55:27 +03:00
|
|
|
from .const import (
|
|
|
|
|
DOMAIN,
|
|
|
|
|
PLATFORMS,
|
|
|
|
|
CONF_MODEL,
|
|
|
|
|
CONF_TEMPERATURE,
|
|
|
|
|
CONF_MAX_TOKENS,
|
|
|
|
|
CONF_API_ENDPOINT,
|
|
|
|
|
CONF_REQUEST_INTERVAL,
|
2025-12-22 00:07:17 +03:00
|
|
|
CONF_API_TIMEOUT,
|
2024-11-22 01:34:47 +03:00
|
|
|
CONF_API_PROVIDER,
|
2024-11-25 14:59:44 +03:00
|
|
|
CONF_CONTEXT_MESSAGES,
|
2024-11-21 14:55:27 +03:00
|
|
|
DEFAULT_TEMPERATURE,
|
|
|
|
|
DEFAULT_MAX_TOKENS,
|
|
|
|
|
DEFAULT_REQUEST_INTERVAL,
|
2025-12-22 00:07:17 +03:00
|
|
|
DEFAULT_API_TIMEOUT,
|
2024-11-25 14:59:44 +03:00
|
|
|
DEFAULT_CONTEXT_MESSAGES,
|
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-28 23:27:39 +03:00
|
|
|
DEFAULT_MAX_HISTORY,
|
|
|
|
|
CONF_MAX_HISTORY_SIZE,
|
2026-03-23 12:18:58 +03:00
|
|
|
CONF_ALLOW_LOCAL_NETWORK,
|
|
|
|
|
DEFAULT_ALLOW_LOCAL_NETWORK,
|
2026-04-17 01:30:57 +03:00
|
|
|
CONF_DISABLE_THINKING,
|
|
|
|
|
DEFAULT_DISABLE_THINKING,
|
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,
|
2026-03-12 01:24:01 +03:00
|
|
|
vol.Required("question"): vol.All(cv.string, vol.Length(min=1, max=100000)),
|
|
|
|
|
vol.Optional("system_prompt"): vol.All(cv.string, vol.Length(max=50000)),
|
2024-11-24 02:20:29 +03:00
|
|
|
vol.Optional("model"): cv.string,
|
2026-03-12 01:24:01 +03:00
|
|
|
vol.Optional("temperature"): vol.All(
|
|
|
|
|
vol.Coerce(float), vol.Range(min=0.0, max=2.0)
|
|
|
|
|
),
|
2024-11-24 02:20:29 +03:00
|
|
|
vol.Optional("max_tokens"): cv.positive_int,
|
2024-11-25 14:59:44 +03:00
|
|
|
vol.Optional("context_messages"): cv.positive_int,
|
2025-12-30 16:42:32 +03:00
|
|
|
vol.Optional("structured_output", default=False): cv.boolean,
|
2026-03-12 01:24:01 +03:00
|
|
|
vol.Optional("json_schema"): vol.All(cv.string, vol.Length(max=50000)),
|
2026-04-17 01:30:57 +03:00
|
|
|
vol.Optional("disable_thinking"): cv.boolean,
|
2024-11-24 02:20:29 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
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,
|
2026-07-07 01:22:19 +03:00
|
|
|
# No default and no schema max: omitting limit returns the full history
|
|
|
|
|
# (pre-2.5.0 behavior) and oversized values are clamped to
|
|
|
|
|
# ABSOLUTE_MAX_HISTORY_SIZE in history.async_get_history instead of
|
|
|
|
|
# failing the whole service call.
|
|
|
|
|
vol.Optional("limit"): vol.All(cv.positive_int, vol.Range(min=1)),
|
2024-11-24 02:20:29 +03:00
|
|
|
vol.Optional("filter_model"): cv.string,
|
2025-09-02 23:27:34 +03:00
|
|
|
vol.Optional("start_date"): cv.string,
|
|
|
|
|
vol.Optional("include_metadata"): cv.boolean,
|
|
|
|
|
vol.Optional("sort_order"): vol.In(["newest", "oldest"]),
|
2024-11-24 02:20:29 +03:00
|
|
|
})
|
2024-11-21 18:00:33 +03:00
|
|
|
|
2024-11-24 20:12:03 +03:00
|
|
|
def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAICoordinator:
|
2026-03-12 02:24:09 +03:00
|
|
|
"""Get coordinator by instance name or normalized name.
|
|
|
|
|
|
|
|
|
|
Accepts instance_name, normalized_name, or sensor entity_id.
|
|
|
|
|
"""
|
2024-11-24 20:12:03 +03:00
|
|
|
if instance.startswith("sensor."):
|
|
|
|
|
instance = instance.replace("sensor.ha_text_ai_", "", 1)
|
|
|
|
|
|
2026-03-12 02:24:09 +03:00
|
|
|
normalized_input = normalize_name(instance)
|
|
|
|
|
|
2024-11-24 20:12:03 +03:00
|
|
|
for entry_id, coord in hass.data[DOMAIN].items():
|
2026-03-12 02:24:09 +03:00
|
|
|
if not isinstance(coord, HATextAICoordinator):
|
|
|
|
|
continue
|
|
|
|
|
if (
|
|
|
|
|
coord.instance_name.lower() == instance.lower()
|
|
|
|
|
or coord.normalized_name == normalized_input
|
|
|
|
|
):
|
2024-11-24 20:12:03 +03:00
|
|
|
return coord
|
|
|
|
|
|
|
|
|
|
raise HomeAssistantError(f"Instance {instance} not found")
|
|
|
|
|
|
2026-04-17 01:58:16 +03:00
|
|
|
async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool:
|
2024-12-06 02:51:06 +03:00
|
|
|
"""Set up the Home Assistant Text AI component."""
|
|
|
|
|
# Initialize domain data storage
|
|
|
|
|
hass.data.setdefault(DOMAIN, {})
|
2026-07-07 01:38:27 +03:00
|
|
|
_async_register_services(hass)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def _async_register_services(hass: HomeAssistant) -> None:
|
|
|
|
|
"""Register domain services; safe to call again after unload.
|
|
|
|
|
|
|
|
|
|
Unloading the last config entry unregisters the services, and a config
|
|
|
|
|
entry reload (every options change does one) runs unload + setup_entry
|
|
|
|
|
without re-running async_setup — so setup_entry must be able to bring
|
|
|
|
|
the services back.
|
|
|
|
|
"""
|
|
|
|
|
if hass.services.has_service(DOMAIN, SERVICE_ASK_QUESTION):
|
|
|
|
|
return
|
2024-11-23 18:50:48 +03:00
|
|
|
|
2025-09-01 17:14:23 +03:00
|
|
|
async def async_ask_question(call: ServiceCall) -> dict:
|
|
|
|
|
"""Handle ask_question service with response data."""
|
2024-11-21 16:17:51 +03:00
|
|
|
try:
|
2024-11-24 20:12:03 +03:00
|
|
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
2025-09-01 17:14:23 +03:00
|
|
|
response = await coordinator.async_ask_question(
|
2024-11-24 02:20:29 +03:00
|
|
|
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-25 14:59:44 +03:00
|
|
|
context_messages=call.data.get("context_messages"),
|
2025-12-30 16:42:32 +03:00
|
|
|
structured_output=call.data.get("structured_output", False),
|
|
|
|
|
json_schema=call.data.get("json_schema"),
|
2026-04-17 01:30:57 +03:00
|
|
|
disable_thinking=call.data.get("disable_thinking"),
|
2024-11-24 02:20:29 +03:00
|
|
|
)
|
2025-09-01 17:14:23 +03:00
|
|
|
|
|
|
|
|
# Return structured response data
|
|
|
|
|
return {
|
|
|
|
|
"response_text": response.get("content", ""),
|
|
|
|
|
"tokens_used": response.get("tokens", {}).get("total", 0),
|
|
|
|
|
"prompt_tokens": response.get("tokens", {}).get("prompt", 0),
|
|
|
|
|
"completion_tokens": response.get("tokens", {}).get("completion", 0),
|
|
|
|
|
"model_used": response.get("model", call.data.get("model", coordinator.model)),
|
|
|
|
|
"instance": call.data["instance"],
|
|
|
|
|
"question": call.data["question"],
|
|
|
|
|
"timestamp": response.get("timestamp"),
|
|
|
|
|
"success": True
|
|
|
|
|
}
|
2024-11-21 16:17:51 +03:00
|
|
|
except Exception as err:
|
|
|
|
|
_LOGGER.error("Error asking question: %s", str(err))
|
2025-09-01 17:14:23 +03:00
|
|
|
# Return error response
|
|
|
|
|
return {
|
|
|
|
|
"response_text": "",
|
|
|
|
|
"tokens_used": 0,
|
|
|
|
|
"prompt_tokens": 0,
|
|
|
|
|
"completion_tokens": 0,
|
|
|
|
|
"model_used": call.data.get("model", ""),
|
|
|
|
|
"instance": call.data["instance"],
|
|
|
|
|
"question": call.data["question"],
|
2026-03-12 01:26:31 +03:00
|
|
|
"timestamp": dt_util.utcnow().isoformat(),
|
2025-09-01 17:14:23 +03:00
|
|
|
"success": False,
|
2026-03-12 02:24:09 +03:00
|
|
|
"error": str(err),
|
|
|
|
|
"error_type": type(err).__name__
|
2025-09-01 17:14:23 +03:00
|
|
|
}
|
2024-11-21 16:17:51 +03:00
|
|
|
|
|
|
|
|
async def async_clear_history(call: ServiceCall) -> None:
|
|
|
|
|
"""Handle clear_history service."""
|
2024-11-21 18:00:33 +03:00
|
|
|
try:
|
2024-11-24 20:12:03 +03:00
|
|
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
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))
|
2026-04-17 01:30:57 +03:00
|
|
|
raise HomeAssistantError(f"Failed to clear history: {str(err)}") from err
|
2024-11-21 16:17:51 +03:00
|
|
|
|
2026-07-07 01:38:27 +03:00
|
|
|
async def async_get_history(call: ServiceCall) -> dict:
|
2024-11-23 18:50:48 +03:00
|
|
|
"""Handle get_history service."""
|
|
|
|
|
try:
|
2024-11-24 20:12:03 +03:00
|
|
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
2026-07-07 01:38:27 +03:00
|
|
|
history = await coordinator.async_get_history(
|
2024-11-24 02:20:29 +03:00
|
|
|
limit=call.data.get("limit"),
|
2025-09-02 23:27:34 +03:00
|
|
|
filter_model=call.data.get("filter_model"),
|
|
|
|
|
start_date=call.data.get("start_date"),
|
|
|
|
|
include_metadata=call.data.get("include_metadata", False),
|
|
|
|
|
sort_order=call.data.get("sort_order", "newest")
|
2024-11-23 18:50:48 +03:00
|
|
|
)
|
2026-07-07 01:38:27 +03:00
|
|
|
# HA requires action responses to be dicts. The bare list made
|
|
|
|
|
# every return_response call fail with a server error, so this
|
|
|
|
|
# path never worked before and the wrapper breaks no consumer.
|
|
|
|
|
return {"history": history}
|
2024-11-23 18:50:48 +03:00
|
|
|
except Exception as err:
|
|
|
|
|
_LOGGER.error("Error getting history: %s", str(err))
|
2026-04-17 01:30:57 +03:00
|
|
|
raise HomeAssistantError(f"Failed to get history: {str(err)}") from err
|
2024-11-23 18:50:48 +03:00
|
|
|
|
2024-11-21 16:17:51 +03:00
|
|
|
async def async_set_system_prompt(call: ServiceCall) -> None:
|
|
|
|
|
"""Handle set_system_prompt service."""
|
2024-11-21 18:00:33 +03:00
|
|
|
try:
|
2024-11-24 20:12:03 +03:00
|
|
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
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))
|
2026-04-17 01:30:57 +03:00
|
|
|
raise HomeAssistantError(f"Failed to set system prompt: {str(err)}") from err
|
2024-11-21 18:00:33 +03:00
|
|
|
|
2024-12-06 02:51:06 +03:00
|
|
|
# Register services
|
2024-11-22 18:59:10 +03:00
|
|
|
hass.services.async_register(
|
|
|
|
|
DOMAIN,
|
|
|
|
|
SERVICE_ASK_QUESTION,
|
|
|
|
|
async_ask_question,
|
2025-09-02 01:19:44 +03:00
|
|
|
schema=SERVICE_SCHEMA_ASK_QUESTION,
|
2026-03-12 01:24:01 +03:00
|
|
|
supports_response=SupportsResponse.OPTIONAL
|
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,
|
2026-03-12 01:24:01 +03:00
|
|
|
schema=SERVICE_SCHEMA_GET_HISTORY,
|
|
|
|
|
supports_response=SupportsResponse.OPTIONAL
|
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
|
|
|
)
|
|
|
|
|
|
2025-12-22 00:07:17 +03:00
|
|
|
async def async_check_api(session, endpoint: str, headers: dict, provider: str, api_timeout: int = DEFAULT_API_TIMEOUT) -> bool:
|
2026-03-12 02:24:09 +03:00
|
|
|
"""Check API availability using provider registry configuration."""
|
2024-11-20 01:02:27 +03:00
|
|
|
try:
|
2026-03-12 02:24:09 +03:00
|
|
|
from .providers import get_provider_config
|
|
|
|
|
provider_config = get_provider_config(provider)
|
|
|
|
|
check_path = provider_config.get("check_path")
|
|
|
|
|
|
|
|
|
|
if check_path is None:
|
|
|
|
|
# Provider does not support /models check (e.g. Gemini)
|
|
|
|
|
auth_header = provider_config["auth_header"]
|
|
|
|
|
auth_value = headers.get(auth_header, "").replace(provider_config.get("auth_prefix", ""), "")
|
|
|
|
|
if auth_value:
|
2025-05-21 01:26:42 +03:00
|
|
|
return True
|
2026-03-12 02:24:09 +03:00
|
|
|
_LOGGER.error("API key is missing or empty for %s", provider)
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
check_url = f"{endpoint}{check_path}"
|
2024-11-20 01:02:27 +03:00
|
|
|
|
2026-03-12 01:24:01 +03:00
|
|
|
async with asyncio.timeout(api_timeout):
|
2026-07-07 01:22:19 +03:00
|
|
|
async with session.get(
|
|
|
|
|
check_url, headers=headers, allow_redirects=False
|
|
|
|
|
) as response:
|
2026-03-12 01:24:01 +03:00
|
|
|
if response.status == 200:
|
2024-11-21 14:28:17 +03:00
|
|
|
return True
|
2024-11-20 01:02:27 +03:00
|
|
|
elif response.status == 401:
|
2025-05-21 01:26:42 +03:00
|
|
|
_LOGGER.error("Invalid API key")
|
|
|
|
|
return False
|
2024-11-20 01:02:27 +03:00
|
|
|
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."""
|
2026-03-12 01:24:01 +03:00
|
|
|
_LOGGER.debug("Setting up HA Text AI entry: %s", safe_log_data(dict(entry.data)))
|
2024-11-28 23:27:39 +03:00
|
|
|
|
2026-07-07 01:22:19 +03:00
|
|
|
session = None
|
2024-11-18 11:35:23 +03:00
|
|
|
try:
|
2025-12-30 17:22:48 +03:00
|
|
|
# Get provider from data or options (options takes precedence)
|
|
|
|
|
config = {**entry.data, **entry.options}
|
|
|
|
|
api_provider = config.get(CONF_API_PROVIDER)
|
|
|
|
|
|
|
|
|
|
if not api_provider:
|
2024-11-22 01:34:47 +03:00
|
|
|
_LOGGER.error("API provider not specified")
|
|
|
|
|
raise ConfigEntryNotReady("API provider is required")
|
|
|
|
|
|
2026-03-12 00:55:59 +03:00
|
|
|
model = config.get(CONF_MODEL, get_default_model(api_provider))
|
2026-03-12 01:24:01 +03:00
|
|
|
raw_endpoint = config.get(CONF_API_ENDPOINT, get_default_endpoint(api_provider))
|
2026-03-23 12:18:58 +03:00
|
|
|
allow_local = config.get(CONF_ALLOW_LOCAL_NETWORK, DEFAULT_ALLOW_LOCAL_NETWORK)
|
|
|
|
|
if allow_local:
|
2026-04-17 01:58:16 +03:00
|
|
|
_LOGGER.info(
|
2026-03-23 12:18:58 +03:00
|
|
|
"Local network mode enabled for endpoint %s — "
|
2026-04-17 01:58:16 +03:00
|
|
|
"SSRF protection relaxed for self-hosted proxies",
|
2026-03-23 12:18:58 +03:00
|
|
|
raw_endpoint,
|
|
|
|
|
)
|
2026-03-12 01:24:01 +03:00
|
|
|
try:
|
2026-04-17 01:58:16 +03:00
|
|
|
endpoint, resolved_ips = await validate_endpoint(
|
|
|
|
|
hass, raw_endpoint, allow_local=allow_local
|
|
|
|
|
)
|
2026-03-12 01:24:01 +03:00
|
|
|
except ValueError as err:
|
2026-03-12 01:57:49 +03:00
|
|
|
_LOGGER.error("Invalid API endpoint: %s", err)
|
2026-03-12 01:26:31 +03:00
|
|
|
raise ConfigEntryNotReady(f"Invalid API endpoint: {err}") from err
|
2026-04-17 01:58:16 +03:00
|
|
|
|
|
|
|
|
# Pinned session closes DNS-rebinding TOCTOU and isolates cookies
|
|
|
|
|
# from other integrations sharing the same endpoint hostname.
|
2026-07-07 01:22:19 +03:00
|
|
|
# The integration owns this session: APIClient.shutdown() closes it
|
|
|
|
|
# on unload, the except handler below closes it on failed setup.
|
|
|
|
|
session = create_pinned_session(endpoint, resolved_ips)
|
2025-12-30 17:22:48 +03:00
|
|
|
# API key can now be updated via options
|
|
|
|
|
api_key = config.get(CONF_API_KEY, entry.data.get(CONF_API_KEY))
|
2024-11-24 02:20:29 +03:00
|
|
|
instance_name = entry.data.get(CONF_NAME, entry.entry_id)
|
2025-12-22 00:07:17 +03:00
|
|
|
request_interval = config.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
|
|
|
|
api_timeout = config.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
|
|
|
|
|
max_tokens = config.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
|
|
|
|
temperature = config.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
|
|
|
|
max_history_size = config.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
|
|
|
|
context_messages = config.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
2026-04-17 01:30:57 +03:00
|
|
|
disable_thinking = config.get(CONF_DISABLE_THINKING, DEFAULT_DISABLE_THINKING)
|
2024-11-24 17:27:49 +03:00
|
|
|
|
2026-03-12 00:55:59 +03:00
|
|
|
headers = build_auth_headers(api_provider, api_key)
|
2024-11-20 01:02:27 +03:00
|
|
|
|
2025-12-22 00:07:17 +03:00
|
|
|
if not await async_check_api(session, endpoint, headers, api_provider, api_timeout):
|
2024-11-23 18:50:48 +03:00
|
|
|
raise ConfigEntryNotReady("API connection failed")
|
2024-11-20 01:02:27 +03:00
|
|
|
|
2024-11-24 23:14:48 +03:00
|
|
|
_LOGGER.debug("Creating API client for %s with endpoint %s", api_provider, endpoint)
|
|
|
|
|
|
|
|
|
|
api_client = APIClient(
|
|
|
|
|
session=session,
|
|
|
|
|
endpoint=endpoint,
|
|
|
|
|
headers=headers,
|
|
|
|
|
api_provider=api_provider,
|
|
|
|
|
model=model,
|
2025-12-22 00:07:17 +03:00
|
|
|
api_timeout=api_timeout,
|
2026-03-12 01:57:49 +03:00
|
|
|
api_key=api_key,
|
2024-11-24 23:14:48 +03:00
|
|
|
)
|
2024-11-24 17:27:49 +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-28 23:27:39 +03:00
|
|
|
update_interval=request_interval,
|
2024-11-24 02:20:29 +03:00
|
|
|
instance_name=instance_name,
|
2026-03-12 02:24:09 +03:00
|
|
|
config_entry=entry,
|
2024-11-28 23:27:39 +03:00
|
|
|
max_tokens=max_tokens,
|
|
|
|
|
temperature=temperature,
|
|
|
|
|
max_history_size=max_history_size,
|
|
|
|
|
context_messages=context_messages,
|
2025-12-22 00:07:17 +03:00
|
|
|
api_timeout=api_timeout,
|
2026-04-17 01:30:57 +03:00
|
|
|
disable_thinking=disable_thinking,
|
2024-11-23 18:50:48 +03:00
|
|
|
)
|
2024-11-18 11:35:23 +03:00
|
|
|
|
2026-03-12 01:24:01 +03:00
|
|
|
# Initialize coordinator (directories, history, metrics)
|
|
|
|
|
await coordinator.async_initialize()
|
|
|
|
|
|
|
|
|
|
_LOGGER.debug("Created coordinator for %s", instance_name)
|
2024-11-25 02:05:13 +03:00
|
|
|
|
2024-11-28 23:27:39 +03:00
|
|
|
# Store coordinator
|
2024-11-25 02:05:13 +03:00
|
|
|
hass.data.setdefault(DOMAIN, {})
|
|
|
|
|
hass.data[DOMAIN][entry.entry_id] = coordinator
|
|
|
|
|
|
2026-07-07 01:38:27 +03:00
|
|
|
# A reload after the last entry was unloaded needs the services back.
|
|
|
|
|
_async_register_services(hass)
|
|
|
|
|
|
2026-03-12 01:24:01 +03:00
|
|
|
_LOGGER.debug("Stored coordinator in hass.data[%s][%s]", DOMAIN, entry.entry_id)
|
2024-11-28 23:27:39 +03:00
|
|
|
|
|
|
|
|
# Set up platforms
|
2024-11-25 02:05:13 +03:00
|
|
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
|
|
|
|
|
2025-12-30 17:22:48 +03:00
|
|
|
# Register update listener for options changes
|
|
|
|
|
entry.async_on_unload(entry.add_update_listener(async_update_options))
|
|
|
|
|
|
2026-07-07 01:49:03 +03:00
|
|
|
# HA Core stop does not unload entries, so close the dedicated
|
|
|
|
|
# session on the CLOSE event too; unload removes this listener
|
|
|
|
|
# and closes the session via APIClient.shutdown() instead.
|
|
|
|
|
async def _async_close_session_on_stop(_event) -> None:
|
|
|
|
|
if not session.closed:
|
|
|
|
|
await session.close()
|
|
|
|
|
|
|
|
|
|
entry.async_on_unload(
|
|
|
|
|
hass.bus.async_listen_once(
|
|
|
|
|
EVENT_HOMEASSISTANT_CLOSE, _async_close_session_on_stop
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-12 01:24:01 +03:00
|
|
|
_LOGGER.debug("Setup completed for %s", instance_name)
|
2024-11-25 02:05:13 +03:00
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
2024-11-28 23:27:39 +03:00
|
|
|
except Exception as err:
|
2026-03-12 01:24:01 +03:00
|
|
|
_LOGGER.exception("Error setting up HA Text AI: %s", err)
|
2026-07-07 01:22:19 +03:00
|
|
|
if session is not None and not session.closed:
|
|
|
|
|
await session.close()
|
2024-11-28 23:27:39 +03:00
|
|
|
raise
|
2024-11-25 02:05:13 +03:00
|
|
|
|
2025-12-30 17:22:48 +03:00
|
|
|
async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
|
|
|
|
"""Handle options update - reload the config entry."""
|
|
|
|
|
_LOGGER.info("Options updated for %s, reloading integration", entry.title)
|
|
|
|
|
await hass.config_entries.async_reload(entry.entry_id)
|
|
|
|
|
|
2024-11-25 02:05:13 +03:00
|
|
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|
|
|
|
"""Unload a config entry."""
|
|
|
|
|
try:
|
2026-03-12 02:06:21 +03:00
|
|
|
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
|
|
|
|
if unload_ok and entry.entry_id in hass.data[DOMAIN]:
|
|
|
|
|
coordinator = hass.data[DOMAIN].pop(entry.entry_id)
|
2024-11-25 02:05:13 +03:00
|
|
|
|
|
|
|
|
if hasattr(coordinator.client, 'shutdown'):
|
|
|
|
|
await coordinator.client.shutdown()
|
|
|
|
|
|
|
|
|
|
await coordinator.async_shutdown()
|
|
|
|
|
|
2026-04-17 01:30:57 +03:00
|
|
|
# When removing the last config entry, also unregister services and
|
|
|
|
|
# clear the domain bucket so HA doesn't show stale services in the UI.
|
2026-03-12 02:06:21 +03:00
|
|
|
if not hass.data.get(DOMAIN):
|
|
|
|
|
hass.data.pop(DOMAIN, None)
|
2026-04-17 01:30:57 +03:00
|
|
|
for service in (
|
|
|
|
|
SERVICE_ASK_QUESTION,
|
|
|
|
|
SERVICE_CLEAR_HISTORY,
|
|
|
|
|
SERVICE_GET_HISTORY,
|
|
|
|
|
SERVICE_SET_SYSTEM_PROMPT,
|
|
|
|
|
):
|
|
|
|
|
if hass.services.has_service(DOMAIN, service):
|
|
|
|
|
hass.services.async_remove(DOMAIN, service)
|
2026-03-12 02:06:21 +03:00
|
|
|
|
|
|
|
|
return unload_ok
|
2024-11-25 02:05:13 +03:00
|
|
|
|
|
|
|
|
except Exception as ex:
|
|
|
|
|
_LOGGER.exception("Error unloading entry: %s", str(ex))
|
|
|
|
|
return False
|