Release v2.0.0

This commit is contained in:
SMKRV
2024-11-25 16:18:54 +03:00
parent 4cd95813bc
commit 094062773a
7 changed files with 22 additions and 115 deletions
@@ -107,17 +107,14 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors=self._errors errors=self._errors
) )
# Проверка уникальности имени
instance_name = user_input[CONF_NAME] instance_name = user_input[CONF_NAME]
await self._async_validate_name(instance_name) await self._async_validate_name(instance_name)
if self._errors: if self._errors:
return await self.async_step_provider() return await self.async_step_provider()
# Проверка API подключения
if not await self._async_validate_api(user_input): if not await self._async_validate_api(user_input):
return await self.async_step_provider() return await self.async_step_provider()
# Создание записи конфигурации
return await self._create_entry(user_input) return await self._create_entry(user_input)
async def _async_validate_name(self, name: str) -> bool: async def _async_validate_name(self, name: str) -> bool:
-1
View File
@@ -149,7 +149,6 @@ SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
vol.Coerce(int), vol.Coerce(int),
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS) vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
), ),
# Добавить опциональный параметр контекста
vol.Optional("context_messages"): vol.All( vol.Optional("context_messages"): vol.All(
vol.Coerce(int), vol.Coerce(int),
vol.Range(min=1, max=20) vol.Range(min=1, max=20)
+1 -4
View File
@@ -83,11 +83,10 @@ class HATextAICoordinator(DataUpdateCoordinator):
update_interval_td = timedelta(seconds=update_interval) update_interval_td = timedelta(seconds=update_interval)
# Добавляем name в вызов родительского конструктора
super().__init__( super().__init__(
hass, hass,
_LOGGER, _LOGGER,
name=instance_name, # Передаем имя экземпляра name=instance_name,
update_interval=update_interval_td, update_interval=update_interval_td,
) )
@@ -166,12 +165,10 @@ class HATextAICoordinator(DataUpdateCoordinator):
return STATE_READY return STATE_READY
def _calculate_context_tokens(self, messages: List[Dict[str, str]]) -> int: def _calculate_context_tokens(self, messages: List[Dict[str, str]]) -> int:
"""Приблизительный подсчет токенов в контексте."""
try: try:
if self.is_anthropic and hasattr(self.client, 'count_tokens'): if self.is_anthropic and hasattr(self.client, 'count_tokens'):
return sum(self.client.count_tokens(msg['content']) for msg in messages) return sum(self.client.count_tokens(msg['content']) for msg in messages)
# Простая эвристика: 1 токен примерно на 4 символа
return sum(len(msg['content']) // 4 for msg in messages) return sum(len(msg['content']) // 4 for msg in messages)
except Exception as e: except Exception as e:
_LOGGER.warning(f"Error calculating context tokens: {e}") _LOGGER.warning(f"Error calculating context tokens: {e}")
+2 -6
View File
@@ -73,7 +73,7 @@ async def async_setup_entry(
coordinator = hass.data[DOMAIN][entry.entry_id] coordinator = hass.data[DOMAIN][entry.entry_id]
instance_name = coordinator.instance_name instance_name = coordinator.instance_name
_LOGGER.debug(f"Setting up sensor with instance: {instance_name}") # Убрал префикс "HA Text AI" _LOGGER.debug(f"Setting up sensor with instance: {instance_name}")
sensor = HATextAISensor(coordinator, entry) sensor = HATextAISensor(coordinator, entry)
async_add_entities([sensor], True) async_add_entities([sensor], True)
@@ -96,18 +96,15 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
self._conversation_history = [] self._conversation_history = []
self._system_prompt = None self._system_prompt = None
# Убираем дублирование префикса self._attr_name = f"HA Text AI {self._instance_name}"
self._attr_name = f"HA Text AI {self._instance_name}" # Устанавливаем имя только здесь
self.entity_id = f"sensor.ha_text_ai_{slugify(self._instance_name)}" self.entity_id = f"sensor.ha_text_ai_{slugify(self._instance_name)}"
self._attr_unique_id = f"{config_entry.entry_id}" self._attr_unique_id = f"{config_entry.entry_id}"
# Entity description без дублирования
self.entity_description = SensorEntityDescription( self.entity_description = SensorEntityDescription(
key=f"ha_text_ai_{self._instance_name}", key=f"ha_text_ai_{self._instance_name}",
entity_registry_enabled_default=True, entity_registry_enabled_default=True,
) )
# State tracking
self._current_state = STATE_INITIALIZING self._current_state = STATE_INITIALIZING
self._error_count = 0 self._error_count = 0
self._last_error = None self._last_error = None
@@ -116,7 +113,6 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
self._last_response = {} self._last_response = {}
self._metrics = {} self._metrics = {}
# Device info
model = config_entry.data.get(CONF_MODEL, "Unknown") model = config_entry.data.get(CONF_MODEL, "Unknown")
api_provider = config_entry.data.get(CONF_API_PROVIDER, "Unknown") api_provider = config_entry.data.get(CONF_API_PROVIDER, "Unknown")
+12 -95
View File
@@ -30,6 +30,18 @@ ask_question:
text: text:
multiline: true multiline: true
context_messages:
name: Context Messages
description: Number of previous messages to include in context (1-20)
required: false
default: 5
selector:
number:
min: 1
max: 20
step: 1
mode: box
model: model:
name: Model name: Model
description: "Select AI model to use (optional, overrides default setting)" description: "Select AI model to use (optional, overrides default setting)"
@@ -61,98 +73,3 @@ ask_question:
max: 4096 max: 4096
step: 1 step: 1
mode: box mode: box
clear_history:
name: Clear History
description: Delete all stored questions and responses from the conversation history
fields:
instance:
name: Instance
description: Name of the HA Text AI instance to clear history for
required: true
selector:
entity:
integration: ha_text_ai
domain: sensor
get_history:
name: Get History
description: Retrieve conversation history with optional filtering and sorting
fields:
instance:
name: Instance
description: Name of the HA Text AI instance to get history from
required: true
selector:
entity:
integration: ha_text_ai
domain: sensor
limit:
name: Limit
description: Number of conversations to return (1-100)
required: false
default: 10
selector:
number:
min: 1
max: 100
step: 1
mode: box
filter_model:
name: Filter Model
description: Filter conversations by specific AI model
required: false
selector:
text:
multiline: false
start_date:
name: Start Date
description: Filter conversations starting from this date/time
required: false
selector:
datetime:
include_metadata:
name: Include Metadata
description: Include additional information like tokens used, response time, etc.
required: false
default: false
selector:
boolean:
sort_order:
name: Sort Order
description: Sort order for results (newest or oldest first)
required: false
default: "desc"
selector:
select:
options:
- label: "Newest First"
value: "desc"
- label: "Oldest First"
value: "asc"
set_system_prompt:
name: Set System Prompt
description: Set default system behavior instructions for all future conversations
fields:
instance:
name: Instance
description: Name of the HA Text AI instance to set system prompt for
required: true
selector:
entity:
integration: ha_text_ai
domain: sensor
prompt:
name: System Prompt
description: Instructions that define how the AI should behave and respond
required: true
selector:
text:
multiline: true
+2 -1
View File
@@ -14,5 +14,6 @@ ha-text-ai/
└── strings/ └── strings/
├── en.json ├── en.json
──ru.json ── de.json
└── ru.json
``` ```