mirror of
https://github.com/smkrv/ha-text-ai.git
synced 2026-07-29 09:53:56 +08:00
Release v2.0.0
This commit is contained in:
@@ -252,6 +252,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
temperature=entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
|
temperature=entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
|
||||||
max_tokens=entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
|
max_tokens=entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
|
||||||
request_interval=float(entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)),
|
request_interval=float(entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)),
|
||||||
|
name=entry.title, # Передаем имя из конфигурации
|
||||||
session=session,
|
session=session,
|
||||||
is_anthropic=is_anthropic
|
is_anthropic=is_anthropic
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import voluptuous as vol
|
|||||||
import aiohttp
|
import aiohttp
|
||||||
|
|
||||||
from homeassistant import config_entries
|
from homeassistant import config_entries
|
||||||
from homeassistant.const import CONF_API_KEY, CONF_NAME
|
from homeassistant.const import CONF_API_KEY
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
from homeassistant.data_entry_flow import FlowResult
|
from homeassistant.data_entry_flow import FlowResult
|
||||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||||
@@ -41,18 +41,13 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
|
|
||||||
VERSION = 1
|
VERSION = 1
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
"""Initialize the config flow."""
|
|
||||||
self._provider = None
|
|
||||||
|
|
||||||
async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||||
"""Handle the initial step."""
|
"""Handle the initial step."""
|
||||||
if user_input is None:
|
if user_input is None:
|
||||||
return self._show_provider_selection()
|
return self._show_provider_selection()
|
||||||
|
|
||||||
if "provider" in user_input:
|
if "provider" in user_input:
|
||||||
self._provider = user_input["provider"]
|
return self._show_provider_config(user_input["provider"])
|
||||||
return self._show_provider_config(self._provider)
|
|
||||||
|
|
||||||
return await self._process_configuration(user_input)
|
return await self._process_configuration(user_input)
|
||||||
|
|
||||||
@@ -70,10 +65,12 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
"""Show configuration screen for selected provider."""
|
"""Show configuration screen for selected provider."""
|
||||||
default_endpoint = DEFAULT_OPENAI_ENDPOINT if provider == API_PROVIDER_OPENAI else DEFAULT_ANTHROPIC_ENDPOINT
|
default_endpoint = DEFAULT_OPENAI_ENDPOINT if provider == API_PROVIDER_OPENAI else DEFAULT_ANTHROPIC_ENDPOINT
|
||||||
|
|
||||||
|
default_name = f"HA Text AI {len(self._async_current_entries()) + 1}"
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="user",
|
step_id="user",
|
||||||
data_schema=vol.Schema({
|
data_schema=vol.Schema({
|
||||||
vol.Required(CONF_NAME): str, # Добавлено поле имени
|
vol.Required("name", default=default_name): str,
|
||||||
vol.Required(CONF_API_PROVIDER): vol.In([provider]),
|
vol.Required(CONF_API_PROVIDER): vol.In([provider]),
|
||||||
vol.Required(CONF_API_KEY): str,
|
vol.Required(CONF_API_KEY): str,
|
||||||
vol.Required(CONF_MODEL, default=DEFAULT_MODEL): str,
|
vol.Required(CONF_MODEL, default=DEFAULT_MODEL): str,
|
||||||
@@ -99,10 +96,8 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
errors = {}
|
errors = {}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Создаем уникальный идентификатор на основе имени и эндпоинта
|
# Принудительная очистка существующих записей с тем же API-ключом
|
||||||
unique_id = f"{user_input[CONF_NAME]}_{user_input[CONF_API_ENDPOINT]}"
|
await self._async_cleanup_existing_entries(user_input[CONF_API_KEY])
|
||||||
await self.async_set_unique_id(unique_id)
|
|
||||||
self._abort_if_unique_id_configured()
|
|
||||||
|
|
||||||
session = async_get_clientsession(self.hass)
|
session = async_get_clientsession(self.hass)
|
||||||
|
|
||||||
@@ -112,7 +107,7 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Adjust headers based on provider
|
# Adjust headers and endpoint based on provider
|
||||||
if user_input[CONF_API_PROVIDER] == API_PROVIDER_ANTHROPIC:
|
if user_input[CONF_API_PROVIDER] == API_PROVIDER_ANTHROPIC:
|
||||||
headers = {
|
headers = {
|
||||||
"x-api-key": user_input[CONF_API_KEY],
|
"x-api-key": user_input[CONF_API_KEY],
|
||||||
@@ -132,8 +127,12 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
errors["base"] = "cannot_connect"
|
errors["base"] = "cannot_connect"
|
||||||
|
|
||||||
if not errors:
|
if not errors:
|
||||||
|
# Генерируем уникальный идентификатор на основе ключа
|
||||||
|
await self.async_set_unique_id(user_input[CONF_API_KEY])
|
||||||
|
self._abort_if_unique_id_configured()
|
||||||
|
|
||||||
return self.async_create_entry(
|
return self.async_create_entry(
|
||||||
title=user_input[CONF_NAME],
|
title=user_input.get("name", f"HA Text AI ({user_input[CONF_API_PROVIDER]})"), # Используем введенное имя
|
||||||
data=user_input
|
data=user_input
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -145,8 +144,9 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="user",
|
step_id="user",
|
||||||
data_schema=vol.Schema({
|
data_schema=vol.Schema({
|
||||||
|
vol.Required("name", default=user_input.get("name", f"HA Text AI {len(self._async_current_entries()) + 1}")): str,
|
||||||
vol.Required(CONF_API_PROVIDER): vol.In([user_input[CONF_API_PROVIDER]]),
|
vol.Required(CONF_API_PROVIDER): vol.In([user_input[CONF_API_PROVIDER]]),
|
||||||
vol.Required(CONF_API_KEY, default=user_input.get(CONF_API_KEY, "")): str,
|
vol.Required(CONF_API_KEY): str,
|
||||||
vol.Required(CONF_MODEL, default=user_input.get(CONF_MODEL, DEFAULT_MODEL)): str,
|
vol.Required(CONF_MODEL, default=user_input.get(CONF_MODEL, DEFAULT_MODEL)): str,
|
||||||
vol.Optional(CONF_API_ENDPOINT, default=user_input.get(CONF_API_ENDPOINT,
|
vol.Optional(CONF_API_ENDPOINT, default=user_input.get(CONF_API_ENDPOINT,
|
||||||
DEFAULT_OPENAI_ENDPOINT if user_input[CONF_API_PROVIDER] == API_PROVIDER_OPENAI
|
DEFAULT_OPENAI_ENDPOINT if user_input[CONF_API_PROVIDER] == API_PROVIDER_OPENAI
|
||||||
@@ -168,19 +168,19 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
errors=errors
|
errors=errors
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _async_cleanup_existing_entries(self, api_key):
|
async def _async_cleanup_existing_entries(self, api_key):
|
||||||
"""Cleanup existing entries with the same API key."""
|
"""Cleanup existing entries with the same API key."""
|
||||||
existing_entries = [
|
existing_entries = [
|
||||||
entry for entry in self.hass.config_entries.async_entries(DOMAIN)
|
entry for entry in self.hass.config_entries.async_entries(DOMAIN)
|
||||||
if entry.data.get(CONF_API_KEY) == api_key
|
if entry.data.get(CONF_API_KEY) == api_key
|
||||||
]
|
]
|
||||||
|
|
||||||
for entry in existing_entries:
|
for entry in existing_entries:
|
||||||
try:
|
try:
|
||||||
await self.hass.config_entries.async_remove(entry.entry_id)
|
await self.hass.config_entries.async_remove(entry.entry_id)
|
||||||
_LOGGER.info(f"Removed existing entry with ID: {entry.entry_id}")
|
_LOGGER.info(f"Removed existing entry with ID: {entry.entry_id}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_LOGGER.warning(f"Could not remove existing entry: {e}")
|
_LOGGER.warning(f"Could not remove existing entry: {e}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@callback
|
@callback
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ from homeassistant.helpers import config_validation as cv
|
|||||||
# Domain and platforms
|
# Domain and platforms
|
||||||
DOMAIN: Final = "ha_text_ai"
|
DOMAIN: Final = "ha_text_ai"
|
||||||
PLATFORMS: Final = [Platform.SENSOR]
|
PLATFORMS: Final = [Platform.SENSOR]
|
||||||
|
CONF_NAME = "name"
|
||||||
|
DEFAULT_NAME = "HA Text AI"
|
||||||
|
|
||||||
# New constants for providers
|
# New constants for providers
|
||||||
CONF_API_PROVIDER: Final = "api_provider"
|
CONF_API_PROVIDER: Final = "api_provider"
|
||||||
|
|||||||
@@ -38,16 +38,17 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
request_interval: float,
|
request_interval: float,
|
||||||
|
name: str,
|
||||||
session: Optional[Any] = None,
|
session: Optional[Any] = None,
|
||||||
is_anthropic: bool = False,
|
is_anthropic: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
super().__init__(
|
super().__init__(
|
||||||
hass,
|
hass,
|
||||||
_LOGGER,
|
_LOGGER,
|
||||||
name=DOMAIN,
|
name=name,
|
||||||
update_interval=timedelta(seconds=float(request_interval)),
|
update_interval=timedelta(seconds=float(request_interval)),
|
||||||
)
|
)
|
||||||
|
self._name = name
|
||||||
self._validate_params(api_key, temperature, max_tokens)
|
self._validate_params(api_key, temperature, max_tokens)
|
||||||
self._entity_id = None
|
self._entity_id = None
|
||||||
self.api_key = api_key
|
self.api_key = api_key
|
||||||
@@ -512,6 +513,11 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
"""Set entity ID."""
|
"""Set entity ID."""
|
||||||
self._entity_id = value
|
self._entity_id = value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
"""Get coordinator name."""
|
||||||
|
return self._name
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def performance_metrics(self) -> Dict[str, Any]:
|
def performance_metrics(self) -> Dict[str, Any]:
|
||||||
"""Return current performance metrics."""
|
"""Return current performance metrics."""
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
|||||||
from homeassistant.helpers.typing import StateType
|
from homeassistant.helpers.typing import StateType
|
||||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||||
from homeassistant.util import dt as dt_util
|
from homeassistant.util import dt as dt_util
|
||||||
|
from homeassistant.util import slugify
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
@@ -62,31 +63,39 @@ async def async_setup_entry(
|
|||||||
class HATextAISensor(CoordinatorEntity, SensorEntity):
|
class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||||
"""HA text AI Sensor."""
|
"""HA text AI Sensor."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
coordinator: HATextAICoordinator,
|
coordinator: HATextAICoordinator,
|
||||||
config_entry: ConfigEntry,
|
config_entry: ConfigEntry,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize the sensor."""
|
"""Initialize the sensor."""
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
self._config_entry = config_entry
|
self._config_entry = config_entry
|
||||||
|
|
||||||
self._attr_unique_id = f"{config_entry.entry_id}_sensor"
|
# Используем имя из конфигурации
|
||||||
self.entity_id = "sensor.ha_text_ai"
|
self._name = config_entry.title
|
||||||
self._attr_name = "HA Text AI"
|
|
||||||
|
|
||||||
self._current_state = STATE_INITIALIZING
|
# Создаем уникальный ID используя имя
|
||||||
self._error_count = 0
|
self._attr_unique_id = f"{config_entry.entry_id}_{slugify(self._name)}"
|
||||||
self._last_error = None
|
|
||||||
|
|
||||||
# Девайс инфо
|
# Создаем entity_id используя имя
|
||||||
self._attr_device_info = {
|
self.entity_id = f"sensor.ha_text_ai_{slugify(self._name)}"
|
||||||
"identifiers": {(DOMAIN, self._attr_unique_id)},
|
|
||||||
"name": "HA Text AI",
|
# Устанавливаем отображаемое имя
|
||||||
"manufacturer": "Community",
|
self._attr_name = self._name
|
||||||
"model": f"{coordinator.model} ({self._config_entry.data.get(CONF_API_PROVIDER, 'Unknown')} provider)",
|
|
||||||
"sw_version": coordinator.api_version,
|
self._current_state = STATE_INITIALIZING
|
||||||
}
|
self._error_count = 0
|
||||||
|
self._last_error = None
|
||||||
|
|
||||||
|
# Обновляем device_info с использованием имени
|
||||||
|
self._attr_device_info = {
|
||||||
|
"identifiers": {(DOMAIN, self._attr_unique_id)},
|
||||||
|
"name": self._name, # Используем имя из конфигурации
|
||||||
|
"manufacturer": "Community",
|
||||||
|
"model": f"{coordinator.model} ({self._config_entry.data.get(CONF_API_PROVIDER, 'Unknown')} provider)",
|
||||||
|
"sw_version": coordinator.api_version,
|
||||||
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def icon(self) -> str:
|
def icon(self) -> str:
|
||||||
|
|||||||
@@ -12,11 +12,12 @@
|
|||||||
"max_tokens": "Maximum response length (1-4096 tokens)",
|
"max_tokens": "Maximum response length (1-4096 tokens)",
|
||||||
"api_endpoint": "Custom API endpoint URL (optional)",
|
"api_endpoint": "Custom API endpoint URL (optional)",
|
||||||
"request_interval": "Minimum time between requests in seconds (min: 0.1)",
|
"request_interval": "Minimum time between requests in seconds (min: 0.1)",
|
||||||
"name": "Integration name"
|
"name": "Name for this integration instance (e.g., 'GPT Assistant', 'Claude Helper')"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"error": {
|
"error": {
|
||||||
|
"invalid_name": "Invalid integration name",
|
||||||
"invalid_auth": "Authentication failed - check your API key",
|
"invalid_auth": "Authentication failed - check your API key",
|
||||||
"invalid_api_key": "Invalid API key - please verify your credentials",
|
"invalid_api_key": "Invalid API key - please verify your credentials",
|
||||||
"cannot_connect": "Connection failed - check endpoint and network status",
|
"cannot_connect": "Connection failed - check endpoint and network status",
|
||||||
@@ -71,7 +72,15 @@
|
|||||||
"entity": {
|
"entity": {
|
||||||
"sensor": {
|
"sensor": {
|
||||||
"ha_text_ai": {
|
"ha_text_ai": {
|
||||||
"name": "HA Text AI"
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"initializing": "Initializing",
|
||||||
|
"ready": "Ready",
|
||||||
|
"processing": "Processing",
|
||||||
|
"error": "Error",
|
||||||
|
"disconnected": "Disconnected",
|
||||||
|
"rate_limited": "Rate Limited"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user