Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82e1f0c4f9 | ||
|
|
5c16eee6e4 | ||
|
|
e988d445a4 | ||
|
|
f9bfb9ab7f | ||
|
|
92dd1bc110 | ||
|
|
17d547325a | ||
|
|
b8cb70217c | ||
|
|
530d04f25d | ||
|
|
b71083b9bf | ||
|
|
f9f7d10f7f | ||
|
|
9f7cb20621 | ||
|
|
6fc3b23365 | ||
|
|
15c717fcb0 | ||
|
|
be06fddce1 | ||
|
|
5f0bd861a7 | ||
|
|
428aee46c8 | ||
|
|
561bcf0b1d | ||
|
|
2b1e42c665 | ||
|
|
2d68f29ab5 | ||
|
|
19d4a93bca | ||
|
|
fb75c5f44e | ||
|
|
52af987985 | ||
|
|
162a30acdd | ||
|
|
898a6fc638 | ||
|
|
38e2362be4 | ||
|
|
cea912d0b5 | ||
|
|
5ec00040c2 | ||
|
|
8d28fc4a0d | ||
|
|
7cc6587724 | ||
|
|
bacf76e0a9 | ||
|
|
f86c7bfd57 | ||
|
|
2aaf340575 | ||
|
|
bae11ba85c | ||
|
|
9eb7d8912c |
@@ -38,3 +38,4 @@ Thumbs.db
|
|||||||
*.psd
|
*.psd
|
||||||
*.zip
|
*.zip
|
||||||
*.txt
|
*.txt
|
||||||
|
*.pdf
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our
|
||||||
|
community a harassment-free experience for everyone, regardless of age, body
|
||||||
|
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||||
|
identity and expression, level of experience, education, socio-economic status,
|
||||||
|
nationality, personal appearance, race, religion, or sexual identity
|
||||||
|
and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||||
|
diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our
|
||||||
|
community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||||
|
and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the
|
||||||
|
overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or
|
||||||
|
advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email
|
||||||
|
address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a
|
||||||
|
professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of
|
||||||
|
acceptable behavior and will take appropriate and fair corrective action in
|
||||||
|
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||||
|
or harmful.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject
|
||||||
|
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||||
|
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||||
|
decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when
|
||||||
|
an individual is officially representing the community in public spaces.
|
||||||
|
Examples of representing our community include using an official e-mail address,
|
||||||
|
posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported to the community leaders responsible for enforcement at
|
||||||
|
issue tracker.
|
||||||
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining
|
||||||
|
the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||||
|
unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing
|
||||||
|
clarity around the nature of the violation and an explanation of why the
|
||||||
|
behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series
|
||||||
|
of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No
|
||||||
|
interaction with the people involved, including unsolicited interaction with
|
||||||
|
those enforcing the Code of Conduct, for a specified period of time. This
|
||||||
|
includes avoiding interactions in community spaces as well as external channels
|
||||||
|
like social media. Violating these terms may lead to a temporary or
|
||||||
|
permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including
|
||||||
|
sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public
|
||||||
|
communication with the community for a specified period of time. No public or
|
||||||
|
private interaction with the people involved, including unsolicited interaction
|
||||||
|
with those enforcing the Code of Conduct, is allowed during this period.
|
||||||
|
Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community
|
||||||
|
standards, including sustained inappropriate behavior, harassment of an
|
||||||
|
individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within
|
||||||
|
the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||||
|
version 2.0, available at
|
||||||
|
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||||
|
enforcement ladder](https://github.com/mozilla/diversity).
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at
|
||||||
|
https://www.contributor-covenant.org/faq. Translations are available at
|
||||||
|
https://www.contributor-covenant.org/translations.
|
||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)   
|
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)
|
||||||
|
       
