Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be06fddce1 | ||
|
|
5f0bd861a7 | ||
|
|
428aee46c8 | ||
|
|
561bcf0b1d | ||
|
|
2b1e42c665 | ||
|
|
2d68f29ab5 | ||
|
|
19d4a93bca | ||
|
|
fb75c5f44e | ||
|
|
52af987985 | ||
|
|
162a30acdd | ||
|
|
898a6fc638 | ||
|
|
38e2362be4 | ||
|
|
cea912d0b5 | ||
|
|
5ec00040c2 | ||
|
|
8d28fc4a0d | ||
|
|
7cc6587724 | ||
|
|
bacf76e0a9 | ||
|
|
f86c7bfd57 | ||
|
|
2aaf340575 | ||
|
|
bae11ba85c | ||
|
|
9eb7d8912c | ||
|
|
d29535245f | ||
|
|
ca3ae982b0 | ||
|
|
0c4399b46c | ||
|
|
c13ef1921d | ||
|
|
0fb9acfa8f | ||
|
|
2ac4389e1a | ||
|
|
de194e425c | ||
|
|
95f3d6506e | ||
|
|
3e877243b9 | ||
|
|
fd795c9e90 | ||
|
|
5f5dc041b9 | ||
|
|
3d3885d43d | ||
|
|
b059744716 | ||
|
|
f2a41aaa2c | ||
|
|
1fcf751d0d | ||
|
|
a45c9407fd | ||
|
|
21fdf108cf | ||
|
|
c7ec2b3ea4 | ||
|
|
6c4da6cea5 | ||
|
|
3029c5dd26 | ||
|
|
3e97028094 | ||
|
|
1194c87134 | ||
|
|
e03b5315c2 | ||
|
|
fad887492f | ||
|
|
f26df29937 | ||
|
|
69b54a08ba | ||
|
|
7ce77eb18e | ||
|
|
1480669dc8 |
@@ -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.
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)   
|
||||
|
||||
<img src="https://github.com/smkrv/ha-text-ai/blob/524849f6a945ec62c2cf6a6b7ecd9a28b37bf0fa/misc/icons/logo.jpg" alt="HA Text AI" height="160"/>
|
||||
<img src="https://github.com/smkrv/ha-text-ai/blob/2aaf3405759eb2d97624834594e24ace896131df/assets/images/icons/logo.png" alt="HA Text AI" style="width: 80%; max-width: 640px; max-height: 150px; aspect-ratio: 2/1; object-fit: contain;"/>
|
||||
|
||||
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
||||
</div>
|
||||
@@ -17,63 +17,88 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
||||
---
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 🚧 BETA VERSION
|
||||
> Expect: potential bugs, frequent changes, incomplete features.
|
||||
> 🤝 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>
|
||||
>
|
||||
> [Screenshots](misc/screenshots/screenshot.jpg)
|
||||
> [Screenshots](assets/images/screenshots/screenshot.jpg)
|
||||
|
||||
## 🌟 Features
|
||||
|
||||
- 🧠 **Multi-Provider AI Integration**:
|
||||
- Support for OpenAI GPT models
|
||||
- Anthropic Claude integration
|
||||
- Custom API endpoints
|
||||
- Flexible model selection
|
||||
- 🧠 **Multi-Provider AI Integration**: Support for OpenAI GPT and Anthropic Claude models
|
||||
- 💬 **Advanced Language Processing**: Context-aware, multi-turn conversations
|
||||
- 📝 **Enhanced Memory Management**: Secure file-based history storage
|
||||
- ⚡ **Performance Optimization**: Efficient token usage and smart rate limiting
|
||||
- 🎯 **Advanced Customization**: Per-request model and parameter selection
|
||||
- 🔒 **Enhanced Security**: Secure API key management and usage monitoring
|
||||
- 🎨 **Improved User Experience**: Intuitive configuration and rich interfaces
|
||||
- 🔄 **Automation Integration**: Event-driven responses and template compatibility
|
||||
|
||||
- 💬 **Advanced Language Processing**:
|
||||
- Context-aware responses
|
||||
- Multi-turn conversations
|
||||
- Custom system instructions
|
||||
- Natural conversation flow
|
||||
<details>
|
||||
<summary>📦 Detailed Feature Breakdown</summary>
|
||||
|
||||
- 📝 **Enhanced Memory Management**:
|
||||
- File-based conversation history storage
|
||||
- Automatic history rotation
|
||||
- Configurable history size limits
|
||||
- Secure storage in Home Assistant
|
||||
### 🧠 **Multi-Provider AI Integration**
|
||||
- Support for OpenAI GPT models
|
||||
- Anthropic Claude integration
|
||||
- Custom API endpoints
|
||||
- Flexible model selection
|
||||
|
||||
- ⚡ **Performance Optimization**:
|
||||
- Efficient token usage
|
||||
- Smart rate limiting
|
||||
- Response caching
|
||||
- Request interval control
|
||||
### 💬 **Advanced Language Processing**
|
||||
- Context-aware responses
|
||||
- Multi-turn conversations
|
||||
- Custom system instructions
|
||||
- Natural conversation flow
|
||||
|
||||
- 🎯 **Advanced Customization**:
|
||||
- Per-request model selection
|
||||
- Adjustable parameters
|
||||
- Custom system prompts
|
||||
- Temperature control
|
||||
### 📝 **Enhanced Memory Management**
|
||||
- File-based conversation history storage
|
||||
- Automatic history rotation
|
||||
- Configurable history size limits
|
||||
- Secure storage in Home Assistant
|
||||
|
||||
- 🔒 **Enhanced Security**:
|
||||
- Secure API key storage
|
||||
- Rate limiting protection
|
||||
- Error handling
|
||||
- Usage monitoring
|
||||
### ⚡ **Performance Optimization**
|
||||
- Efficient token usage
|
||||
- Smart rate limiting
|
||||
- Response caching
|
||||
- Request interval control
|
||||
|
||||
- 🎨 **Improved User Experience**:
|
||||
- Intuitive configuration UI
|
||||
- Detailed sensor attributes
|
||||
- Rich service interface
|
||||
- Model selection UI
|
||||
### 🎯 **Advanced Customization**
|
||||
- Per-request model selection
|
||||
- Adjustable parameters
|
||||
- Custom system prompts
|
||||
- Temperature control
|
||||
|
||||
- 🔄 **Automation Integration**:
|
||||
- Event-driven responses
|
||||
- Conditional logic support
|
||||
- Template compatibility
|
||||
- Model-specific automation
|
||||
### 🔒 **Enhanced Security**
|
||||
- Secure API key storage
|
||||
- Rate limiting protection
|
||||
- Error handling
|
||||
- Usage monitoring
|
||||
|
||||
### 🎨 **Improved User Experience**
|
||||
- Intuitive configuration UI
|
||||
- Detailed sensor attributes
|
||||
- Rich service interface
|
||||
- Model selection UI
|
||||
|
||||
### 🔄 **Automation Integration**
|
||||
- Event-driven responses
|
||||
- Conditional logic support
|
||||
- Template compatibility
|
||||
- Model-specific automation
|
||||
|
||||
</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
|
||||
|
||||
@@ -82,41 +107,50 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
||||
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
||||
- Anthropic ([Get key](https://console.anthropic.com/))
|
||||
- OpenRouter ([Get key](https://openrouter.ai/keys))
|
||||
- Any OpenAI-compatible API provider
|
||||
- Python 3.9 or newer
|
||||
- Stable internet connection
|
||||
|
||||
### Configuration Options
|
||||
- API Provider (OpenAI/Anthropic)
|
||||
- API Key (provider-specific)
|
||||
- Model Selection (flexible, provider-specific models)
|
||||
- Temperature (Creativity control, 0.0-2.0)
|
||||
- Max Tokens (Response length limit)
|
||||
- Request Interval (API call throttling)
|
||||
- Custom API Endpoint (optional)
|
||||
## Configuration Options
|
||||
|
||||
#### ⓘ Potentially Compatible Providers
|
||||
The integration is designed to be flexible and may work with other providers offering OpenAI-compatible APIs:
|
||||
- Groq
|
||||
- Together AI
|
||||
- Perplexity AI
|
||||
- Mistral AI
|
||||
- Google AI
|
||||
- Local AI servers (like Ollama)
|
||||
- Custom OpenAI-compatible endpoints
|
||||
### 🔧 **Core Configuration Settings**
|
||||
- 🌐 **API Provider**: OpenAI/Anthropic
|
||||
- 🔑 **API Key**: Provider-specific authentication
|
||||
- 🤖 **Model Selection**: Flexible, provider-specific models
|
||||
- 🌡️ **Temperature**: Creativity control (0.0-2.0)
|
||||
- 📏 **Max Tokens**: Response length limit (token usage is estimated using a heuristic method based on word count and specific word characteristics, which may differ from actual token usage)
|
||||
- ⏱️ **Request Interval**: API call throttling
|
||||
- 💾 **History Size**: Number of messages to retain
|
||||
- 🌍 **Custom API Endpoint**: Optional advanced configuration
|
||||
|
||||
#### Additional Notes
|
||||
- Not all providers guarantee full compatibility
|
||||
- Performance may vary between providers
|
||||
- Check individual provider's documentation
|
||||
<details>
|
||||
<summary>🌐 Potentially Compatible Providers</summary>
|
||||
|
||||
#### Flexible Provider Ecosystem
|
||||
The integration is designed to be flexible and may work with other providers offering OpenAI-compatible APIs:
|
||||
- Groq
|
||||
- Together AI
|
||||
- Perplexity AI
|
||||
- Mistral AI
|
||||
- Google AI
|
||||
- Local AI servers (like Ollama)
|
||||
- Custom OpenAI-compatible endpoints
|
||||
|
||||
#### 🚨 Compatibility Notes
|
||||
- Not all providers guarantee full compatibility
|
||||
- Performance may vary between providers
|
||||
- Check individual provider's documentation
|
||||
- Ensure your API key has sufficient credits/quota
|
||||
|
||||
#### Provider Compatibility Requirements
|
||||
To be compatible, a provider should support:
|
||||
- OpenAI-like REST API structure
|
||||
- JSON request/response format
|
||||
- Standard authentication method
|
||||
#### 🔍 Provider Compatibility Requirements
|
||||
To be compatible, a provider should support:
|
||||
- OpenAI-like REST API structure
|
||||
- JSON request/response format
|
||||
- Standard authentication method
|
||||
- Similar model parameter handling
|
||||
|
||||
</details>
|
||||
|
||||
## ⚡ Installation
|
||||
|
||||
### HACS Installation (Recommended)
|
||||
@@ -130,6 +164,8 @@ To be compatible, a provider should support:
|
||||
7. Click "Download"
|
||||
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
|
||||
1. Download the latest release
|
||||
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
||||
@@ -144,7 +180,8 @@ To be compatible, a provider should support:
|
||||
3. Search for "HA Text AI"
|
||||
4. Follow the configuration steps
|
||||
|
||||
### Via YAML
|
||||
<details>
|
||||
<summary>📦 Via YAML (Advanced)</summary>
|
||||
|
||||
### Platform Configuration (Global Settings)
|
||||
|
||||
@@ -202,6 +239,8 @@ sensor:
|
||||
| `temperature` | Float | ❌ | Platform setting | Override global temperature |
|
||||
| `max_tokens` | Integer | ❌ | Platform setting | Override global max tokens |
|
||||
|
||||
</details>
|
||||
|
||||
## 🛠️ Available Services
|
||||
|
||||
### ask_question
|
||||
@@ -214,12 +253,14 @@ data:
|
||||
max_tokens: 500 # optional
|
||||
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
||||
system_prompt: "You are a sleep optimization expert" # optional
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
```
|
||||
|
||||
### set_system_prompt
|
||||
```yaml
|
||||
service: ha_text_ai.set_system_prompt
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
prompt: |
|
||||
You are a home automation expert focused on:
|
||||
1. Energy efficiency
|
||||
@@ -258,7 +299,7 @@ sensor.ha_text_ai_YOUR_UNIQUE_SUFFIX
|
||||
# Examples:
|
||||
sensor.ha_text_ai_gpt # GPT-based sensor
|
||||
sensor.ha_text_ai_claude # Claude-based sensor
|
||||
sensor.ha_text_ai_gpt # Custom suffix
|
||||
sensor.ha_text_ai_abc # Custom suffix
|
||||
```
|
||||
|
||||
#### Response Retrieval
|
||||
@@ -275,6 +316,7 @@ automation:
|
||||
- service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: "Home automation advice"
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
- service: notify.mobile
|
||||
data:
|
||||
message: >
|
||||
@@ -291,6 +333,16 @@ automation:
|
||||
|
||||
### 🔍 HA Text AI Sensor Attributes
|
||||
|
||||
- 🤖 **Model and Provider Information**: Tracking current AI model and service provider
|
||||
- 🚦 **System Status**: Real-time API and processing readiness
|
||||
- 📊 **Performance Metrics**: Request success rates and response times
|
||||
- 💬 **Conversation Tracking**: Token usage and interaction history are estimated using a heuristic method based on word count and specific word characteristics, which may differ from actual token usage.
|
||||
- 🕒 **Last Interaction Details**: Recent query and response tracking
|
||||
- ❤️ **System Health**: Error monitoring and service uptime
|
||||
|
||||
<details>
|
||||
<summary>📦 Detailed Sensor Attributes</summary>
|
||||
|
||||
#### Model and Provider Information
|
||||
```yaml
|
||||
# Name of the AI model currently in use (e.g., latest version of GPT)
|
||||
@@ -352,7 +404,6 @@ automation:
|
||||
|
||||
# Last few conversation entries (limited to 3 for performance)
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
|
||||
|
||||
```
|
||||
|
||||
#### Last Interaction Details
|
||||
@@ -381,7 +432,7 @@ automation:
|
||||
|
||||
### History Storage
|
||||
Conversation history stored in `.storage/ha_text_ai_history/` directory:
|
||||
- Each instance has its own history file
|
||||
- Each instance has its own history file (JSON)
|
||||
- Files are automatically rotated when size limit is reached
|
||||
- Archived history files are timestamped
|
||||
- Default maximum file size: 1MB
|
||||
@@ -391,6 +442,7 @@ Conversation history stored in `.storage/ha_text_ai_history/` directory:
|
||||
- Use these attributes for monitoring and automation
|
||||
- Some values might be 0 or empty initially
|
||||
|
||||
</details>
|
||||
|
||||
## 📘 FAQ
|
||||
|
||||
@@ -427,7 +479,6 @@ A: Yes, archived history files are stored with timestamps and can be accessed ma
|
||||
**Q: How much history is kept?**
|
||||
A: By default, up to 100 conversations are stored, but this can be configured. Files are automatically rotated when they reach 1MB.
|
||||
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md).
|
||||
@@ -474,9 +525,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/2aaf3405759eb2d97624834594e24ace896131df/assets/images/icons/footer_icon.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div>
|
||||
<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)
|
||||
|
||||
|
||||
|
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 |
|
After Width: | Height: | Size: 339 KiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.0 MiB |
@@ -11,8 +11,9 @@ from __future__ import annotations
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict
|
||||
from typing import Any, Dict, TypeVar
|
||||
|
||||
import voluptuous as vol
|
||||
from async_timeout import timeout
|
||||
@@ -52,11 +53,13 @@ from .const import (
|
||||
SERVICE_SET_SYSTEM_PROMPT,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
ICONS_SUBDOMAIN,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
|
||||
ConfigType = TypeVar("ConfigType", bound=Dict[str, Any])
|
||||
|
||||
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
||||
vol.Required("instance"): cv.string,
|
||||
@@ -90,19 +93,18 @@ def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAIC
|
||||
|
||||
raise HomeAssistantError(f"Instance {instance} not found")
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
"""Set up the HA Text AI component."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
def get_file_hash(file_path: str) -> str:
|
||||
"""Calculate SHA256 hash of file."""
|
||||
sha256_hash = hashlib.sha256()
|
||||
with open(file_path, "rb") as f:
|
||||
for byte_block in iter(lambda: f.read(4096), b""):
|
||||
sha256_hash.update(byte_block)
|
||||
return sha256_hash.hexdigest()
|
||||
|
||||
try:
|
||||
source = os.path.join(os.path.dirname(__file__), 'icons', 'icon.svg')
|
||||
dest_dir = os.path.join(hass.config.path('www'), 'icons')
|
||||
os.makedirs(dest_dir, exist_ok=True)
|
||||
dest = os.path.join(dest_dir, 'icon.png')
|
||||
if not os.path.exists(dest):
|
||||
shutil.copyfile(source, dest)
|
||||
except Exception as ex:
|
||||
_LOGGER.warning("Failed to copy custom icon: %s", str(ex))
|
||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
"""Set up the Home Assistant Text AI component."""
|
||||
# Initialize domain data storage
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
|
||||
async def async_ask_question(call: ServiceCall) -> None:
|
||||
"""Handle ask_question service."""
|
||||
@@ -150,6 +152,7 @@ async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
_LOGGER.error("Error setting system prompt: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to set system prompt: {str(err)}")
|
||||
|
||||
# Register services
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_ASK_QUESTION,
|
||||
@@ -178,6 +181,53 @@ async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
schema=SERVICE_SCHEMA_SET_SYSTEM_PROMPT
|
||||
)
|
||||
|
||||
# Handle icons
|
||||
try:
|
||||
source_icon_path = os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
ICONS_SUBDOMAIN,
|
||||
'icon@2x.png'
|
||||
)
|
||||
|
||||
destination_directory = os.path.join(
|
||||
hass.config.path('www'),
|
||||
DOMAIN,
|
||||
ICONS_SUBDOMAIN
|
||||
)
|
||||
|
||||
destination_icon_path = os.path.join(
|
||||
destination_directory,
|
||||
'icon.png'
|
||||
)
|
||||
|
||||
if not os.path.exists(source_icon_path):
|
||||
_LOGGER.error("Source icon not found: %s", source_icon_path)
|
||||
return True
|
||||
|
||||
def create_directory():
|
||||
os.makedirs(destination_directory, exist_ok=True)
|
||||
|
||||
await hass.async_add_executor_job(create_directory)
|
||||
|
||||
should_copy = True
|
||||
|
||||
if os.path.exists(destination_icon_path):
|
||||
source_hash = await hass.async_add_executor_job(get_file_hash, source_icon_path)
|
||||
dest_hash = await hass.async_add_executor_job(get_file_hash, destination_icon_path)
|
||||
should_copy = source_hash != dest_hash
|
||||
|
||||
if should_copy:
|
||||
def copy_file():
|
||||
shutil.copyfile(source_icon_path, destination_icon_path)
|
||||
|
||||
await hass.async_add_executor_job(copy_file)
|
||||
_LOGGER.debug("Icon updated: %s", destination_icon_path)
|
||||
|
||||
except PermissionError as e:
|
||||
_LOGGER.error("Permission denied when managing icons: %s", str(e))
|
||||
except Exception as e:
|
||||
_LOGGER.error("Failed to manage icons: %s", str(e))
|
||||
|
||||
return True
|
||||
|
||||
async def async_check_api(session, endpoint: str, headers: dict, provider: str) -> bool:
|
||||
|
||||
@@ -41,7 +41,9 @@ CONF_IS_ANTHROPIC: Final = "is_anthropic"
|
||||
CONF_CONTEXT_MESSAGES: Final = "context_messages"
|
||||
|
||||
ABSOLUTE_MAX_HISTORY_SIZE = 500
|
||||
MAX_ENTRY_SIZE = 1 * 1024 * 1024
|
||||
MAX_ATTRIBUTE_SIZE = 4 * 1024
|
||||
MAX_HISTORY_FILE_SIZE = 1 * 1024 * 1024
|
||||
ICONS_SUBDOMAIN = "icons"
|
||||
|
||||
# Default values
|
||||
DEFAULT_MODEL: Final = "gpt-4o-mini"
|
||||
@@ -54,6 +56,8 @@ DEFAULT_NAME: Final = "HA Text AI"
|
||||
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
||||
|
||||
TRUNCATION_INDICATOR = " … "
|
||||
|
||||
# Parameter constraints
|
||||
MIN_TEMPERATURE: Final = 0.0
|
||||
MAX_TEMPERATURE: Final = 2.0
|
||||
|
||||
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 351 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 257 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 86 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 259 KiB |
@@ -13,16 +13,16 @@
|
||||
"loggers": ["custom_components.ha_text_ai"],
|
||||
"mqtt": [],
|
||||
"quality_scale": "silver",
|
||||
"requirements": [
|
||||
"openai>=1.12.0",
|
||||
"anthropic>=0.8.0",
|
||||
"aiohttp>=3.8.0",
|
||||
"async-timeout>=4.0.0",
|
||||
"certifi>=2024.2.2"
|
||||
],
|
||||
"requirements": [
|
||||
"openai>=1.12.0",
|
||||
"anthropic>=0.8.0",
|
||||
"aiohttp>=3.8.0",
|
||||
"async-timeout>=4.0.0",
|
||||
"certifi>=2024.2.2"
|
||||
],
|
||||
"single_config_entry": false,
|
||||
"ssdp": [],
|
||||
"usb": [],
|
||||
"version": "2.0.5-beta",
|
||||
"version": "2.0.8",
|
||||
"zeroconf": []
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ from .const import (
|
||||
ENTITY_ICON_PROCESSING,
|
||||
DEFAULT_NAME_PREFIX,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
MAX_ATTRIBUTE_SIZE,
|
||||
)
|
||||
|
||||
from .coordinator import HATextAICoordinator
|
||||
@@ -178,12 +179,29 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
|
||||
def _sanitize_attributes(self, attributes: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Sanitize all attributes for JSON serialization."""
|
||||
return {
|
||||
sanitized = {
|
||||
key: self._sanitize_value(value)
|
||||
for key, value in attributes.items()
|
||||
if value is not None
|
||||
}
|
||||
|
||||
# Log metrics for debugging
|
||||
metrics_keys = [
|
||||
METRIC_TOTAL_TOKENS,
|
||||
METRIC_PROMPT_TOKENS,
|
||||
METRIC_COMPLETION_TOKENS,
|
||||
METRIC_SUCCESSFUL_REQUESTS,
|
||||
METRIC_FAILED_REQUESTS,
|
||||
METRIC_AVERAGE_LATENCY,
|
||||
METRIC_MAX_LATENCY,
|
||||
METRIC_MIN_LATENCY,
|
||||
]
|
||||
|
||||
metrics_values = {k: sanitized.get(k) for k in metrics_keys if k in sanitized}
|
||||
_LOGGER.debug(f"Metrics for {self.entity_id}: {metrics_values}")
|
||||
|
||||
return sanitized
|
||||
|
||||
@property
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the native value of the sensor."""
|
||||
@@ -212,68 +230,65 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
|
||||
try:
|
||||
data = self.coordinator.data
|
||||
metrics = data.get("metrics", {})
|
||||
|
||||
# Base attributes
|
||||
attributes = {
|
||||
ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"),
|
||||
ATTR_API_PROVIDER: self._config_entry.data.get(
|
||||
CONF_API_PROVIDER, "Unknown"
|
||||
),
|
||||
ATTR_API_PROVIDER: self._config_entry.data.get(CONF_API_PROVIDER, "Unknown"),
|
||||
ATTR_API_STATUS: self._current_state,
|
||||
ATTR_TOTAL_ERRORS: self._error_count,
|
||||
ATTR_LAST_ERROR: self._last_error,
|
||||
ATTR_TOTAL_ERRORS: metrics.get("total_errors", 0),
|
||||
"instance_name": self._instance_name,
|
||||
"normalized_name": self._normalized_name,
|
||||
ATTR_SYSTEM_PROMPT: data.get("system_prompt"),
|
||||
ATTR_SYSTEM_PROMPT: (data.get("system_prompt", "")[:MAX_ATTRIBUTE_SIZE]
|
||||
if data.get("system_prompt") else None),
|
||||
ATTR_IS_PROCESSING: data.get("is_processing", False),
|
||||
ATTR_IS_RATE_LIMITED: data.get("is_rate_limited", False),
|
||||
ATTR_IS_MAINTENANCE: data.get("is_maintenance", False),
|
||||
ATTR_ENDPOINT_STATUS: data.get("endpoint_status", "unknown"),
|
||||
ATTR_UPTIME: data.get("uptime", 0),
|
||||
ATTR_UPTIME: round(data.get("uptime", 0), 2),
|
||||
ATTR_HISTORY_SIZE: data.get("history_size", 0),
|
||||
ATTR_CONVERSATION_HISTORY: data.get("conversation_history", []),
|
||||
}
|
||||
|
||||
# Add metrics
|
||||
metrics = data.get("metrics", {})
|
||||
if isinstance(metrics, dict):
|
||||
self._metrics = metrics
|
||||
attributes.update(
|
||||
{
|
||||
METRIC_TOTAL_TOKENS: metrics.get("total_tokens", 0),
|
||||
METRIC_PROMPT_TOKENS: metrics.get("prompt_tokens", 0),
|
||||
METRIC_COMPLETION_TOKENS: metrics.get("completion_tokens", 0),
|
||||
METRIC_SUCCESSFUL_REQUESTS: metrics.get(
|
||||
"successful_requests", 0
|
||||
),
|
||||
METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0),
|
||||
METRIC_AVERAGE_LATENCY: metrics.get("average_latency", 0),
|
||||
METRIC_MAX_LATENCY: metrics.get("max_latency", 0),
|
||||
METRIC_MIN_LATENCY: metrics.get("min_latency", float("inf")),
|
||||
# History limit
|
||||
conversation_history = data.get("conversation_history", [])
|
||||
if conversation_history:
|
||||
limited_history = []
|
||||
for entry in conversation_history:
|
||||
limited_entry = {
|
||||
"timestamp": entry["timestamp"],
|
||||
"question": entry["question"][:MAX_ATTRIBUTE_SIZE],
|
||||
"response": entry["response"][:MAX_ATTRIBUTE_SIZE]
|
||||
}
|
||||
)
|
||||
limited_history.append(limited_entry)
|
||||
attributes[ATTR_CONVERSATION_HISTORY] = limited_history
|
||||
|
||||
# Add last response
|
||||
# Metrics
|
||||
if isinstance(metrics, dict):
|
||||
attributes.update({
|
||||
METRIC_TOTAL_TOKENS: metrics.get("total_tokens", 0),
|
||||
METRIC_PROMPT_TOKENS: metrics.get("prompt_tokens", 0),
|
||||
METRIC_COMPLETION_TOKENS: metrics.get("completion_tokens", 0),
|
||||
METRIC_SUCCESSFUL_REQUESTS: metrics.get("successful_requests", 0),
|
||||
METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0),
|
||||
METRIC_AVERAGE_LATENCY: round(metrics.get("average_latency", 0), 2),
|
||||
METRIC_MAX_LATENCY: round(metrics.get("max_latency", 0), 2),
|
||||
METRIC_MIN_LATENCY: (metrics.get("min_latency")
|
||||
if metrics.get("min_latency") != float("inf")
|
||||
else None),
|
||||
})
|
||||
|
||||
# Last response handling
|
||||
last_response = data.get("last_response", {})
|
||||
if isinstance(last_response, dict):
|
||||
self._last_response = last_response
|
||||
attributes.update(
|
||||
{
|
||||
ATTR_RESPONSE: last_response.get("response", ""),
|
||||
ATTR_QUESTION: last_response.get("question", ""),
|
||||
"last_model": last_response.get("model", ""),
|
||||
"last_timestamp": last_response.get("timestamp", ""),
|
||||
"last_error": last_response.get("error"),
|
||||
}
|
||||
)
|
||||
|
||||
# Add performance metrics if available
|
||||
if ATTR_PERFORMANCE_METRICS in data:
|
||||
attributes[ATTR_PERFORMANCE_METRICS] = data[
|
||||
ATTR_PERFORMANCE_METRICS
|
||||
]
|
||||
|
||||
# Add API version if available
|
||||
if ATTR_API_VERSION in data:
|
||||
attributes[ATTR_API_VERSION] = data[ATTR_API_VERSION]
|
||||
attributes.update({
|
||||
ATTR_RESPONSE: last_response.get("response", "")[:MAX_ATTRIBUTE_SIZE],
|
||||
ATTR_QUESTION: last_response.get("question", "")[:MAX_ATTRIBUTE_SIZE],
|
||||
"last_model": last_response.get("model", ""),
|
||||
"last_timestamp": last_response.get("timestamp", ""),
|
||||
"last_error": (last_response.get("error", "")[:MAX_ATTRIBUTE_SIZE]
|
||||
if last_response.get("error") else None),
|
||||
})
|
||||
|
||||
return self._sanitize_attributes(attributes)
|
||||
|
||||
@@ -299,6 +314,12 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
|
||||
self._is_processing = data.get("is_processing", False)
|
||||
|
||||
# Update metrics
|
||||
metrics = data.get("metrics", {})
|
||||
if isinstance(metrics, dict):
|
||||
self._metrics.update(metrics)
|
||||
_LOGGER.debug(f"Updated metrics for {self.entity_id}: {self._metrics}")
|
||||
|
||||
# Update conversation history and system prompt
|
||||
self._conversation_history = data.get("conversation_history", [])
|
||||
self._system_prompt = data.get("system_prompt")
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
},
|
||||
"services": {
|
||||
"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.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "प्रश्न पूछें (एचए टेक्स्ट एआई)",
|
||||
"name": "प्रश्न पूछें (HA Text AI)",
|
||||
"description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
|
||||
"fields": {
|
||||
"instance": {
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Задать вопрос (Текстовый ИИ HA)",
|
||||
"name": "Задать вопрос (HA Text AI)",
|
||||
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "提问(HA文本AI)",
|
||||
"name": "提问 (HA Text AI)",
|
||||
"description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。",
|
||||
"fields": {
|
||||
"instance": {
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
```
|
||||
ha-text-ai/
|
||||
│
|
||||
├── custom_components/
|
||||
├── ha_text_ai/
|
||||
│ ├── __init__.py
|
||||
│ ├── config_flow.py
|
||||
│ ├── coordinator.py
|
||||
│ ├── manifest.json
|
||||
│ ├── sensor.py
|
||||
│ ├── services.yaml
|
||||
│ ├── const.py
|
||||
│ └── api_client.py
|
||||
│
|
||||
├── translations/
|
||||
│ ├── en.json
|
||||
│ ├── de.json
|
||||
│ └── ru.json
|
||||
│
|
||||
└── icons/
|
||||
├── icon.png
|
||||
├── icon@2x.png
|
||||
├── logo.png
|
||||
└── logo@2x.png
|
||||
ha_text_ai/
|
||||
├── __init__.py
|
||||
├── api_client.py
|
||||
├── config_flow.py
|
||||
├── const.py
|
||||
├── coordinator.py
|
||||
├── icons
|
||||
│ ├── dark_icon.png
|
||||
│ ├── dark_icon@2x.png
|
||||
│ ├── dark_logo.png
|
||||
│ ├── dark_logo@2x.png
|
||||
│ ├── icon.png
|
||||
│ ├── icon@2x.png
|
||||
│ ├── logo.png
|
||||
│ └── logo@2x.png
|
||||
├── manifest.json
|
||||
├── sensor.py
|
||||
├── services.yaml
|
||||
└── translations
|
||||
├── de.json
|
||||
├── en.json
|
||||
├── es.json
|
||||
├── hi.json
|
||||
├── it.json
|
||||
├── ru.json
|
||||
├── sr.json
|
||||
└── zh.json
|
||||
|
||||
```
|
||||
|
||||