2024-11-22 01:57:21 +03:00
# 🤖 HA Text AI for Home Assistant
2024-11-14 18:39:06 +03:00
2024-11-19 19:03:51 +03:00
<div align="center">
2024-11-18 10:59:06 +03:00
2025-09-02 01:56:24 +03:00
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)
2025-01-29 00:57:27 +03:00
       
2024-12-10 23:27:18 +03:00
2024-11-19 19:30:42 +03:00
2025-09-02 02:06:58 +03:00
<img src="https://github.com/smkrv/ha-text-ai/blob/main/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;"/>
2024-11-26 17:47:49 +03:00
2024-11-29 00:57:39 +03:00
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
2024-11-18 10:59:06 +03:00
</div>
<p align="center">
2025-01-28 16:25:59 +03:00
Transform your smart home experience with powerful AI assistance powered by multiple AI providers including OpenAI GPT, DeepSeek and Anthropic Claude models. Get intelligent responses, automate complex scenarios, and enhance your home automation with advanced natural language processing.
2024-11-26 00:14:26 +03:00
</p>
2024-11-26 17:47:49 +03:00
2024-11-26 00:14:26 +03:00
---
> [!IMPORTANT]
2025-01-29 03:05:11 +03:00
> 🤝 Community Driven: for more details on the integration,
2025-01-29 03:04:39 +03:00
> check out the discussion on the **[Home Assistant Community forum](https://community.home-assistant.io/t/ha-text-ai-transforming-home-automation-through-multi-llm-integration/799741)**
2024-11-26 00:14:26 +03:00
>
2025-01-29 03:05:47 +03:00
> <a href="https://my.home-assistant.io/redirect/hacs_repository/?owner=smkrv&repository=ha-text-ai&category=Integration"><img src="https://my.home-assistant.io/badges/hacs_repository.svg" width="210" height="auto"></a>
2024-11-29 01:27:01 +03:00
>
2024-12-06 16:13:27 +03:00
> [Screenshots](assets/images/screenshots/screenshot.jpg)
2024-11-25 16:40:55 +03:00
2024-11-19 12:45:26 +03:00
## 🌟 Features
2024-11-14 18:39:06 +03:00
2025-01-28 16:25:59 +03:00
- 🧠 **Multi-Provider AI Integration** : Support for OpenAI GPT, DeepSeek and Anthropic Claude models
2024-12-05 01:49:26 +03:00
- 💬 **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
2024-12-09 15:29:53 +03:00
- 🔄 **Automation Integration** : Event-driven responses and template compatibility
2024-11-22 02:00:42 +03:00
2024-12-05 01:49:26 +03:00
<details>
<summary>📦 Detailed Feature Breakdown</summary>
2024-11-22 02:00:42 +03:00
2024-12-05 01:49:26 +03:00
### 🧠 **Multi-Provider AI Integration**
- Support for OpenAI GPT models
- Anthropic Claude integration
2025-01-28 16:25:59 +03:00
- DeepSeek integration
2024-12-05 01:49:26 +03:00
- Custom API endpoints
- Flexible model selection
2024-11-22 02:00:42 +03:00
2024-12-05 01:49:26 +03:00
### 💬 **Advanced Language Processing**
- Context-aware responses
- Multi-turn conversations
- Custom system instructions
- Natural conversation flow
2024-11-22 02:00:42 +03:00
2024-12-05 01:49:26 +03:00
### 📝 **Enhanced Memory Management**
- File-based conversation history storage
- Automatic history rotation
- Configurable history size limits
- Secure storage in Home Assistant
2024-11-22 02:00:42 +03:00
2024-12-05 01:49:26 +03:00
### ⚡ **Performance Optimization**
- Efficient token usage
- Smart rate limiting
- Response caching
- Request interval control
2024-11-22 02:00:42 +03:00
2024-12-05 01:49:26 +03:00
### 🎯 **Advanced Customization**
- Per-request model selection
- Adjustable parameters
- Custom system prompts
- Temperature control
2024-11-22 02:00:42 +03:00
2024-12-05 01:49:26 +03:00
### 🔒 **Enhanced Security**
- Secure API key storage
- Rate limiting protection
- Error handling
- Usage monitoring
2024-12-05 01:46:28 +03:00
2024-12-05 01:49:26 +03:00
### 🎨 **Improved User Experience**
- Intuitive configuration UI
- Detailed sensor attributes
- Rich service interface
- Model selection UI
2024-12-05 01:46:28 +03:00
2024-12-05 01:49:26 +03:00
### 🔄 **Automation Integration**
- Event-driven responses
- Conditional logic support
- Template compatibility
- Model-specific automation
2024-12-05 01:46:28 +03:00
2024-12-05 01:49:26 +03:00
</details>
2024-11-18 10:59:06 +03:00
2024-12-06 16:35:26 +03:00
#### 🌐 Translations
| Code | Language | Status |
|------|----------|--------|
| 🇩🇪 de | Deutsch | Full |
| 🇬🇧 en | English | Primary |
| 🇪🇸 es | Español | Full |
| 🇮🇳 hi | हिन्दी | Full |
| 🇮🇹 it | Italiano | Full |
| 🇷🇺 ru | Русский | Full |
2024-12-07 00:43:53 +03:00
| 🇷🇸 sr | Српски | Full |
2024-12-06 16:35:26 +03:00
| 🇨🇳 zh | 中文 | Full |
2024-11-19 12:45:26 +03:00
## 📋 Prerequisites
2024-11-18 10:59:06 +03:00
2025-09-02 02:06:58 +03:00
- Home Assistant 2024.12.0 or later (recommended for best compatibility)
2024-11-22 01:56:36 +03:00
- Active API key from:
2024-11-19 19:03:51 +03:00
- OpenAI ([Get key ](https://platform.openai.com/account/api-keys ))
- Anthropic ([Get key ](https://console.anthropic.com/ ))
2025-05-19 15:10:19 +03:00
- DeepSeek ([Get key ](https://platform.deepseek.com/api_keys ))
2024-11-25 16:57:14 +03:00
- OpenRouter ([Get key ](https://openrouter.ai/keys ))
2025-05-19 15:10:19 +03:00
- Google Gemini 🆕 ([Get key ](https://ai.google.dev/gemini-api/docs/api-key )) thanks to ([@Azzedde ](https://github.com/Azzedde ))
2024-12-06 16:46:11 +03:00
- Any OpenAI-compatible API provider
2024-11-19 12:45:26 +03:00
- Python 3.9 or newer
2024-11-19 14:06:32 +03:00
- Stable internet connection
2024-11-18 10:59:06 +03:00
2024-12-05 01:54:09 +03:00
## Configuration Options
2024-11-22 01:56:36 +03:00
2024-12-05 01:54:09 +03:00
### 🔧 **Core Configuration Settings**
2025-09-02 02:06:58 +03:00
- 🌐 **API Provider** : OpenAI/Anthropic/DeepSeek/Gemini
2024-12-05 01:54:09 +03:00
- 🔑 **API Key** : Provider-specific authentication
- 🤖 **Model Selection** : Flexible, provider-specific models
- 🌡️ **Temperature** : Creativity control (0.0-2.0)
2025-01-28 15:54:48 +03:00
- 📏 **Max Tokens** : Response length limit (passed directly to the LLM API to control the maximum length of the response)
2024-12-05 01:54:09 +03:00
- ⏱️ **Request Interval** : API call throttling
- 💾 **History Size** : Number of messages to retain
- 🌍 **Custom API Endpoint** : Optional advanced configuration
2024-11-25 16:34:36 +03:00
2025-09-02 02:11:34 +03:00
### 🤖 **Recommended Models**
2025-09-02 02:06:58 +03:00
#### OpenAI Models
2025-09-02 02:19:37 +03:00
- **GPT-5** - The latest flagship model, best for complex reasoning
- **GPT-5 mini** - A cost-effective and fast model, suitable for most tasks
2025-09-02 02:06:58 +03:00
#### Anthropic Claude Models
2025-09-02 02:19:37 +03:00
- **Claude Opus 4.1** - The most capable model for handling complex tasks
- **Claude Sonnet 4** - Offers a balance between performance and cost
- **Claude Haiku 4** - The fastest and most economical option in the series
2025-09-02 02:06:58 +03:00
#### DeepSeek Models
2025-09-02 02:19:37 +03:00
- **DeepSeek-V3.1** - A general-purpose model for a wide range of tasks
- **DeepSeek-R1** - A specialized model focused on reasoning and coding
2025-09-02 02:06:58 +03:00
#### Google Gemini Models
2025-09-02 02:19:37 +03:00
- **Gemini 2.5 Pro & 2.5 Flash** - The newest and most advanced models available
- **Gemini 2.0 Pro & 2.0 Flash** - Previous generation models that are still powerful and efficient
2025-09-02 02:06:58 +03:00
2024-12-05 01:54:09 +03:00
<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
2024-11-25 16:37:57 +03:00
- Ensure your API key has sufficient credits/quota
2024-11-25 16:34:36 +03:00
2024-12-05 01:54:09 +03:00
#### 🔍 Provider Compatibility Requirements
To be compatible, a provider should support:
- OpenAI-like REST API structure
- JSON request/response format
- Standard authentication method
2024-11-25 16:34:36 +03:00
- Similar model parameter handling
2024-12-06 16:33:46 +03:00
2024-12-05 01:54:09 +03:00
</details>
2024-11-25 16:34:36 +03:00
2024-11-19 14:06:32 +03:00
## ⚡ Installation
2024-11-22 01:56:36 +03:00
### HACS Installation (Recommended)
2025-05-19 15:10:19 +03:00
>[!TIP]
>HA Text AI is available in the default HACS repository. You can install it directly through HACS or click the button below to open it there.
2024-11-25 17:10:38 +03:00
<a href="https://my.home-assistant.io/redirect/hacs_repository/?owner=smkrv&repository=ha-text-ai&category=Integration"><img src="https://my.home-assistant.io/badges/hacs_repository.svg" width="170" height="auto"></a>
2024-11-22 01:56:36 +03:00
1. Open HACS in Home Assistant
2. Click on "Integrations"
2025-09-02 02:11:34 +03:00
3. Search for "HA Text AI"
4. Click "Download"
5. Restart Home Assistant
**Alternative Method (Custom Repository):**
If the integration is not found in the default repository:
1. Click "..." in top right corner of HACS
2. Select "Custom repositories"
3. Add repository URL: `https://github.com/smkrv/ha-text-ai`
4. Choose "Integration" as category
5. Click "Download"
2024-11-18 10:59:06 +03:00
2024-11-19 12:45:26 +03:00
### Manual Installation
2024-11-19 14:06:32 +03:00
1. Download the latest release
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
2024-11-19 12:45:26 +03:00
3. Restart Home Assistant
2024-11-19 14:06:32 +03:00
4. Add configuration via UI or YAML
## ⚙️ Configuration
### Via UI (Recommended)
1. Go to Settings → Devices & Services
2. Click "Add Integration"
3. Search for "HA Text AI"
4. Follow the configuration steps
2024-12-05 01:54:09 +03:00
<details>
<summary>📦 Via YAML (Advanced)</summary>
2024-11-27 16:30:58 +03:00
### Platform Configuration (Global Settings)
2024-11-18 10:59:06 +03:00
```yaml
2024-11-19 00:51:57 +03:00
ha_text_ai :
2024-11-27 16:30:58 +03:00
api_provider : openai # Required
api_key : !secret ai_api_key # Required
2025-09-02 02:06:58 +03:00
model : gpt-4o # Strongly recommended
2024-11-27 16:30:58 +03:00
temperature : 0.7 # Optional
max_tokens : 1000 # Optional
request_interval : 1.0 # Optional
2024-11-27 16:58:00 +03:00
api_endpoint : https://api.openai.com/v1 # Required
2024-11-27 16:30:58 +03:00
system_prompt : | # Optional
2024-11-19 19:03:51 +03:00
You are a home automation expert assistant.
Focus on practical and efficient solutions.
2024-11-18 10:59:06 +03:00
```
2024-11-27 16:30:58 +03:00
### Sensor Configuration
```yaml
sensor :
- platform : ha_text_ai
name : "My AI Assistant" # Required, unique identifier
api_provider : openai # Optional (inherits from platform)
2025-09-02 02:06:58 +03:00
model : "gpt-4o" # Optional
2024-11-27 16:30:58 +03:00
temperature : 0.7 # Optional
max_tokens : 1000 # Optional
```
### 📋 Configuration Parameters
#### Platform Configuration
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
2025-09-02 02:06:58 +03:00
| `api_provider` | String | ✅ | - | AI service provider (openai, anthropic, deepseek, gemini) |
2024-11-27 16:30:58 +03:00
| `api_key` | String | ✅ | - | Authentication key for AI service |
2025-09-02 02:06:58 +03:00
| `model` | String | ⚠️ | gpt-4o-mini | Strongly recommended: Specific AI model to use. Default varies by provider |
| `temperature` | Float | ❌ | 0.1 | Response creativity level (0.0-2.0) |
2024-11-27 16:30:58 +03:00
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
2024-11-27 16:43:20 +03:00
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
2024-11-27 16:30:58 +03:00
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
2025-09-02 02:06:58 +03:00
| `max_history_size` | Integer | ❌ | 50 | Maximum number of conversation entries to store |
2025-09-02 02:11:34 +03:00
| `context_messages` | Integer | ❌ | 5 | Number of previous messages to include in context (1-20) |
2024-11-27 16:30:58 +03:00
#### Sensor Configuration
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `platform` | String | ✅ | - | Must be `ha_text_ai` |
| `name` | String | ✅ | - | Unique sensor identifier |
| `api_provider` | String | ❌ | Platform setting | Override global provider |
2025-09-02 02:06:58 +03:00
| `model` | String | ⚠️ | Provider default | Recommended: Override global model (gpt-4o-mini, deepseek-chat, gemini-2.0-flash) |
| `temperature` | Float | ❌ | 0.1 | Override global temperature |
| `max_tokens` | Integer | ❌ | 1000 | Override global max tokens |
2024-11-27 16:30:58 +03:00
2024-12-05 01:54:09 +03:00
</details>
2024-11-19 12:45:26 +03:00
## 🛠️ Available Services
2025-09-01 17:14:23 +03:00
### 🔄 Response Variables (New!)
**HA Text AI now supports response variables** - a powerful feature that returns AI responses directly from service calls, eliminating the need for separate text sensors and the 255-character limitation!
#### ✨ Key Benefits:
- **Unlimited response length** - No more 255-character truncation
- **Direct data access** - Get responses immediately in automations
- **Race condition prevention** - Eliminates conflicts in parallel automations
- **Simplified workflows** - No need to read from sensors
2024-11-19 12:45:26 +03:00
### ask_question
2024-11-18 10:59:06 +03:00
```yaml
2024-11-19 00:51:57 +03:00
service : ha_text_ai.ask_question
2024-11-18 10:59:06 +03:00
data :
2024-11-19 12:45:26 +03:00
question : "What's the optimal temperature for sleeping?"
2025-09-02 02:11:34 +03:00
model : "claude-3.5-sonnet" # optional
2024-11-19 12:45:26 +03:00
temperature : 0.5 # optional
max_tokens : 500 # optional
2024-11-25 15:42:04 +03:00
context_messages : 10 #optional, number of previous messages to include in context, default: 5
2024-11-19 19:03:51 +03:00
system_prompt : "You are a sleep optimization expert" # optional
2024-12-07 00:48:17 +03:00
instance : sensor.ha_text_ai_gpt
2025-09-01 17:14:23 +03:00
response_variable : ai_response # NEW! Store response data directly
```
#### 📊 Response Data Structure:
```yaml
# The service returns structured data:
response_text : "The optimal sleeping temperature is 65-68°F (18-20°C)..."
tokens_used : 150
prompt_tokens : 50
completion_tokens : 100
2025-09-02 02:11:34 +03:00
model_used : "claude-3.5-sonnet"
2025-09-01 17:14:23 +03:00
instance : "sensor.ha_text_ai_gpt"
question : "What's the optimal temperature for sleeping?"
2025-09-02 02:06:58 +03:00
timestamp : "2025-02-09T16:57:00.000Z"
2025-09-01 17:14:23 +03:00
success : true
# error: "Error message" (only present if success: false)
2024-11-18 10:59:06 +03:00
```
2024-11-19 12:45:26 +03:00
### set_system_prompt
```yaml
service : ha_text_ai.set_system_prompt
data :
2024-12-07 00:48:17 +03:00
instance : sensor.ha_text_ai_gpt
2024-11-19 14:06:32 +03:00
prompt : |
You are a home automation expert focused on:
1. Energy efficiency
2. Comfort optimization
3. Security considerations
Provide practical, actionable advice.
2024-11-19 12:45:26 +03:00
```
2024-11-18 10:59:06 +03:00
2024-11-19 12:45:26 +03:00
### clear_history
```yaml
service : ha_text_ai.clear_history
2024-12-10 23:33:32 +03:00
data :
instance : sensor.ha_text_ai_gpt
2024-11-19 12:45:26 +03:00
```
2024-11-18 10:59:06 +03:00
2024-11-19 12:45:26 +03:00
### get_history
```yaml
service : ha_text_ai.get_history
data :
2025-09-02 02:11:34 +03:00
limit : 5 # optional, number of conversations to return (1-100)
filter_model : "gpt-4o" # optional, filter by specific AI model
start_date : "2025-02-01" # optional, filter conversations from this date
include_metadata : false # optional, include tokens, response time, etc.
sort_order : "newest" # optional, sort order: "newest" or "oldest"
2024-12-10 23:33:32 +03:00
instance : sensor.ha_text_ai_gpt
2024-11-19 12:45:26 +03:00
```
2025-09-01 17:14:23 +03:00
## 🚀 Advanced Automation Examples with Response Variables
### Example 1: Smart Home Advice with Direct Response
```yaml
automation :
- alias : "Get AI Home Advice"
trigger :
- platform : state
entity_id : input_button.ask_ai_advice
action :
- service : ha_text_ai.ask_question
data :
question : "What's the best way to optimize energy usage in my home?"
instance : sensor.ha_text_ai_gpt
response_variable : ai_advice
- service : notify.mobile_app
data :
title : "🏠 Smart Home Tip"
message : |
{{ ai_advice.response_text }}
📊 Tokens used: {{ ai_advice.tokens_used }}
🤖 Model: {{ ai_advice.model_used }}
```
### Example 2: Weather-Based AI Recommendations
```yaml
automation :
- alias : "Weather-Based AI Suggestions"
trigger :
- platform : numeric_state
entity_id : sensor.outdoor_temperature
below : 0
action :
- service : ha_text_ai.ask_question
data :
question : |
The outdoor temperature is {{ states('sensor.outdoor_temperature') }}°C.
What should I do to prepare my home for freezing weather?
system_prompt : "You are a home maintenance expert. Provide practical, actionable advice."
instance : sensor.ha_text_ai_gpt
response_variable : winter_advice
- if :
- condition : template
value_template : "{{ winter_advice.success }}"
then :
- service : persistent_notification.create
data :
title : "❄️ Winter Preparation Advice"
message : |
{{ winter_advice.response_text }}
Generated at: {{ winter_advice.timestamp }}
else :
- service : persistent_notification.create
data :
title : "⚠️ AI Service Error"
message : "Failed to get winter advice: {{ winter_advice.error }}"
```
### Example 3: Multi-Step AI Workflow
```yaml
automation :
- alias : "Multi-Step AI Analysis"
trigger :
- platform : state
entity_id : input_button.analyze_home_status
action :
# Step 1: Get current status analysis
- service : ha_text_ai.ask_question
data :
question : |
Current home status:
- Temperature: {{ states('sensor.indoor_temperature') }}°C
- Humidity: {{ states('sensor.indoor_humidity') }}%
- Energy usage: {{ states('sensor.power_consumption') }}W
Analyze this data and provide insights.
instance : sensor.ha_text_ai_gpt
response_variable : status_analysis
# Step 2: Get recommendations based on analysis
- service : ha_text_ai.ask_question
data :
question : |
Based on this analysis: "{{ status_analysis.response_text[:500] }}"
Provide 3 specific actionable recommendations for improvement.
context_messages : 2 # Include previous conversation
instance : sensor.ha_text_ai_gpt
response_variable : recommendations
# Step 3: Send comprehensive report
- service : notify.telegram
data :
title : "🏠 Home Analysis Report"
message : |
**Analysis:**
{{ status_analysis.response_text }}
**Recommendations:**
{{ recommendations.response_text }}
**Report Details:**
- Total tokens used: {{ status_analysis.tokens_used + recommendations.tokens_used }}
- Analysis model: {{ status_analysis.model_used }}
- Generated: {{ recommendations.timestamp }}
```
### 💡 Migration from Sensors to Response Variables
#### Old Method (Limited):
```yaml
# ❌ Old way - limited to 255 characters, race conditions
automation :
- alias : "Old AI Response Method"
action :
- service : ha_text_ai.ask_question
data :
question : "Long question here..."
instance : sensor.ha_text_ai_gpt
- delay : "00:00:05" # Wait for sensor update
- service : notify.mobile
data :
message : "{{ state_attr('sensor.ha_text_ai_gpt', 'response')[:255] }}..." # Truncated!
```
#### New Method (Unlimited):
```yaml
# ✅ New way - unlimited length, immediate access, no race conditions
automation :
- alias : "New AI Response Method"
action :
- service : ha_text_ai.ask_question
data :
question : "Long question here..."
instance : sensor.ha_text_ai_gpt
response_variable : ai_response # Direct access!
- service : notify.mobile
data :
message : "{{ ai_response.response_text }}" # Full response, no truncation!
```
2024-11-25 17:59:17 +03:00
### 🏷️ HA Text AI Sensor Naming Convention
2024-11-28 23:27:39 +03:00
#### Character Restrictions
- Only lowercase letters (a-z)
- Numbers (0-9)
- Underscore (_)
2024-11-29 00:21:21 +03:00
- Maximum length: 50 characters (including `ha_text_ai_` )
2024-11-28 23:27:39 +03:00
2024-11-25 17:59:17 +03:00
#### Sensor Name Structure
```yaml
# Always starts with 'sensor.ha_text_ai_'
# You define only the part after the underscore
sensor.ha_text_ai_YOUR_UNIQUE_SUFFIX
# Examples:
sensor.ha_text_ai_gpt # GPT-based sensor
sensor.ha_text_ai_claude # Claude-based sensor
2024-12-05 01:55:31 +03:00
sensor.ha_text_ai_abc # Custom suffix
2024-11-25 17:59:17 +03:00
```
#### Response Retrieval
```yaml
# Use your specific sensor name
{{ state_attr('sensor.ha_text_ai_gpt', 'response') }}
```
#### Practical Usage
```yaml
automation :
- alias : "AI Response with Custom Sensor"
action :
- service : ha_text_ai.ask_question
data :
question : "Home automation advice"
2024-12-07 00:48:17 +03:00
instance : sensor.ha_text_ai_gpt
2024-11-25 17:59:17 +03:00
- service : notify.mobile
data :
message : >
AI Tip:
{{ state_attr('sensor.ha_text_ai_gpt', 'response') }}
```
### 💡 Naming Rules
- Prefix is always `sensor.ha_text_ai_`
- Add your unique identifier after the underscore
- Use lowercase
- No spaces allowed
- Keep it descriptive but concise
### 🔍 HA Text AI Sensor Attributes
2024-12-05 02:00:24 +03:00
- 🤖 **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
2024-12-06 02:53:41 +03:00
- 💬 **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.
2024-12-05 02:00:24 +03:00
- 🕒 **Last Interaction Details** : Recent query and response tracking
- ❤️ **System Health** : Error monitoring and service uptime
<details>
<summary>📦 Detailed Sensor Attributes</summary>
2024-11-25 17:59:17 +03:00
#### Model and Provider Information
```yaml
2024-11-26 15:01:40 +03:00
# Name of the AI model currently in use (e.g., latest version of GPT)
{{ state_attr('sensor.ha_text_ai_gpt', 'Model') }} # gpt-4o
# Service provider for the AI model (determines API endpoint and authentication)
{{ state_attr('sensor.ha_text_ai_gpt', 'Api provider') }} # openai
# Previous or alternative model configuration
2024-11-25 17:59:17 +03:00
{{ state_attr('sensor.ha_text_ai_gpt', 'Last model') }} # gpt-4o
```
#### System Status
```yaml
2024-11-26 15:01:40 +03:00
# Current operational readiness of the AI service API
{{ state_attr('sensor.ha_text_ai_gpt', 'Api status') }} # ready
# Indicates if a request is currently being processed
{{ state_attr('sensor.ha_text_ai_gpt', 'Is processing') }} # false
# Shows if the API has hit its request rate limit
{{ state_attr('sensor.ha_text_ai_gpt', 'Is rate limited') }} # false
# Status of the specific API endpoint being used
2024-11-25 17:59:17 +03:00
{{ state_attr('sensor.ha_text_ai_gpt', 'Endpoint status') }} # ready
```
#### Performance Metrics
```yaml
2024-11-26 15:01:40 +03:00
# Total number of successfully completed API requests
{{ state_attr('sensor.ha_text_ai_gpt', 'Successful requests') }} # 0
# Number of API requests that encountered errors
{{ state_attr('sensor.ha_text_ai_gpt', 'Failed requests') }} # 0
# Mean time taken to receive a response from the AI service
{{ state_attr('sensor.ha_text_ai_gpt', 'Average latency') }} # 0
# Maximum time taken for a single request-response cycle
2024-11-25 17:59:17 +03:00
{{ state_attr('sensor.ha_text_ai_gpt', 'Max latency') }} # 0
```
#### Conversation and Token Usage
```yaml
2024-11-26 15:01:40 +03:00
# Number of previous interactions stored in conversation context
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
# Total number of tokens used across all interactions
{{ state_attr('sensor.ha_text_ai_gpt', 'Total tokens') }} # 0
# Tokens used in the input prompts
{{ state_attr('sensor.ha_text_ai_gpt', 'Prompt tokens') }} # 0
# Tokens used in the AI's generated responses
2024-11-25 17:59:17 +03:00
{{ state_attr('sensor.ha_text_ai_gpt', 'Completion tokens') }} # 0
2024-12-03 18:29:24 +03:00
# Number of entries in current history file
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
2024-12-10 23:33:32 +03:00
# Last few conversation entries (limited to 1 for performance)
2024-12-03 18:29:24 +03:00
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
2024-11-25 17:59:17 +03:00
```
#### Last Interaction Details
```yaml
2024-11-26 15:01:40 +03:00
# Most recent complete response generated by the AI service
{{ state_attr('sensor.ha_text_ai_gpt', 'Response') }} # Last AI response
# The most recently processed user query or prompt
{{ state_attr('sensor.ha_text_ai_gpt', 'Question') }} # Last asked question
# Precise moment when the last interaction occurred (useful for tracking and logging)
2024-11-25 17:59:17 +03:00
{{ state_attr('sensor.ha_text_ai_gpt', 'Last timestamp') }} # Timestamp
```
#### System Health
```yaml
2024-11-26 15:01:40 +03:00
# Cumulative count of all errors encountered during AI service interactions
{{ state_attr('sensor.ha_text_ai_gpt', 'Total errors') }} # 0
# Indicates if the AI service is currently undergoing scheduled or emergency maintenance
{{ state_attr('sensor.ha_text_ai_gpt', 'Is maintenance') }} # false
# Total continuous operational time of the AI service (in hours or days)
2024-11-25 17:59:17 +03:00
{{ state_attr('sensor.ha_text_ai_gpt', 'Uptime') }} # 547,58
```
2024-12-03 18:29:24 +03:00
### History Storage
Conversation history stored in `.storage/ha_text_ai_history/` directory:
2024-12-06 02:53:41 +03:00
- Each instance has its own history file (JSON)
2024-12-03 18:29:24 +03:00
- Files are automatically rotated when size limit is reached
- Archived history files are timestamped
- Default maximum file size: 1MB
2024-11-25 17:59:17 +03:00
### 💡 Pro Tips
- Always check attribute existence
- Use these attributes for monitoring and automation
- Some values might be 0 or empty initially
2024-12-05 02:00:24 +03:00
</details>
2024-11-25 17:59:17 +03:00
2024-11-19 14:06:32 +03:00
## 📘 FAQ
2024-11-19 19:03:51 +03:00
**Q: Which AI providers are supported?**
2025-09-02 02:06:58 +03:00
A: OpenAI (GPT models), Anthropic (Claude models), DeepSeek, Google Gemini, and OpenRouter are officially supported, with many other OpenAI-compatible providers working as well.
2024-11-19 19:03:51 +03:00
**Q: How can I reduce API costs?**
2025-09-02 02:11:34 +03:00
A: Use gpt-4o-mini or claude-3.5-haiku for most queries, implement caching, and optimize token usage.
2024-11-19 19:03:51 +03:00
2024-11-22 01:56:36 +03:00
**Q: Are there limitations on the number of requests?**
A: Depends on your API provider's plan. We recommend monitoring usage and implementing request throttling via `request_interval` configuration.
2024-11-19 19:31:26 +03:00
2024-11-22 01:56:36 +03:00
**Q: Can I use custom models?**
2024-11-19 19:03:51 +03:00
A: Yes, you can configure custom endpoints and use any compatible model by specifying it in the configuration.
**Q: How do I switch between different AI providers?**
A: Simply change the model parameter in your configuration or service calls to use the desired provider's model.
2025-09-02 02:06:58 +03:00
**Q: What are the token limits for different models?**
A: Token limits vary by provider and model. OpenAI's gpt-4o supports up to 128K tokens, Claude 3.5 Sonnet supports up to 200K tokens, while smaller models typically have 8K-32K limits. Check your provider's documentation for specific limits.
**Q: How do I monitor token usage?**
A: Use the sensor attributes like `Total tokens` , `Prompt tokens` , and `Completion tokens` to track usage. You can also create automations to alert you when usage exceeds certain thresholds.
2024-11-19 14:06:32 +03:00
**Q: Is my data secure?**
2024-11-22 02:00:42 +03:00
A: Yes, your data is secure. The system operates entirely on your local machine, keeping your data under your control. API keys are stored securely and all external communications use encrypted connections.
2024-11-19 14:06:32 +03:00
2024-11-25 15:42:04 +03:00
**Q: How do context messages work?**
A: Context messages allow the AI to remember and reference previous conversation history. By default, 5 previous messages are included, but you can customize this from 1 to 20 messages to control the conversation depth and token usage.
2024-12-03 18:29:24 +03:00
**Q: Where is conversation history stored?**
A: History is stored in files under the `.storage/ha_text_ai_history/` directory, with automatic rotation and size management.
**Q: Can I access old conversation history?**
A: Yes, archived history files are stored with timestamps and can be accessed manually if needed.
**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.
2024-12-04 23:28:14 +03:00
2024-11-19 12:45:26 +03:00
## 🤝 Contributing
2024-11-18 10:59:06 +03:00
2024-11-19 14:06:32 +03:00
Contributions welcome! Please read our [Contributing Guide ](CONTRIBUTING.md ).
2024-11-18 10:59:06 +03:00
1. Fork the repository
2024-11-19 14:06:32 +03:00
2. Create feature branch (`git checkout -b feature/Enhancement` )
3. Commit changes (`git commit -m 'Add Enhancement'` )
4. Push branch (`git push origin feature/Enhancement` )
5. Open Pull Request
2024-11-19 12:45:26 +03:00
2024-11-29 16:27:04 +03:00
## Legal Disclaimer and Limitation of Liability
### Software Disclaimer
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
2024-11-19 12:45:26 +03:00
## 📝 License
2024-11-29 16:27:04 +03:00
Author: SMKRV
2024-11-29 16:54:41 +03:00
[CC BY-NC-SA 4.0 ](https://creativecommons.org/licenses/by-nc-sa/4.0/ ) - see [LICENSE ](LICENSE ) for details.
2024-11-14 18:39:06 +03:00
2024-11-26 00:09:46 +03:00
## 💡 Support the Project
The best support is:
- Sharing feedback
- Contributing ideas
- Recommending to friends
- Reporting issues
- Star the repository
If you want to say thanks financially, you can send a small token of appreciation in USDT:
**USDT Wallet (TRC10/TRC20):**
`TXC9zYHYPfWUGi4Sv4R1ctTBGScXXQk5HZ`
*Open-source is built by community passion!* 🚀
2024-11-18 10:54:24 +03:00
---
2024-11-14 18:39:06 +03:00
2024-12-06 16:13:27 +03:00
<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>
2024-11-18 10:59:06 +03:00
<div align="center">
2024-11-14 18:39:06 +03:00
2025-09-02 02:06:58 +03:00
Made with ❤️ for the Home Assistant Community
2024-11-14 18:39:06 +03:00
2024-11-19 14:06:32 +03:00
[Report Bug ](https://github.com/smkrv/ha-text-ai/issues ) · [Request Feature ](https://github.com/smkrv/ha-text-ai/issues )
2024-11-18 10:59:06 +03:00
</div>
2025-09-02 23:50:20 +03:00