|
||||||
|
|
||||||
<img src="https://github.com/smkrv/ha-text-ai/blob/e03b5315c2cc7b489a6e1175da728075275ed614/misc/icons/logo.png" alt="HA Text AI" style="width: 80%; max-width: 640px; max-height: 150px; aspect-ratio: 2/1; object-fit: contain;"/>
|
|
||||||
|
<img src="https://github.com/smkrv/ha-text-ai/blob/15c717fcb0204bf4a0d4b4b4c6f0bb93e9f6c9a9/custom_components/ha_text_ai/icons/logo%402x.png" alt="HA Text AI" style="width: 50%; max-width: 256px; max-height: 128px; aspect-ratio: 2/1; object-fit: contain;"/>
|
||||||
|
|
||||||
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
||||||
</div>
|
</div>
|
||||||
@@ -17,13 +19,11 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
---
|
---
|
||||||
|
|
||||||
> [!IMPORTANT]
|
> [!IMPORTANT]
|
||||||
> 🚧 BETA VERSION
|
|
||||||
> Expect: potential bugs, frequent changes, incomplete features.
|
|
||||||
> 🤝 Community Driven
|
> 🤝 Community Driven
|
||||||
>
|
>
|
||||||
> <a href="https://community.home-assistant.io/t/ha-text-ai-transforming-home-automation-with-multi-provider-language-models/799741"><img src="https://img.shields.io/badge/Community-blue?style=for-the-badge&logo=homeassistant&logoColor=white&color=03a9f4"/></a>
|
> <a href="https://community.home-assistant.io/t/ha-text-ai-transforming-home-automation-with-multi-provider-language-models/799741"><img src="https://img.shields.io/badge/Community-blue?style=for-the-badge&logo=homeassistant&logoColor=white&color=03a9f4"/></a>
|
||||||
>
|
>
|
||||||
> [Screenshots](misc/screenshots/screenshot.jpg)
|
> [Screenshots](assets/images/screenshots/screenshot.jpg)
|
||||||
|
|
||||||
## 🌟 Features
|
## 🌟 Features
|
||||||
|
|
||||||
@@ -89,6 +89,19 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
#### 🌐 Translations
|
||||||
|
|
||||||
|
| Code | Language | Status |
|
||||||
|
|------|----------|--------|
|
||||||
|
| 🇩🇪 de | Deutsch | Full |
|
||||||
|
| 🇬🇧 en | English | Primary |
|
||||||
|
| 🇪🇸 es | Español | Full |
|
||||||
|
| 🇮🇳 hi | हिन्दी | Full |
|
||||||
|
| 🇮🇹 it | Italiano | Full |
|
||||||
|
| 🇷🇺 ru | Русский | Full |
|
||||||
|
| 🇷🇸 sr | Српски | Full |
|
||||||
|
| 🇨🇳 zh | 中文 | Full |
|
||||||
|
|
||||||
## 📋 Prerequisites
|
## 📋 Prerequisites
|
||||||
|
|
||||||
- Home Assistant 2024.11 or later
|
- Home Assistant 2024.11 or later
|
||||||
@@ -96,6 +109,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
||||||
- Anthropic ([Get key](https://console.anthropic.com/))
|
- Anthropic ([Get key](https://console.anthropic.com/))
|
||||||
- OpenRouter ([Get key](https://openrouter.ai/keys))
|
- OpenRouter ([Get key](https://openrouter.ai/keys))
|
||||||
|
- Any OpenAI-compatible API provider
|
||||||
- Python 3.9 or newer
|
- Python 3.9 or newer
|
||||||
- Stable internet connection
|
- Stable internet connection
|
||||||
|
|
||||||
@@ -136,6 +150,7 @@ To be compatible, a provider should support:
|
|||||||
- JSON request/response format
|
- JSON request/response format
|
||||||
- Standard authentication method
|
- Standard authentication method
|
||||||
- Similar model parameter handling
|
- Similar model parameter handling
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
## ⚡ Installation
|
## ⚡ Installation
|
||||||
@@ -151,6 +166,8 @@ To be compatible, a provider should support:
|
|||||||
7. Click "Download"
|
7. Click "Download"
|
||||||
8. Restart Home Assistant
|
8. Restart Home Assistant
|
||||||
|
|
||||||
|
Note: Also Integration has been submitted to HACS store and is currently pending review in [pull request #2896](https://github.com/hacs/default/pull/2896).
|
||||||
|
|
||||||
### Manual Installation
|
### Manual Installation
|
||||||
1. Download the latest release
|
1. Download the latest release
|
||||||
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
||||||
@@ -238,12 +255,14 @@ data:
|
|||||||
max_tokens: 500 # optional
|
max_tokens: 500 # optional
|
||||||
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
||||||
system_prompt: "You are a sleep optimization expert" # optional
|
system_prompt: "You are a sleep optimization expert" # optional
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
```
|
```
|
||||||
|
|
||||||
### set_system_prompt
|
### set_system_prompt
|
||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.set_system_prompt
|
service: ha_text_ai.set_system_prompt
|
||||||
data:
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
prompt: |
|
prompt: |
|
||||||
You are a home automation expert focused on:
|
You are a home automation expert focused on:
|
||||||
1. Energy efficiency
|
1. Energy efficiency
|
||||||
@@ -255,6 +274,8 @@ data:
|
|||||||
### clear_history
|
### clear_history
|
||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.clear_history
|
service: ha_text_ai.clear_history
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
```
|
```
|
||||||
|
|
||||||
### get_history
|
### get_history
|
||||||
@@ -263,6 +284,7 @@ service: ha_text_ai.get_history
|
|||||||
data:
|
data:
|
||||||
limit: 5 # optional
|
limit: 5 # optional
|
||||||
filter_model: "gpt-4o" # optional
|
filter_model: "gpt-4o" # optional
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
```
|
```
|
||||||
|
|
||||||
### 🏷️ HA Text AI Sensor Naming Convention
|
### 🏷️ HA Text AI Sensor Naming Convention
|
||||||
@@ -299,6 +321,7 @@ automation:
|
|||||||
- service: ha_text_ai.ask_question
|
- service: ha_text_ai.ask_question
|
||||||
data:
|
data:
|
||||||
question: "Home automation advice"
|
question: "Home automation advice"
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
- service: notify.mobile
|
- service: notify.mobile
|
||||||
data:
|
data:
|
||||||
message: >
|
message: >
|
||||||
@@ -384,7 +407,7 @@ automation:
|
|||||||
# Number of entries in current history file
|
# Number of entries in current history file
|
||||||
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
|
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
|
||||||
|
|
||||||
# Last few conversation entries (limited to 3 for performance)
|
# Last few conversation entries (limited to 1 for performance)
|
||||||
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
|
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -507,10 +530,11 @@ If you want to say thanks financially, you can send a small token of appreciatio
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
<div align="center"><img src="https://github.com/smkrv/ha-text-ai/blob/f2a41aaa2cd88adaf6929ba5f228205a315efdfa/custom_components/ha_text_ai/icons/dark_icon%402x.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div>
|
<div align="center"><img src="https://github.com/smkrv/ha-text-ai/blob/2aaf3405759eb2d97624834594e24ace896131df/assets/images/icons/footer_icon.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div>
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
Made with ❤️ and Claude 3.5 Sonnet for the Home Assistant Community
|
Made with ❤️ for the Home Assistant Community,
|
||||||
|
utilizing Claude 3.5 Sonnet, Gemini Pro 1.5, and Qwen 2.5 Coder 32B Instruct.
|
||||||
|
|
||||||
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
||||||
|
|
||||||
|
|||||||
|
After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 618 KiB After Width: | Height: | Size: 618 KiB |
|
Before Width: | Height: | Size: 923 KiB After Width: | Height: | Size: 923 KiB |
|
Before Width: | Height: | Size: 339 KiB After Width: | Height: | Size: 339 KiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.0 MiB |
@@ -6,6 +6,8 @@ Constants for the HA text AI integration.
|
|||||||
@github: https://github.com/smkrv/ha-text-ai
|
@github: https://github.com/smkrv/ha-text-ai
|
||||||
@source: https://github.com/smkrv/ha-text-ai
|
@source: https://github.com/smkrv/ha-text-ai
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
|
import json
|
||||||
from typing import Final
|
from typing import Final
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
from homeassistant.const import Platform, CONF_API_KEY, CONF_NAME
|
from homeassistant.const import Platform, CONF_API_KEY, CONF_NAME
|
||||||
@@ -25,6 +27,22 @@ API_PROVIDERS: Final = [
|
|||||||
API_PROVIDER_ANTHROPIC
|
API_PROVIDER_ANTHROPIC
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# Read version from manifest.json
|
||||||
|
MANIFEST_PATH = os.path.join(os.path.dirname(__file__), "manifest.json")
|
||||||
|
try:
|
||||||
|
with open(MANIFEST_PATH) as manifest_file:
|
||||||
|
manifest = json.load(manifest_file)
|
||||||
|
VERSION = manifest.get("version", "unknown")
|
||||||
|
except FileNotFoundError:
|
||||||
|
VERSION = "unknown"
|
||||||
|
_LOGGER.warning("manifest.json not found at %s", MANIFEST_PATH)
|
||||||
|
except json.JSONDecodeError as err:
|
||||||
|
VERSION = "unknown"
|
||||||
|
_LOGGER.error("Error decoding JSON from manifest.json: %s", err)
|
||||||
|
except Exception as err:
|
||||||
|
VERSION = "unknown"
|
||||||
|
_LOGGER.error("Error reading manifest.json: %s", err)
|
||||||
|
|
||||||
# Default endpoints
|
# Default endpoints
|
||||||
DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1"
|
DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1"
|
||||||
DEFAULT_ANTHROPIC_ENDPOINT: Final = "https://api.anthropic.com"
|
DEFAULT_ANTHROPIC_ENDPOINT: Final = "https://api.anthropic.com"
|
||||||
@@ -56,6 +74,8 @@ DEFAULT_NAME: Final = "HA Text AI"
|
|||||||
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||||
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
||||||
|
|
||||||
|
TRUNCATION_INDICATOR = " ... "
|
||||||
|
|
||||||
# Parameter constraints
|
# Parameter constraints
|
||||||
MIN_TEMPERATURE: Final = 0.0
|
MIN_TEMPERATURE: Final = 0.0
|
||||||
MAX_TEMPERATURE: Final = 2.0
|
MAX_TEMPERATURE: Final = 2.0
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ from .const import (
|
|||||||
ABSOLUTE_MAX_HISTORY_SIZE,
|
ABSOLUTE_MAX_HISTORY_SIZE,
|
||||||
MAX_ATTRIBUTE_SIZE,
|
MAX_ATTRIBUTE_SIZE,
|
||||||
MAX_HISTORY_FILE_SIZE,
|
MAX_HISTORY_FILE_SIZE,
|
||||||
|
TRUNCATION_INDICATOR,
|
||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
@@ -173,7 +174,6 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
|
|
||||||
self.available = True
|
self.available = True
|
||||||
self._state = STATE_READY
|
self._state = STATE_READY
|
||||||
self._conversation_history = [] # Full conversation history
|
|
||||||
|
|
||||||
self._start_time = dt_util.utcnow()
|
self._start_time = dt_util.utcnow()
|
||||||
|
|
||||||
@@ -404,17 +404,32 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
|
|
||||||
async def async_initialize_history_file(self) -> None:
|
async def async_initialize_history_file(self) -> None:
|
||||||
"""
|
"""
|
||||||
Asynchronously initialize history file.
|
Asynchronously initialize history file and load existing history.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Ensure directory exists first
|
|
||||||
await self._create_history_dir()
|
await self._create_history_dir()
|
||||||
|
|
||||||
# Initialize file
|
if await self._file_exists(self._history_file):
|
||||||
if not await self._file_exists(self._history_file):
|
# Load existing history
|
||||||
|
async with AsyncFileHandler(self._history_file, 'r') as f:
|
||||||
|
content = await f.read()
|
||||||
|
if content:
|
||||||
|
history = json.loads(content)
|
||||||
|
# Validate and load history
|
||||||
|
if isinstance(history, list):
|
||||||
|
self._conversation_history = history[-self.max_history_size:]
|
||||||
|
_LOGGER.debug(
|
||||||
|
f"Loaded {len(self._conversation_history)} history entries "
|
||||||
|
f"for {self.instance_name}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Create new history file
|
||||||
async with AsyncFileHandler(self._history_file, 'w') as f:
|
async with AsyncFileHandler(self._history_file, 'w') as f:
|
||||||
await f.write(json.dumps([]))
|
await f.write(json.dumps([]))
|
||||||
|
|
||||||
|
await self._check_history_size()
|
||||||
|
await self.async_update_ha_state()
|
||||||
|
|
||||||
_LOGGER.debug(f"History file initialized: {self._history_file}")
|
_LOGGER.debug(f"History file initialized: {self._history_file}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -504,6 +519,15 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
_LOGGER.error(f"Error writing history entry: {e}")
|
_LOGGER.error(f"Error writing history entry: {e}")
|
||||||
_LOGGER.debug(traceback.format_exc())
|
_LOGGER.debug(traceback.format_exc())
|
||||||
|
|
||||||
|
async def _check_history_size(self) -> None:
|
||||||
|
"""Verify and adjust history size if needed."""
|
||||||
|
if len(self._conversation_history) > self.max_history_size:
|
||||||
|
_LOGGER.warning(
|
||||||
|
f"History size ({len(self._conversation_history)}) exceeds "
|
||||||
|
f"maximum ({self.max_history_size}). Trimming..."
|
||||||
|
)
|
||||||
|
self._conversation_history = self._conversation_history[-self.max_history_size:]
|
||||||
|
|
||||||
async def _check_file_size(self, file_path: str) -> int:
|
async def _check_file_size(self, file_path: str) -> int:
|
||||||
"""
|
"""
|
||||||
Check file size asynchronously.
|
Check file size asynchronously.
|
||||||
@@ -624,15 +648,14 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
|
|
||||||
async def _async_update_data(self) -> Dict[str, Any]:
|
async def _async_update_data(self) -> Dict[str, Any]:
|
||||||
"""Update coordinator data with improved error handling and performance."""
|
"""Update coordinator data with improved error handling and performance."""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with asyncio.Semaphore(1):
|
async with asyncio.Semaphore(1):
|
||||||
current_state = self._get_current_state()
|
current_state = self._get_current_state()
|
||||||
|
|
||||||
limited_history = await self._get_limited_history()
|
# Get limited history with info
|
||||||
|
history_data = await self._get_limited_history()
|
||||||
|
|
||||||
metrics = await self._get_current_metrics()
|
metrics = await self._get_current_metrics()
|
||||||
|
|
||||||
if metrics is None:
|
if metrics is None:
|
||||||
metrics = {}
|
metrics = {}
|
||||||
|
|
||||||
@@ -647,47 +670,68 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
"uptime": self._calculate_uptime(),
|
"uptime": self._calculate_uptime(),
|
||||||
"system_prompt": self._get_truncated_system_prompt(),
|
"system_prompt": self._get_truncated_system_prompt(),
|
||||||
"history_size": len(self._conversation_history),
|
"history_size": len(self._conversation_history),
|
||||||
"conversation_history": limited_history,
|
"conversation_history": history_data["entries"],
|
||||||
|
"history_info": history_data["info"],
|
||||||
"normalized_name": self.normalized_name,
|
"normalized_name": self.normalized_name,
|
||||||
}
|
}
|
||||||
|
|
||||||
await self._validate_update_data(data)
|
await self._validate_update_data(data)
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
_LOGGER.warning("Update was cancelled")
|
|
||||||
raise
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
_LOGGER.error(f"Error updating data: {err}", exc_info=True)
|
_LOGGER.error(f"Error updating data: {err}", exc_info=True)
|
||||||
return self._get_safe_initial_state()
|
return self._get_safe_initial_state()
|
||||||
|
|
||||||
async def _get_limited_history(self) -> List[Dict[str, Any]]:
|
async def _get_limited_history(self) -> Dict[str, Any]:
|
||||||
"""Get limited conversation history with size constraints."""
|
"""Get limited conversation history showing only last Q&A."""
|
||||||
limited_history = []
|
limited_history = []
|
||||||
|
|
||||||
if self._conversation_history:
|
if self._conversation_history:
|
||||||
for entry in self._conversation_history[-3:]:
|
last_entry = self._conversation_history[-1]
|
||||||
limited_entry = {
|
limited_entry = {
|
||||||
"timestamp": entry["timestamp"],
|
"timestamp": last_entry["timestamp"],
|
||||||
"question": self._truncate_text(entry["question"]),
|
"question": last_entry["question"][:4096] + (TRUNCATION_INDICATOR if len(last_entry["question"]) > 4096 else ""),
|
||||||
"response": self._truncate_text(entry["response"]),
|
"response": last_entry["response"][:4096] + (TRUNCATION_INDICATOR if len(last_entry["response"]) > 4096 else ""),
|
||||||
}
|
}
|
||||||
limited_history.append(limited_entry)
|
limited_history.append(limited_entry)
|
||||||
return limited_history
|
|
||||||
|
history_info = {
|
||||||
|
"total_entries": len(self._conversation_history),
|
||||||
|
"displayed_entries": len(limited_history),
|
||||||
|
"full_history_available": True,
|
||||||
|
"history_path": self._history_file,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"entries": limited_history,
|
||||||
|
"full_history": self._conversation_history,
|
||||||
|
"info": history_info
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _get_sanitized_last_response(self) -> Dict[str, Any]:
|
||||||
|
"""Get sanitized version of last response with truncation indicators."""
|
||||||
|
response = self.last_response.copy()
|
||||||
|
|
||||||
|
if "response" in response:
|
||||||
|
original_response = response["response"]
|
||||||
|
is_response_truncated = len(original_response) > 4096
|
||||||
|
response["response"] = original_response[:4096] + (TRUNCATION_INDICATOR if is_response_truncated else "")
|
||||||
|
response["is_response_truncated"] = is_response_truncated
|
||||||
|
response["full_response_length"] = len(original_response)
|
||||||
|
|
||||||
|
if "question" in response:
|
||||||
|
original_question = response["question"]
|
||||||
|
is_question_truncated = len(original_question) > 4096
|
||||||
|
response["question"] = original_question[:4096] + (TRUNCATION_INDICATOR if is_question_truncated else "")
|
||||||
|
response["is_question_truncated"] = is_question_truncated
|
||||||
|
response["full_question_length"] = len(original_question)
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
def _truncate_text(self, text: str, max_length: int = MAX_ATTRIBUTE_SIZE) -> str:
|
def _truncate_text(self, text: str, max_length: int = MAX_ATTRIBUTE_SIZE) -> str:
|
||||||
"""Safely truncate text to maximum length."""
|
"""Safely truncate text to maximum length."""
|
||||||
return text[:max_length] if text else ""
|
return text[:max_length] if text else ""
|
||||||
|
|
||||||
async def _get_sanitized_last_response(self) -> Dict[str, Any]:
|
|
||||||
"""Get sanitized version of last response."""
|
|
||||||
response = self.last_response.copy()
|
|
||||||
if "response" in response:
|
|
||||||
response["response"] = self._truncate_text(response["response"])
|
|
||||||
if "question" in response:
|
|
||||||
response["question"] = self._truncate_text(response["question"])
|
|
||||||
return response
|
|
||||||
|
|
||||||
def _calculate_uptime(self) -> float:
|
def _calculate_uptime(self) -> float:
|
||||||
"""Calculate current uptime in seconds."""
|
"""Calculate current uptime in seconds."""
|
||||||
return (dt_util.utcnow() - self._start_time).total_seconds()
|
return (dt_util.utcnow() - self._start_time).total_seconds()
|
||||||
|
|||||||
@@ -23,6 +23,6 @@
|
|||||||
"single_config_entry": false,
|
"single_config_entry": false,
|
||||||
"ssdp": [],
|
"ssdp": [],
|
||||||
"usb": [],
|
"usb": [],
|
||||||
"version": "2.0.7-beta",
|
"version": "2.1.0",
|
||||||
"zeroconf": []
|
"zeroconf": []
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ from .const import (
|
|||||||
DEFAULT_NAME_PREFIX,
|
DEFAULT_NAME_PREFIX,
|
||||||
CONF_MAX_HISTORY_SIZE,
|
CONF_MAX_HISTORY_SIZE,
|
||||||
MAX_ATTRIBUTE_SIZE,
|
MAX_ATTRIBUTE_SIZE,
|
||||||
|
VERSION,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .coordinator import HATextAICoordinator
|
from .coordinator import HATextAICoordinator
|
||||||
@@ -154,7 +155,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
name=self._attr_name,
|
name=self._attr_name,
|
||||||
manufacturer="Community",
|
manufacturer="Community",
|
||||||
model=f"{model} ({api_provider} provider)",
|
model=f"{model} ({api_provider} provider)",
|
||||||
sw_version="1.0.0",
|
sw_version=VERSION,
|
||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
|
|||||||
@@ -95,7 +95,7 @@
|
|||||||
},
|
},
|
||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Hacer Pregunta (IA de Texto de HA)",
|
"name": "Hacer Pregunta (HA Text AI)",
|
||||||
"description": "Envía una pregunta al modelo de IA y recibe una respuesta detallada. La respuesta se almacenará en el historial de conversación y se podrá recuperar más tarde.",
|
"description": "Envía una pregunta al modelo de IA y recibe una respuesta detallada. La respuesta se almacenará en el historial de conversación y se podrá recuperar más tarde.",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
|
|||||||
@@ -95,7 +95,7 @@
|
|||||||
},
|
},
|
||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "प्रश्न पूछें (एचए टेक्स्ट एआई)",
|
"name": "प्रश्न पूछें (HA Text AI)",
|
||||||
"description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
|
"description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
|
|||||||
@@ -95,7 +95,7 @@
|
|||||||
},
|
},
|
||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Задать вопрос (Текстовый ИИ HA)",
|
"name": "Задать вопрос (HA Text AI)",
|
||||||
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.",
|
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
|
|||||||
@@ -95,7 +95,7 @@
|
|||||||
},
|
},
|
||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "提问(HA文本AI)",
|
"name": "提问 (HA Text AI)",
|
||||||
"description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。",
|
"description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
|
|||||||
@@ -1,32 +1,30 @@
|
|||||||
```
|
```
|
||||||
ha-text-ai/
|
ha_text_ai/
|
||||||
├── custom_components
|
├── __init__.py
|
||||||
│ └── ha_text_ai
|
├── api_client.py
|
||||||
│ ├── __init__.py
|
├── config_flow.py
|
||||||
│ ├── api_client.py
|
├── const.py
|
||||||
│ ├── config_flow.py
|
├── coordinator.py
|
||||||
│ ├── const.py
|
├── icons
|
||||||
│ ├── coordinator.py
|
│ ├── dark_icon.png
|
||||||
│ ├── icons
|
│ ├── dark_icon@2x.png
|
||||||
│ │ ├── dark_icon.png
|
│ ├── dark_logo.png
|
||||||
│ │ ├── dark_icon@2x.png
|
│ ├── dark_logo@2x.png
|
||||||
│ │ ├── dark_logo.png
|
│ ├── icon.png
|
||||||
│ │ ├── dark_logo@2x.png
|
│ ├── icon@2x.png
|
||||||
│ │ ├── icon.png
|
│ ├── logo.png
|
||||||
│ │ ├── icon@2x.png
|
│ └── logo@2x.png
|
||||||
│ │ ├── logo.png
|
├── manifest.json
|
||||||
│ │ └── logo@2x.png
|
├── sensor.py
|
||||||
│ ├── manifest.json
|
├── services.yaml
|
||||||
│ ├── sensor.py
|
└── translations
|
||||||
│ ├── services.yaml
|
├── de.json
|
||||||
│ └── translations
|
├── en.json
|
||||||
│ ├── de.json
|
├── es.json
|
||||||
│ ├── en.json
|
├── hi.json
|
||||||
│ ├── es.json
|
├── it.json
|
||||||
│ ├── hi.json
|
├── ru.json
|
||||||
│ ├── it.json
|
├── sr.json
|
||||||
│ ├── ru.json
|
└── zh.json
|
||||||
│ ├── sr.json
|
|
||||||
│ └── zh.json
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||