Files

366 lines
13 KiB
Python
Raw Permalink Normal View History

2024-11-29 16:38:41 +03:00
"""
Sensor platform for HA Text AI.
@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
"""
from __future__ import annotations
2024-11-22 17:31:48 +03:00
import logging
2024-11-24 22:49:11 +03:00
import math
2026-04-17 01:58:16 +03:00
from typing import Any
2024-11-24 19:37:01 +03:00
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
)
2024-11-22 17:31:48 +03:00
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
2024-11-22 17:31:48 +03:00
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt as dt_util
2024-11-23 00:36:58 +03:00
from homeassistant.util import slugify
2024-11-22 17:31:48 +03:00
from .const import (
DOMAIN,
2024-11-24 16:56:39 +03:00
CONF_MODEL,
2024-11-24 17:09:23 +03:00
CONF_API_PROVIDER,
2024-11-22 17:31:48 +03:00
ATTR_TOTAL_RESPONSES,
2024-11-24 16:56:39 +03:00
ATTR_TOTAL_ERRORS,
ATTR_AVG_RESPONSE_TIME,
ATTR_LAST_REQUEST_TIME,
2024-11-22 17:31:48 +03:00
ATTR_LAST_ERROR,
2024-11-24 16:56:39 +03:00
ATTR_IS_PROCESSING,
ATTR_IS_RATE_LIMITED,
ATTR_IS_MAINTENANCE,
ATTR_API_VERSION,
ATTR_ENDPOINT_STATUS,
ATTR_PERFORMANCE_METRICS,
ATTR_HISTORY_SIZE,
ATTR_UPTIME,
ATTR_API_PROVIDER,
ATTR_MODEL,
ATTR_SYSTEM_PROMPT,
2024-11-24 17:09:23 +03:00
ATTR_RESPONSE,
ATTR_QUESTION,
2024-11-24 16:56:39 +03:00
METRIC_TOTAL_TOKENS,
METRIC_PROMPT_TOKENS,
METRIC_COMPLETION_TOKENS,
METRIC_SUCCESSFUL_REQUESTS,
METRIC_FAILED_REQUESTS,
METRIC_AVERAGE_LATENCY,
METRIC_MAX_LATENCY,
METRIC_MIN_LATENCY,
2024-11-22 17:31:48 +03:00
STATE_READY,
STATE_PROCESSING,
STATE_ERROR,
STATE_INITIALIZING,
STATE_MAINTENANCE,
2024-11-24 16:56:39 +03:00
STATE_RATE_LIMITED,
STATE_DISCONNECTED,
ENTITY_ICON,
ENTITY_ICON_ERROR,
ENTITY_ICON_PROCESSING,
2024-11-28 23:27:39 +03:00
DEFAULT_NAME_PREFIX,
CONF_MAX_HISTORY_SIZE,
VERSION,
2024-11-22 17:31:48 +03:00
)
2024-11-24 17:27:49 +03:00
from .coordinator import HATextAICoordinator
from .utils import safe_log_data
2024-11-24 17:27:49 +03:00
2024-11-22 17:31:48 +03:00
_LOGGER = logging.getLogger(__name__)
# HA Recorder limit is 16384 bytes for state_attributes.
# Budget per field to stay well within the limit.
_ATTR_TEXT_LIMIT = 2048
_ATTR_PROMPT_LIMIT = 512
2024-11-22 17:31:48 +03:00
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
2024-11-24 17:27:49 +03:00
"""Set up the HA Text AI sensor."""
_LOGGER.debug("Starting sensor setup for entry: %s", entry.entry_id)
2024-11-24 19:37:01 +03:00
2024-11-28 23:27:39 +03:00
try:
coordinator = hass.data[DOMAIN][entry.entry_id]
_LOGGER.debug("Found coordinator for entry %s", entry.entry_id)
2024-11-24 19:37:01 +03:00
2024-11-28 23:27:39 +03:00
instance_name = coordinator.instance_name
_LOGGER.debug("Setting up sensor with instance: %s", instance_name)
2024-11-28 23:27:39 +03:00
sensor = HATextAISensor(coordinator, entry)
_LOGGER.debug("Created sensor instance: %s", sensor.entity_id)
2024-11-28 23:27:39 +03:00
async_add_entities([sensor], True)
_LOGGER.debug("Added sensor entity: %s", sensor.entity_id)
2024-11-28 23:27:39 +03:00
except Exception as err:
_LOGGER.exception("Error setting up sensor: %s", err)
2024-11-28 23:27:39 +03:00
raise
2024-11-22 17:31:48 +03:00
2024-11-22 16:46:40 +03:00
class HATextAISensor(CoordinatorEntity, SensorEntity):
2024-11-24 17:27:49 +03:00
"""HA Text AI Sensor."""
coordinator: HATextAICoordinator
2024-11-22 16:58:22 +03:00
2024-11-23 02:21:10 +03:00
def __init__(
self,
2024-11-24 17:27:49 +03:00
coordinator: HATextAICoordinator,
2024-11-23 02:21:10 +03:00
config_entry: ConfigEntry,
) -> None:
"""Initialize the sensor."""
_LOGGER.debug("Initializing sensor with config entry: %s", safe_log_data(dict(config_entry.data)))
2024-11-28 23:27:39 +03:00
2024-11-23 02:21:10 +03:00
super().__init__(coordinator)
2024-11-24 17:27:49 +03:00
2024-11-23 02:21:10 +03:00
self._config_entry = config_entry
2024-11-24 18:36:37 +03:00
self._instance_name = coordinator.instance_name
2024-11-28 23:27:39 +03:00
self._normalized_name = coordinator.normalized_name
_LOGGER.debug("Instance name: %s", self._instance_name)
_LOGGER.debug("Normalized name: %s", self._normalized_name)
2024-11-28 23:27:39 +03:00
2024-11-24 20:12:03 +03:00
self._conversation_history = []
self._system_prompt = None
2024-11-24 18:36:37 +03:00
self._attr_has_entity_name = True
self._attr_name = self._instance_name
2024-11-28 23:27:39 +03:00
self.entity_id = f"sensor.ha_text_ai_{self._normalized_name}"
self._attr_unique_id = config_entry.entry_id
2024-11-24 19:24:30 +03:00
_LOGGER.debug("Created sensor with entity_id: %s", self.entity_id)
_LOGGER.debug("Sensor name: %s", self._attr_name)
_LOGGER.debug("Unique ID: %s", self._attr_unique_id)
2024-11-28 23:27:39 +03:00
2024-11-24 19:37:01 +03:00
self.entity_description = SensorEntityDescription(
2024-11-28 23:27:39 +03:00
key=f"ha_text_ai_{self._normalized_name.lower()}",
2024-11-24 19:37:01 +03:00
entity_registry_enabled_default=True,
2024-11-25 01:20:44 +03:00
)
2024-11-24 19:37:01 +03:00
2024-11-23 02:21:10 +03:00
self._current_state = STATE_INITIALIZING
self._error_count = 0
self._last_error = None
2024-11-24 17:27:49 +03:00
self._last_update = None
2024-11-24 20:12:03 +03:00
self._is_processing = False
2024-11-25 00:50:44 +03:00
self._last_response = {}
self._metrics = {}
2024-11-23 00:36:58 +03:00
2024-11-24 17:27:49 +03:00
model = config_entry.data.get(CONF_MODEL, "Unknown")
api_provider = config_entry.data.get(CONF_API_PROVIDER, "Unknown")
2024-11-24 16:56:39 +03:00
2024-11-23 21:31:27 +03:00
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self._attr_unique_id)},
2024-11-28 23:27:39 +03:00
name=self._attr_name,
2024-11-23 21:31:27 +03:00
manufacturer="Community",
2024-11-24 16:56:39 +03:00
model=f"{model} ({api_provider} provider)",
sw_version=VERSION,
entry_type=DeviceEntryType.SERVICE,
2024-11-23 21:31:27 +03:00
)
2024-11-18 00:43:28 +03:00
2024-11-28 23:27:39 +03:00
_LOGGER.debug(
"Initialized sensor: %s for instance: %s",
self.entity_id, self._instance_name,
2024-11-28 23:27:39 +03:00
)
2024-11-25 00:50:44 +03:00
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
2024-11-25 00:58:02 +03:00
self.coordinator.last_update_success
2024-11-25 00:50:44 +03:00
and self.coordinator.data is not None
2024-11-25 00:58:02 +03:00
and self._current_state != STATE_DISCONNECTED
2024-11-25 00:50:44 +03:00
)
2024-11-24 18:36:37 +03:00
2024-11-24 22:49:11 +03:00
def _sanitize_value(self, value: Any) -> Any:
2024-11-25 00:50:44 +03:00
"""Sanitize values for JSON serialization."""
2024-11-24 22:49:11 +03:00
if isinstance(value, float):
if math.isinf(value) or math.isnan(value):
return None
return value
2026-04-17 01:58:16 +03:00
def _sanitize_attributes(self, attributes: dict[str, Any]) -> dict[str, Any]:
2024-11-25 00:50:44 +03:00
"""Sanitize all attributes for JSON serialization."""
sanitized = {
2024-11-24 22:49:11 +03:00
key: self._sanitize_value(value)
for key, value in attributes.items()
2024-11-25 00:50:44 +03:00
if value is not None
2024-11-24 22:49:11 +03:00
}
# Log metrics for debugging
metrics_keys = [
METRIC_TOTAL_TOKENS,
METRIC_PROMPT_TOKENS,
METRIC_COMPLETION_TOKENS,
METRIC_SUCCESSFUL_REQUESTS,
METRIC_FAILED_REQUESTS,
METRIC_AVERAGE_LATENCY,
METRIC_MAX_LATENCY,
METRIC_MIN_LATENCY,
]
metrics_values = {k: sanitized.get(k) for k in metrics_keys if k in sanitized}
_LOGGER.debug("Metrics for %s: %s", self.entity_id, metrics_values)
return sanitized
2024-11-24 17:27:49 +03:00
@property
def native_value(self) -> StateType:
"""Return the native value of the sensor."""
2024-11-25 00:50:44 +03:00
if not self.coordinator.last_update_success or not self.coordinator.data:
2024-11-25 00:58:02 +03:00
self._current_state = STATE_DISCONNECTED
return self._current_state
2024-11-24 17:27:49 +03:00
2024-11-24 18:36:37 +03:00
status = self.coordinator.data.get("state", STATE_READY)
2024-11-24 17:55:39 +03:00
self._current_state = status
return status
2024-11-24 17:27:49 +03:00
2024-11-19 14:35:45 +03:00
@property
def icon(self) -> str:
2024-11-23 21:31:27 +03:00
"""Return the icon based on the current state."""
if self._current_state == STATE_ERROR:
return ENTITY_ICON_ERROR
elif self._current_state == STATE_PROCESSING:
return ENTITY_ICON_PROCESSING
return ENTITY_ICON
2024-11-18 00:43:28 +03:00
2024-11-22 17:19:40 +03:00
@property
2026-04-17 01:58:16 +03:00
def extra_state_attributes(self) -> dict[str, Any]:
2024-11-22 17:19:40 +03:00
"""Return entity specific state attributes."""
2024-11-24 17:55:39 +03:00
if not self.coordinator.data:
2024-11-25 00:50:44 +03:00
return {}
try:
data = self.coordinator.data
metrics = data.get("metrics", {})
# Base attributes
2024-11-25 00:50:44 +03:00
attributes = {
ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"),
ATTR_API_PROVIDER: self._config_entry.data.get(CONF_API_PROVIDER, "Unknown"),
ATTR_TOTAL_ERRORS: metrics.get("total_errors", 0),
2024-11-25 00:50:44 +03:00
"instance_name": self._instance_name,
2024-11-28 23:27:39 +03:00
"normalized_name": self._normalized_name,
ATTR_SYSTEM_PROMPT: (data.get("system_prompt", "")[:_ATTR_PROMPT_LIMIT]
if data.get("system_prompt") else None),
2024-11-25 00:50:44 +03:00
ATTR_IS_PROCESSING: data.get("is_processing", False),
ATTR_IS_RATE_LIMITED: data.get("is_rate_limited", False),
ATTR_IS_MAINTENANCE: data.get("is_maintenance", False),
ATTR_ENDPOINT_STATUS: data.get("endpoint_status", "unknown"),
ATTR_UPTIME: round(data.get("uptime", 0), 2),
2024-11-25 00:50:44 +03:00
ATTR_HISTORY_SIZE: data.get("history_size", 0),
}
# Conversation history preview (compact: last 3, truncated to 256 chars).
# Full history is available via ha_text_ai.get_history service.
conversation_history = data.get("conversation_history", [])
if conversation_history:
preview = conversation_history[-3:]
attributes["conversation_history"] = [
{
"timestamp": entry["timestamp"],
"question": entry["question"][:256],
"response": entry["response"][:256],
2024-11-28 23:27:39 +03:00
}
for entry in preview
]
2024-11-25 00:50:44 +03:00
# Metrics
if isinstance(metrics, dict):
attributes.update({
METRIC_TOTAL_TOKENS: metrics.get("total_tokens", 0),
METRIC_PROMPT_TOKENS: metrics.get("prompt_tokens", 0),
METRIC_COMPLETION_TOKENS: metrics.get("completion_tokens", 0),
METRIC_SUCCESSFUL_REQUESTS: metrics.get("successful_requests", 0),
METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0),
METRIC_AVERAGE_LATENCY: round(metrics.get("average_latency", 0), 2),
METRIC_MAX_LATENCY: round(metrics.get("max_latency", 0), 2),
METRIC_MIN_LATENCY: metrics.get("min_latency", 0) or None,
})
# Last response handling
2024-11-25 00:50:44 +03:00
last_response = data.get("last_response", {})
if isinstance(last_response, dict):
attributes.update({
ATTR_RESPONSE: last_response.get("response", "")[:_ATTR_TEXT_LIMIT],
ATTR_QUESTION: last_response.get("question", "")[:_ATTR_TEXT_LIMIT],
"last_model": last_response.get("model", ""),
"last_timestamp": last_response.get("timestamp", ""),
"last_error": (last_response.get("error", "")[:_ATTR_TEXT_LIMIT]
if last_response.get("error") else None),
})
2024-11-25 00:50:44 +03:00
2024-11-24 22:49:11 +03:00
return self._sanitize_attributes(attributes)
2024-11-24 02:20:29 +03:00
2024-11-25 00:50:44 +03:00
except Exception as err:
_LOGGER.error("Error preparing attributes: %s", err, exc_info=True)
return {}
2024-11-22 17:19:40 +03:00
2024-11-19 14:00:33 +03:00
async def async_added_to_hass(self) -> None:
"""When entity is added to hass."""
await super().async_added_to_hass()
self._handle_coordinator_update()
_LOGGER.debug("Entity %s added to Home Assistant", self.entity_id)
2024-11-19 14:35:45 +03:00
2024-11-24 17:27:49 +03:00
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
try:
data = self.coordinator.data
2024-11-25 00:58:02 +03:00
if not self.coordinator.last_update_success or not data:
2024-11-25 00:50:44 +03:00
self._current_state = STATE_DISCONNECTED
_LOGGER.warning("No data available for %s", self.entity_id)
2024-11-25 00:50:44 +03:00
self.async_write_ha_state()
return
2024-11-24 17:27:49 +03:00
2024-11-24 20:12:03 +03:00
self._is_processing = data.get("is_processing", False)
2024-11-25 00:50:44 +03:00
# Update metrics
metrics = data.get("metrics", {})
if isinstance(metrics, dict):
self._metrics.update(metrics)
_LOGGER.debug("Updated metrics for %s: %s", self.entity_id, self._metrics)
2024-11-25 00:58:02 +03:00
# Update conversation history and system prompt
2024-11-25 00:50:44 +03:00
self._conversation_history = data.get("conversation_history", [])
self._system_prompt = data.get("system_prompt")
# Update state based on conditions
2024-11-24 20:12:03 +03:00
if self._is_processing:
2024-11-24 17:27:49 +03:00
self._current_state = STATE_PROCESSING
elif data.get("is_rate_limited"):
self._current_state = STATE_RATE_LIMITED
elif data.get("is_maintenance"):
self._current_state = STATE_MAINTENANCE
elif data.get("error"):
self._current_state = STATE_ERROR
self._last_error = data["error"]
self._error_count += 1
else:
2024-11-25 00:58:02 +03:00
self._current_state = data.get("state", STATE_READY)
2024-11-24 17:27:49 +03:00
2024-11-25 00:50:44 +03:00
# Update last update timestamp
self._last_update = dt_util.utcnow()
2024-11-24 20:12:03 +03:00
2024-11-25 00:58:02 +03:00
_LOGGER.debug(
"Updated %s state to: %s (available: %s)",
self.entity_id, self._current_state, self.available,
2024-11-25 00:58:02 +03:00
)
2024-11-24 17:27:49 +03:00
except Exception as err:
self._current_state = STATE_ERROR
self._last_error = str(err)
self._error_count += 1
2024-11-25 00:58:02 +03:00
_LOGGER.error(
"Error handling update for %s: %s",
self.entity_id,
err,
2024-11-28 23:27:39 +03:00
exc_info=True,
2024-11-25 00:58:02 +03:00
)
self.async_write_ha_state()