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

303 lines
9.5 KiB
Python
Raw Normal View History

2024-11-24 17:27:49 +03:00
"""Sensor platform for HA Text AI."""
2024-11-22 17:31:48 +03:00
import logging
2024-11-24 22:49:11 +03:00
import math
2024-11-23 23:42:33 +03:00
from typing import Any, Dict
2024-11-22 17:31:48 +03:00
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
2024-11-23 23:42:33 +03:00
from homeassistant.helpers.device_registry import 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_API_STATUS,
ATTR_RESPONSE,
ATTR_QUESTION,
2024-11-24 20:12:03 +03:00
ATTR_CONVERSATION_HISTORY,
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-22 17:31:48 +03:00
)
2024-11-24 17:27:49 +03:00
from .coordinator import HATextAICoordinator
2024-11-22 17:31:48 +03:00
_LOGGER = logging.getLogger(__name__)
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."""
2024-11-22 17:31:48 +03:00
coordinator = hass.data[DOMAIN][entry.entry_id]
2024-11-24 18:36:37 +03:00
instance_name = coordinator.instance_name
2024-11-24 19:37:01 +03:00
2024-11-24 18:36:37 +03:00
_LOGGER.info(f"Setting up HA Text AI sensor with instance: {instance_name}")
2024-11-24 19:37:01 +03:00
sensor = HATextAISensor(coordinator, entry)
sensor.platform = "sensor"
sensor.platform_domain = DOMAIN
async_add_entities([sensor], True)
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."""
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-24 20:12:03 +03:00
self._conversation_history = []
self._system_prompt = None
2024-11-24 18:36:37 +03:00
2024-11-24 20:12:03 +03:00
# Entity attributes
2024-11-24 19:37:01 +03:00
self._attr_has_entity_name = True
2024-11-24 19:24:30 +03:00
self.entity_id = f"sensor.ha_text_ai_{self._instance_name}"
self._attr_name = f"HA Text AI {self._instance_name}"
self._attr_unique_id = f"{config_entry.entry_id}"
2024-11-24 20:12:03 +03:00
# Entity description
2024-11-24 19:37:01 +03:00
self.entity_description = SensorEntityDescription(
key=f"ha_text_ai_{self._instance_name}",
name=self._attr_name,
entity_registry_enabled_default=True,
)
2024-11-24 20:12:03 +03:00
# Integration info
2024-11-24 19:37:01 +03:00
self._attr_platform = "sensor"
self._attr_domain = DOMAIN
2024-11-24 19:24:30 +03:00
2024-11-24 20:12:03 +03:00
# State tracking
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-23 00:36:58 +03:00
2024-11-24 17:27:49 +03:00
# Device info
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-24 17:27:49 +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)",
2024-11-24 17:27:49 +03:00
sw_version="1.0.0",
2024-11-23 21:31:27 +03:00
)
2024-11-18 00:43:28 +03:00
2024-11-24 19:24:30 +03:00
_LOGGER.info(f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}")
2024-11-24 18:36:37 +03:00
2024-11-24 22:49:11 +03:00
def _sanitize_value(self, value: Any) -> Any:
"""Sanitize values for JSON serialization.
Args:
value: The value to sanitize
Returns:
Sanitized value safe for JSON serialization
"""
if isinstance(value, float):
if math.isinf(value) or math.isnan(value):
return None
return value
def _sanitize_attributes(self, attributes: Dict[str, Any]) -> Dict[str, Any]:
"""Sanitize all attributes for JSON serialization.
Args:
attributes: Dictionary of attributes to sanitize
Returns:
Dictionary with sanitized values
"""
return {
key: self._sanitize_value(value)
for key, value in attributes.items()
}
2024-11-24 17:27:49 +03:00
@property
def native_value(self) -> StateType:
"""Return the native value of the sensor."""
2024-11-24 17:55:39 +03:00
if not self.coordinator.data:
2024-11-24 17:27:49 +03:00
return STATE_DISCONNECTED
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
def extra_state_attributes(self) -> Dict[str, Any]:
"""Return entity specific state attributes."""
attributes = {
2024-11-24 17:09:23 +03:00
ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"),
2024-11-24 17:27:49 +03:00
ATTR_API_PROVIDER: self._config_entry.data.get(CONF_API_PROVIDER, "Unknown"),
2024-11-22 17:19:40 +03:00
ATTR_API_STATUS: self._current_state,
2024-11-24 17:27:49 +03:00
ATTR_TOTAL_ERRORS: self._error_count,
2024-11-22 17:19:40 +03:00
ATTR_LAST_ERROR: self._last_error,
2024-11-24 19:37:01 +03:00
"instance_name": self._instance_name,
2024-11-24 20:12:03 +03:00
ATTR_SYSTEM_PROMPT: self._system_prompt,
ATTR_CONVERSATION_HISTORY: self._conversation_history,
ATTR_IS_PROCESSING: self._is_processing,
2024-11-22 17:19:40 +03:00
}
2024-11-24 17:55:39 +03:00
if not self.coordinator.data:
2024-11-24 22:49:11 +03:00
return self._sanitize_attributes(attributes)
2024-11-24 02:20:29 +03:00
2024-11-24 17:55:39 +03:00
data = self.coordinator.data
2024-11-24 20:12:03 +03:00
# Basic attributes
2024-11-24 17:55:39 +03:00
for attr in [
ATTR_TOTAL_RESPONSES,
ATTR_AVG_RESPONSE_TIME,
ATTR_LAST_REQUEST_TIME,
ATTR_IS_RATE_LIMITED,
ATTR_IS_MAINTENANCE,
ATTR_API_VERSION,
ATTR_ENDPOINT_STATUS,
ATTR_PERFORMANCE_METRICS,
ATTR_HISTORY_SIZE,
ATTR_UPTIME,
]:
value = data.get(attr)
if value is not None:
attributes[attr] = value
2024-11-24 20:12:03 +03:00
# Metrics
2024-11-24 17:55:39 +03:00
metrics = data.get("metrics", {})
if isinstance(metrics, dict):
for metric in [
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-24 17:09:23 +03:00
]:
2024-11-24 17:55:39 +03:00
value = metrics.get(metric)
if value is not None:
attributes[metric] = value
2024-11-24 17:27:49 +03:00
2024-11-24 20:12:03 +03:00
# Last response
2024-11-24 17:55:39 +03:00
last_response = data.get("last_response", {})
if isinstance(last_response, dict):
attributes[ATTR_RESPONSE] = last_response.get("response", "")
attributes[ATTR_QUESTION] = last_response.get("question", "")
2024-11-24 17:09:23 +03:00
2024-11-24 22:49:11 +03:00
return self._sanitize_attributes(attributes)
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()
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."""
2024-11-24 17:55:39 +03:00
if not self.coordinator.data:
2024-11-24 17:27:49 +03:00
self._current_state = STATE_DISCONNECTED
self.async_write_ha_state()
return
try:
data = self.coordinator.data
2024-11-24 20:12:03 +03:00
# Update state
self._is_processing = data.get("is_processing", False)
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:
self._current_state = STATE_READY
2024-11-24 20:12:03 +03:00
# Update history
history = data.get("conversation_history", [])
if isinstance(history, list):
self._conversation_history = history
# Update system prompt
system_prompt = data.get("system_prompt")
if system_prompt is not None:
self._system_prompt = system_prompt
# Update metrics
2024-11-24 17:55:39 +03:00
metrics = data.get("metrics", {})
if isinstance(metrics, dict):
self._error_count = metrics.get("total_errors", self._error_count)
2024-11-24 17:27:49 +03:00
self._last_update = data.get("last_update")
except Exception as err:
_LOGGER.error("Error handling update: %s", err, exc_info=True)
self._current_state = STATE_ERROR
self._last_error = str(err)
self._error_count += 1
2024-11-20 01:02:27 +03:00
self.async_write_ha_state()