From 094062773a39ad0128efb64e88066771ac4d94dd Mon Sep 17 00:00:00 2001 From: SMKRV Date: Mon, 25 Nov 2024 16:18:54 +0300 Subject: [PATCH] Release v2.0.0 --- custom_components/ha_text_ai/__init__.py | 2 +- custom_components/ha_text_ai/config_flow.py | 5 +- custom_components/ha_text_ai/const.py | 1 - custom_components/ha_text_ai/coordinator.py | 5 +- custom_components/ha_text_ai/sensor.py | 10 +- custom_components/ha_text_ai/services.yaml | 111 +++----------------- structure.md | 3 +- 7 files changed, 22 insertions(+), 115 deletions(-) diff --git a/custom_components/ha_text_ai/__init__.py b/custom_components/ha_text_ai/__init__.py index 47386cd..d99090f 100644 --- a/custom_components/ha_text_ai/__init__.py +++ b/custom_components/ha_text_ai/__init__.py @@ -250,7 +250,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: context_messages=entry.data.get( CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES - ), + ), ) coordinator.data = coordinator._initial_state.copy() diff --git a/custom_components/ha_text_ai/config_flow.py b/custom_components/ha_text_ai/config_flow.py index 740bb8b..b87f3d4 100644 --- a/custom_components/ha_text_ai/config_flow.py +++ b/custom_components/ha_text_ai/config_flow.py @@ -107,17 +107,14 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): errors=self._errors ) - # Проверка уникальности имени instance_name = user_input[CONF_NAME] await self._async_validate_name(instance_name) if self._errors: return await self.async_step_provider() - # Проверка API подключения if not await self._async_validate_api(user_input): return await self.async_step_provider() - # Создание записи конфигурации return await self._create_entry(user_input) async def _async_validate_name(self, name: str) -> bool: @@ -242,7 +239,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow): CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES ) - ): vol.All( + ): vol.All( vol.Coerce(int), vol.Range(min=1, max=20) ), diff --git a/custom_components/ha_text_ai/const.py b/custom_components/ha_text_ai/const.py index da00c6e..f423885 100644 --- a/custom_components/ha_text_ai/const.py +++ b/custom_components/ha_text_ai/const.py @@ -149,7 +149,6 @@ SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({ vol.Coerce(int), vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS) ), - # Добавить опциональный параметр контекста vol.Optional("context_messages"): vol.All( vol.Coerce(int), vol.Range(min=1, max=20) diff --git a/custom_components/ha_text_ai/coordinator.py b/custom_components/ha_text_ai/coordinator.py index 59facba..9344e5f 100644 --- a/custom_components/ha_text_ai/coordinator.py +++ b/custom_components/ha_text_ai/coordinator.py @@ -83,11 +83,10 @@ class HATextAICoordinator(DataUpdateCoordinator): update_interval_td = timedelta(seconds=update_interval) - # Добавляем name в вызов родительского конструктора super().__init__( hass, _LOGGER, - name=instance_name, # Передаем имя экземпляра + name=instance_name, update_interval=update_interval_td, ) @@ -166,12 +165,10 @@ class HATextAICoordinator(DataUpdateCoordinator): return STATE_READY def _calculate_context_tokens(self, messages: List[Dict[str, str]]) -> int: - """Приблизительный подсчет токенов в контексте.""" try: if self.is_anthropic and hasattr(self.client, 'count_tokens'): return sum(self.client.count_tokens(msg['content']) for msg in messages) - # Простая эвристика: 1 токен примерно на 4 символа return sum(len(msg['content']) // 4 for msg in messages) except Exception as e: _LOGGER.warning(f"Error calculating context tokens: {e}") diff --git a/custom_components/ha_text_ai/sensor.py b/custom_components/ha_text_ai/sensor.py index 83dafaa..e18fd2f 100644 --- a/custom_components/ha_text_ai/sensor.py +++ b/custom_components/ha_text_ai/sensor.py @@ -73,7 +73,7 @@ async def async_setup_entry( coordinator = hass.data[DOMAIN][entry.entry_id] 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) async_add_entities([sensor], True) @@ -96,18 +96,15 @@ class HATextAISensor(CoordinatorEntity, SensorEntity): self._conversation_history = [] 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._attr_unique_id = f"{config_entry.entry_id}" - # Entity description без дублирования self.entity_description = SensorEntityDescription( key=f"ha_text_ai_{self._instance_name}", entity_registry_enabled_default=True, ) - # State tracking self._current_state = STATE_INITIALIZING self._error_count = 0 self._last_error = None @@ -116,7 +113,6 @@ class HATextAISensor(CoordinatorEntity, SensorEntity): self._last_response = {} self._metrics = {} - # Device info model = config_entry.data.get(CONF_MODEL, "Unknown") api_provider = config_entry.data.get(CONF_API_PROVIDER, "Unknown") @@ -128,7 +124,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity): sw_version="1.0.0", ) - _LOGGER.debug(f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}") + _LOGGER.debug(f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}") @property def available(self) -> bool: diff --git a/custom_components/ha_text_ai/services.yaml b/custom_components/ha_text_ai/services.yaml index e8c264b..b69c734 100644 --- a/custom_components/ha_text_ai/services.yaml +++ b/custom_components/ha_text_ai/services.yaml @@ -20,7 +20,7 @@ ask_question: selector: text: multiline: true - type: text + type: text system_prompt: name: System Prompt @@ -30,11 +30,23 @@ ask_question: text: 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: name: Model description: "Select AI model to use (optional, overrides default setting)" required: false - selector: + selector: text: multiline: false @@ -61,98 +73,3 @@ ask_question: max: 4096 step: 1 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 diff --git a/structure.md b/structure.md index da8c3c3..7fc498a 100644 --- a/structure.md +++ b/structure.md @@ -14,5 +14,6 @@ ha-text-ai/ │ └── strings/ ├── en.json - └──ru.json + ├── de.json + └── ru.json ```