mirror of
https://github.com/smkrv/ha-text-ai.git
synced 2026-07-22 07:03:58 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3097106e93 | ||
|
|
35073960b8 | ||
|
|
8d0e0b5e44 | ||
|
|
e91c3701c5 | ||
|
|
7f62101b3e | ||
|
|
3729c3736f | ||
|
|
f5ce5e459a | ||
|
|
4064486b1e | ||
|
|
185778dbd0 | ||
|
|
83a255dee0 | ||
|
|
6b66dd6a4d | ||
|
|
bd82f23120 | ||
|
|
eee9754033 | ||
|
|
517b1f11ae | ||
|
|
ed8f19bfa9 | ||
|
|
7e3daf611b | ||
|
|
37919be70f | ||
|
|
e427254584 |
@@ -1,5 +1,6 @@
|
||||
name: Validate with hassfest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
name: Validate
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
<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/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;"/>
|
||||
<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;"/>
|
||||
|
||||
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
||||
</div>
|
||||
@@ -106,7 +106,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
- Home Assistant 2024.2.2 or later
|
||||
- Home Assistant 2024.12.0 or later (recommended for best compatibility)
|
||||
- Active API key from:
|
||||
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
||||
- Anthropic ([Get key](https://console.anthropic.com/))
|
||||
@@ -120,7 +120,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
||||
## Configuration Options
|
||||
|
||||
### 🔧 **Core Configuration Settings**
|
||||
- 🌐 **API Provider**: OpenAI/Anthropic/DeepSeek
|
||||
- 🌐 **API Provider**: OpenAI/Anthropic/DeepSeek/Gemini
|
||||
- 🔑 **API Key**: Provider-specific authentication
|
||||
- 🤖 **Model Selection**: Flexible, provider-specific models
|
||||
- 🌡️ **Temperature**: Creativity control (0.0-2.0)
|
||||
@@ -129,6 +129,25 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
||||
- 💾 **History Size**: Number of messages to retain
|
||||
- 🌍 **Custom API Endpoint**: Optional advanced configuration
|
||||
|
||||
### 🤖 **Recommended Models**
|
||||
|
||||
#### OpenAI Models
|
||||
- **GPT-5** - The latest flagship model, best for complex reasoning
|
||||
- **GPT-5 mini** - A cost-effective and fast model, suitable for most tasks
|
||||
|
||||
#### Anthropic Claude Models
|
||||
- **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
|
||||
|
||||
#### DeepSeek Models
|
||||
- **DeepSeek-V3.1** - A general-purpose model for a wide range of tasks
|
||||
- **DeepSeek-R1** - A specialized model focused on reasoning and coding
|
||||
|
||||
#### Google Gemini Models
|
||||
- **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
|
||||
|
||||
<details>
|
||||
<summary>🌐 Potentially Compatible Providers</summary>
|
||||
|
||||
@@ -166,12 +185,17 @@ To be compatible, a provider should support:
|
||||
<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>
|
||||
1. Open HACS in Home Assistant
|
||||
2. Click on "Integrations"
|
||||
3. Click "..." in top right corner
|
||||
4. Select "Custom repositories"
|
||||
5. Add repository URL: `https://github.com/smkrv/ha-text-ai`
|
||||
6. Choose "Integration" as category
|
||||
7. Click "Download"
|
||||
8. Restart Home Assistant
|
||||
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"
|
||||
|
||||
### Manual Installation
|
||||
1. Download the latest release
|
||||
@@ -196,7 +220,7 @@ To be compatible, a provider should support:
|
||||
ha_text_ai:
|
||||
api_provider: openai # Required
|
||||
api_key: !secret ai_api_key # Required
|
||||
model: gpt-4o-mini # Strongly recommended
|
||||
model: gpt-4o # Strongly recommended
|
||||
temperature: 0.7 # Optional
|
||||
max_tokens: 1000 # Optional
|
||||
request_interval: 1.0 # Optional
|
||||
@@ -213,7 +237,7 @@ sensor:
|
||||
- platform: ha_text_ai
|
||||
name: "My AI Assistant" # Required, unique identifier
|
||||
api_provider: openai # Optional (inherits from platform)
|
||||
model: "gpt-4o-mini" # Optional
|
||||
model: "gpt-4o" # Optional
|
||||
temperature: 0.7 # Optional
|
||||
max_tokens: 1000 # Optional
|
||||
```
|
||||
@@ -224,16 +248,16 @@ sensor:
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| `api_provider` | String | ✅ | - | AI service provider (openai, anthropic) |
|
||||
| `api_provider` | String | ✅ | - | AI service provider (openai, anthropic, deepseek, gemini) |
|
||||
| `api_key` | String | ✅ | - | Authentication key for AI service |
|
||||
| `model` | String | ⚠️ | Provider default | Strongly recommended: Specific AI model to use. If not specified, the provider's default model will be used |
|
||||
| `temperature` | Float | ❌ | 0.7 | Response creativity level (0.0-2.0) |
|
||||
| `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) |
|
||||
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
|
||||
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
|
||||
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
|
||||
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
|
||||
| `max_history_size` | Integer | ❌ | 100 | Maximum number of conversation entries to store |
|
||||
| `history_file_size` | Integer | ⚠️ | 1 | Maximum history file size in MB |
|
||||
| `max_history_size` | Integer | ❌ | 50 | Maximum number of conversation entries to store |
|
||||
| `context_messages` | Integer | ❌ | 5 | Number of previous messages to include in context (1-20) |
|
||||
|
||||
#### Sensor Configuration
|
||||
|
||||
@@ -242,25 +266,51 @@ sensor:
|
||||
| `platform` | String | ✅ | - | Must be `ha_text_ai` |
|
||||
| `name` | String | ✅ | - | Unique sensor identifier |
|
||||
| `api_provider` | String | ❌ | Platform setting | Override global provider |
|
||||
| `model` | String | ⚠️ | Platform setting | Recommended: Override global model. If not specified, uses platform or provider default |
|
||||
| `temperature` | Float | ❌ | Platform setting | Override global temperature |
|
||||
| `max_tokens` | Integer | ❌ | Platform setting | Override global max tokens |
|
||||
| `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 |
|
||||
|
||||
</details>
|
||||
|
||||
## 🛠️ Available Services
|
||||
|
||||
### 🔄 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
|
||||
|
||||
### ask_question
|
||||
```yaml
|
||||
service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: "What's the optimal temperature for sleeping?"
|
||||
model: "claude-3-sonnet" # optional
|
||||
model: "claude-3.5-sonnet" # optional
|
||||
temperature: 0.5 # optional
|
||||
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
|
||||
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
|
||||
model_used: "claude-3.5-sonnet"
|
||||
instance: "sensor.ha_text_ai_gpt"
|
||||
question: "What's the optimal temperature for sleeping?"
|
||||
timestamp: "2025-02-09T16:57:00.000Z"
|
||||
success: true
|
||||
# error: "Error message" (only present if success: false)
|
||||
```
|
||||
|
||||
### set_system_prompt
|
||||
@@ -287,11 +337,157 @@ data:
|
||||
```yaml
|
||||
service: ha_text_ai.get_history
|
||||
data:
|
||||
limit: 5 # optional
|
||||
filter_model: "gpt-4o" # optional
|
||||
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"
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
```
|
||||
|
||||
## 🚀 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!
|
||||
```
|
||||
|
||||
### 🏷️ HA Text AI Sensor Naming Convention
|
||||
|
||||
#### Character Restrictions
|
||||
@@ -457,10 +653,10 @@ Conversation history stored in `.storage/ha_text_ai_history/` directory:
|
||||
## 📘 FAQ
|
||||
|
||||
**Q: Which AI providers are supported?**
|
||||
A: Currently OpenAI (GPT models) and Anthropic (Claude models) are supported, with more providers planned.
|
||||
A: OpenAI (GPT models), Anthropic (Claude models), DeepSeek, Google Gemini, and OpenRouter are officially supported, with many other OpenAI-compatible providers working as well.
|
||||
|
||||
**Q: How can I reduce API costs?**
|
||||
A: Use GPT-3.5-Turbo or Claude-3-Sonnet for most queries, implement caching, and optimize token usage.
|
||||
A: Use gpt-4o-mini or claude-3.5-haiku for most queries, implement caching, and optimize token usage.
|
||||
|
||||
**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.
|
||||
@@ -471,8 +667,11 @@ A: Yes, you can configure custom endpoints and use any compatible model by speci
|
||||
**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.
|
||||
|
||||
**Q: How can I reduce API costs?**
|
||||
A: Use GPT-3.5-Turbo for most queries, implement caching, and optimize token usage.
|
||||
**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.
|
||||
|
||||
**Q: Is my data secure?**
|
||||
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.
|
||||
@@ -538,9 +737,9 @@ 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 ❤️ for the Home Assistant Community,
|
||||
utilizing Claude 3.5 Sonnet, Gemini Pro 1.5, and Qwen 2.5 Coder 32B Instruct.
|
||||
Made with ❤️ for the Home Assistant Community
|
||||
|
||||
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
# Using response_variable with HA Text AI
|
||||
|
||||
After updating the HA Text AI integration, it now supports using the `response_variable` parameter in Home Assistant scripts and automations.
|
||||
|
||||
## What Changed
|
||||
|
||||
- Added response schema support in the `ha_text_ai.ask_question` service
|
||||
- Service is now correctly registered with `supports_response=True` flag
|
||||
- You can now use `response_variable` to capture AI response in a variable
|
||||
|
||||
## Example Usage in Script
|
||||
|
||||
```yaml
|
||||
action: ha_text_ai.ask_question
|
||||
data:
|
||||
context_messages: 0
|
||||
temperature: 0.7
|
||||
max_tokens: 1000
|
||||
instance: sensor.ha_text_ai_gemini
|
||||
question: "What time is it?"
|
||||
response_variable: ai_response
|
||||
```
|
||||
|
||||
## Example Usage in Automation
|
||||
|
||||
```yaml
|
||||
alias: "Get AI Response"
|
||||
trigger:
|
||||
- platform: state
|
||||
entity_id: input_boolean.ask_ai
|
||||
to: "on"
|
||||
action:
|
||||
- action: ha_text_ai.ask_question
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gemini
|
||||
question: "What's the current weather?"
|
||||
temperature: 0.7
|
||||
max_tokens: 500
|
||||
response_variable: weather_response
|
||||
|
||||
- action: notify.persistent_notification
|
||||
data:
|
||||
title: "AI Response"
|
||||
message: "{{ weather_response.response_text }}"
|
||||
```
|
||||
|
||||
## Available Fields in response_variable
|
||||
|
||||
When you use `response_variable`, you will receive an object with the following fields:
|
||||
|
||||
- `response_text` (string) - The AI response text
|
||||
- `tokens_used` (integer) - Total number of tokens used
|
||||
- `prompt_tokens` (integer) - Number of tokens in the prompt
|
||||
- `completion_tokens` (integer) - Number of tokens in the completion
|
||||
- `model_used` (string) - The AI model that was used for the response
|
||||
- `instance` (string) - The instance name that was used
|
||||
- `question` (string) - The original question that was asked
|
||||
- `timestamp` (string) - ISO timestamp when the response was generated
|
||||
- `success` (boolean) - Whether the request was successful
|
||||
- `error` (string) - Error message if the request failed
|
||||
|
||||
## Example Using Response Fields
|
||||
|
||||
```yaml
|
||||
action:
|
||||
- action: ha_text_ai.ask_question
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gemini
|
||||
question: "Tell me a joke"
|
||||
response_variable: joke_response
|
||||
|
||||
- condition: template
|
||||
value_template: "{{ joke_response.success }}"
|
||||
|
||||
- action: input_text.set_value
|
||||
target:
|
||||
entity_id: input_text.last_ai_response
|
||||
data:
|
||||
value: "{{ joke_response.response_text }}"
|
||||
|
||||
- action: input_number.set_value
|
||||
target:
|
||||
entity_id: input_number.tokens_used
|
||||
data:
|
||||
value: "{{ joke_response.tokens_used }}"
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```yaml
|
||||
action:
|
||||
- action: ha_text_ai.ask_question
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gemini
|
||||
question: "Test question"
|
||||
response_variable: ai_result
|
||||
|
||||
- choose:
|
||||
- conditions:
|
||||
- condition: template
|
||||
value_template: "{{ ai_result.success }}"
|
||||
sequence:
|
||||
- action: notify.mobile_app_phone
|
||||
data:
|
||||
title: "AI Response"
|
||||
message: "{{ ai_result.response_text }}"
|
||||
- conditions:
|
||||
- condition: template
|
||||
value_template: "{{ not ai_result.success }}"
|
||||
sequence:
|
||||
- action: notify.mobile_app_phone
|
||||
data:
|
||||
title: "AI Error"
|
||||
message: "Error: {{ ai_result.error }}"
|
||||
```
|
||||
|
||||
## Migration from Old Approach
|
||||
|
||||
**Old method (without response_variable):**
|
||||
```yaml
|
||||
# Ask question
|
||||
- action: ha_text_ai.ask_question
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gemini
|
||||
question: "Hello!"
|
||||
|
||||
# Wait and read response from sensor
|
||||
- delay: 00:00:05
|
||||
- action: notify.mobile_app_phone
|
||||
data:
|
||||
message: "{{ states('sensor.ha_text_ai_gemini') }}"
|
||||
```
|
||||
|
||||
**New method (with response_variable):**
|
||||
```yaml
|
||||
# Ask question and get response immediately
|
||||
- action: ha_text_ai.ask_question
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gemini
|
||||
question: "Hello!"
|
||||
response_variable: greeting_response
|
||||
|
||||
- action: notify.mobile_app_phone
|
||||
data:
|
||||
message: "{{ greeting_response.response_text }}"
|
||||
```
|
||||
|
||||
The new approach is more reliable as it doesn't require waiting and reading from the sensor.
|
||||
@@ -35,6 +35,7 @@ from .const import (
|
||||
CONF_MAX_TOKENS,
|
||||
CONF_API_ENDPOINT,
|
||||
CONF_REQUEST_INTERVAL,
|
||||
CONF_API_TIMEOUT,
|
||||
CONF_API_PROVIDER,
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
API_PROVIDER_OPENAI,
|
||||
@@ -51,8 +52,8 @@ from .const import (
|
||||
DEFAULT_DEEPSEEK_ENDPOINT,
|
||||
DEFAULT_GEMINI_ENDPOINT,
|
||||
DEFAULT_REQUEST_INTERVAL,
|
||||
DEFAULT_API_TIMEOUT,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
API_TIMEOUT,
|
||||
SERVICE_ASK_QUESTION,
|
||||
SERVICE_CLEAR_HISTORY,
|
||||
SERVICE_GET_HISTORY,
|
||||
@@ -86,6 +87,9 @@ SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
|
||||
vol.Required("instance"): cv.string,
|
||||
vol.Optional("limit"): cv.positive_int,
|
||||
vol.Optional("filter_model"): cv.string,
|
||||
vol.Optional("start_date"): cv.string,
|
||||
vol.Optional("include_metadata"): cv.boolean,
|
||||
vol.Optional("sort_order"): vol.In(["newest", "oldest"]),
|
||||
})
|
||||
|
||||
def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAICoordinator:
|
||||
@@ -112,11 +116,11 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
# Initialize domain data storage
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
|
||||
async def async_ask_question(call: ServiceCall) -> None:
|
||||
"""Handle ask_question service."""
|
||||
async def async_ask_question(call: ServiceCall) -> dict:
|
||||
"""Handle ask_question service with response data."""
|
||||
try:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
await coordinator.async_ask_question(
|
||||
response = await coordinator.async_ask_question(
|
||||
question=call.data["question"],
|
||||
model=call.data.get("model"),
|
||||
temperature=call.data.get("temperature"),
|
||||
@@ -124,9 +128,34 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
system_prompt=call.data.get("system_prompt"),
|
||||
context_messages=call.data.get("context_messages"),
|
||||
)
|
||||
|
||||
# Return structured response data
|
||||
return {
|
||||
"response_text": response.get("content", ""),
|
||||
"tokens_used": response.get("tokens", {}).get("total", 0),
|
||||
"prompt_tokens": response.get("tokens", {}).get("prompt", 0),
|
||||
"completion_tokens": response.get("tokens", {}).get("completion", 0),
|
||||
"model_used": response.get("model", call.data.get("model", coordinator.model)),
|
||||
"instance": call.data["instance"],
|
||||
"question": call.data["question"],
|
||||
"timestamp": response.get("timestamp"),
|
||||
"success": True
|
||||
}
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error asking question: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to process question: {str(err)}")
|
||||
# Return error response
|
||||
return {
|
||||
"response_text": "",
|
||||
"tokens_used": 0,
|
||||
"prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"model_used": call.data.get("model", ""),
|
||||
"instance": call.data["instance"],
|
||||
"question": call.data["question"],
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
"success": False,
|
||||
"error": str(err)
|
||||
}
|
||||
|
||||
async def async_clear_history(call: ServiceCall) -> None:
|
||||
"""Handle clear_history service."""
|
||||
@@ -143,7 +172,10 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
return await coordinator.async_get_history(
|
||||
limit=call.data.get("limit"),
|
||||
filter_model=call.data.get("filter_model")
|
||||
filter_model=call.data.get("filter_model"),
|
||||
start_date=call.data.get("start_date"),
|
||||
include_metadata=call.data.get("include_metadata", False),
|
||||
sort_order=call.data.get("sort_order", "newest")
|
||||
)
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error getting history: %s", str(err))
|
||||
@@ -163,7 +195,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
DOMAIN,
|
||||
SERVICE_ASK_QUESTION,
|
||||
async_ask_question,
|
||||
schema=SERVICE_SCHEMA_ASK_QUESTION
|
||||
schema=SERVICE_SCHEMA_ASK_QUESTION,
|
||||
supports_response=True
|
||||
)
|
||||
|
||||
hass.services.async_register(
|
||||
@@ -236,7 +269,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
|
||||
return True
|
||||
|
||||
async def async_check_api(session, endpoint: str, headers: dict, provider: str) -> bool:
|
||||
async def async_check_api(session, endpoint: str, headers: dict, provider: str, api_timeout: int = DEFAULT_API_TIMEOUT) -> bool:
|
||||
"""Check API availability for different providers."""
|
||||
try:
|
||||
if provider == API_PROVIDER_GEMINI:
|
||||
@@ -253,7 +286,7 @@ async def async_check_api(session, endpoint: str, headers: dict, provider: str)
|
||||
else: # OpenAI
|
||||
check_url = f"{endpoint}/models"
|
||||
|
||||
async with timeout(API_TIMEOUT):
|
||||
async with timeout(api_timeout):
|
||||
async with session.get(check_url, headers=headers) as response:
|
||||
if response.status in [200, 404]:
|
||||
return True
|
||||
@@ -279,22 +312,24 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
_LOGGER.error("API provider not specified")
|
||||
raise ConfigEntryNotReady("API provider is required")
|
||||
|
||||
# Get configuration
|
||||
# Get configuration (merge data with options to apply any runtime changes)
|
||||
config = {**entry.data, **entry.options}
|
||||
session = aiohttp_client.async_get_clientsession(hass)
|
||||
api_provider = entry.data.get(CONF_API_PROVIDER)
|
||||
model = entry.data.get(CONF_MODEL, DEFAULT_MODEL)
|
||||
endpoint = entry.data.get(
|
||||
api_provider = config.get(CONF_API_PROVIDER)
|
||||
model = config.get(CONF_MODEL, DEFAULT_MODEL)
|
||||
endpoint = config.get(
|
||||
CONF_API_ENDPOINT,
|
||||
DEFAULT_OPENAI_ENDPOINT if api_provider == API_PROVIDER_OPENAI
|
||||
else DEFAULT_ANTHROPIC_ENDPOINT
|
||||
).rstrip('/')
|
||||
api_key = entry.data[CONF_API_KEY]
|
||||
api_key = entry.data[CONF_API_KEY] # API key stays in data, not in options
|
||||
instance_name = entry.data.get(CONF_NAME, entry.entry_id)
|
||||
request_interval = entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||
max_tokens = entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||
temperature = entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||
max_history_size = entry.data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||
context_messages = entry.data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||
request_interval = config.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||
api_timeout = config.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
|
||||
max_tokens = config.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||
temperature = config.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||
max_history_size = config.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||
context_messages = config.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||
is_anthropic = api_provider == API_PROVIDER_ANTHROPIC
|
||||
|
||||
headers = {
|
||||
@@ -308,7 +343,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
else:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
if not await async_check_api(session, endpoint, headers, api_provider):
|
||||
if not await async_check_api(session, endpoint, headers, api_provider, api_timeout):
|
||||
raise ConfigEntryNotReady("API connection failed")
|
||||
|
||||
_LOGGER.debug("Creating API client for %s with endpoint %s", api_provider, endpoint)
|
||||
@@ -319,6 +354,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
headers=headers,
|
||||
api_provider=api_provider,
|
||||
model=model,
|
||||
api_timeout=api_timeout,
|
||||
)
|
||||
|
||||
coordinator = HATextAICoordinator(
|
||||
@@ -332,6 +368,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
max_history_size=max_history_size,
|
||||
context_messages=context_messages,
|
||||
is_anthropic=is_anthropic,
|
||||
api_timeout=api_timeout,
|
||||
)
|
||||
|
||||
_LOGGER.debug(f"Created coordinator for {instance_name}")
|
||||
|
||||
@@ -16,7 +16,7 @@ from datetime import datetime, timedelta
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from .const import (
|
||||
API_TIMEOUT,
|
||||
DEFAULT_API_TIMEOUT,
|
||||
API_RETRY_COUNT,
|
||||
API_PROVIDER_ANTHROPIC,
|
||||
API_PROVIDER_DEEPSEEK,
|
||||
@@ -41,6 +41,7 @@ class APIClient:
|
||||
headers: Dict[str, str],
|
||||
api_provider: str,
|
||||
model: str,
|
||||
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||
) -> None:
|
||||
"""Initialize API client."""
|
||||
self.session = session
|
||||
@@ -48,21 +49,38 @@ class APIClient:
|
||||
self.headers = headers
|
||||
self.api_provider = api_provider
|
||||
self.model = model
|
||||
self.timeout = ClientTimeout(total=API_TIMEOUT)
|
||||
self.api_timeout = api_timeout
|
||||
self.timeout = ClientTimeout(total=api_timeout)
|
||||
self._closed = False
|
||||
|
||||
async def __aenter__(self):
|
||||
"""Async context manager entry."""
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Async context manager exit."""
|
||||
await self.shutdown()
|
||||
|
||||
def _validate_parameters(
|
||||
self,
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> None:
|
||||
"""Validate API parameters."""
|
||||
"""Validate API parameters with enhanced type checking."""
|
||||
# Type validation
|
||||
if not isinstance(temperature, (int, float)):
|
||||
raise TypeError(f"Temperature must be a number, got {type(temperature)}")
|
||||
if not isinstance(max_tokens, int):
|
||||
raise TypeError(f"Max tokens must be an integer, got {type(max_tokens)}")
|
||||
|
||||
# Range validation
|
||||
if not MIN_TEMPERATURE <= temperature <= MAX_TEMPERATURE:
|
||||
raise ValueError(
|
||||
f"Temperature must be between {MIN_TEMPERATURE} and {MAX_TEMPERATURE}"
|
||||
f"Temperature must be between {MIN_TEMPERATURE} and {MAX_TEMPERATURE}, got {temperature}"
|
||||
)
|
||||
if not MIN_MAX_TOKENS <= max_tokens <= MAX_MAX_TOKENS:
|
||||
raise ValueError(
|
||||
f"Max tokens must be between {MIN_MAX_TOKENS} and {MAX_MAX_TOKENS}"
|
||||
f"Max tokens must be between {MIN_MAX_TOKENS} and {MAX_MAX_TOKENS}, got {max_tokens}"
|
||||
)
|
||||
|
||||
async def _make_request(
|
||||
@@ -71,10 +89,13 @@ class APIClient:
|
||||
payload: Dict[str, Any],
|
||||
) -> Dict[str, Any]:
|
||||
"""Make API request with retry logic."""
|
||||
_LOGGER.debug(f"API Request: URL={url}, Payload={payload}")
|
||||
# Log request without sensitive data
|
||||
safe_payload = {k: v for k, v in payload.items() if k not in ['messages', 'system']}
|
||||
_LOGGER.debug(f"API Request: URL={url}, Safe payload: {safe_payload}")
|
||||
|
||||
for attempt in range(API_RETRY_COUNT):
|
||||
try:
|
||||
async with timeout(API_TIMEOUT):
|
||||
async with timeout(self.api_timeout):
|
||||
async with self.session.post(
|
||||
url,
|
||||
json=payload,
|
||||
@@ -84,16 +105,18 @@ class APIClient:
|
||||
_LOGGER.debug(f"Response status: {response.status}")
|
||||
if response.status != 200:
|
||||
error_data = await response.json()
|
||||
_LOGGER.error(f"API error: {error_data}")
|
||||
raise HomeAssistantError(f"API error: {error_data}")
|
||||
# Log error without sensitive data
|
||||
safe_error = {k: v for k, v in error_data.items() if k not in ['message', 'details']}
|
||||
_LOGGER.error(f"API error (status {response.status}): {safe_error}")
|
||||
raise HomeAssistantError(f"API error: status {response.status}")
|
||||
return await response.json()
|
||||
except asyncio.TimeoutError:
|
||||
_LOGGER.warning(f"Timeout on attempt {attempt + 1}")
|
||||
_LOGGER.warning(f"Timeout on attempt {attempt + 1}/{API_RETRY_COUNT}")
|
||||
if attempt == API_RETRY_COUNT - 1:
|
||||
raise HomeAssistantError("API request timed out")
|
||||
await asyncio.sleep(1 * (attempt + 1))
|
||||
except Exception as e:
|
||||
_LOGGER.warning(f"API request failed on attempt {attempt + 1}: {str(e)}")
|
||||
_LOGGER.warning(f"API request failed on attempt {attempt + 1}/{API_RETRY_COUNT}: {type(e).__name__}")
|
||||
if attempt == API_RETRY_COUNT - 1:
|
||||
raise
|
||||
await asyncio.sleep(1 * (attempt + 1))
|
||||
|
||||
@@ -25,6 +25,7 @@ from .const import (
|
||||
CONF_MAX_TOKENS,
|
||||
CONF_API_ENDPOINT,
|
||||
CONF_REQUEST_INTERVAL,
|
||||
CONF_API_TIMEOUT,
|
||||
CONF_API_PROVIDER,
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
API_PROVIDER_OPENAI,
|
||||
@@ -38,6 +39,7 @@ from .const import (
|
||||
DEFAULT_TEMPERATURE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_REQUEST_INTERVAL,
|
||||
DEFAULT_API_TIMEOUT,
|
||||
DEFAULT_OPENAI_ENDPOINT,
|
||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||
DEFAULT_DEEPSEEK_ENDPOINT,
|
||||
@@ -48,6 +50,8 @@ from .const import (
|
||||
MIN_MAX_TOKENS,
|
||||
MAX_MAX_TOKENS,
|
||||
MIN_REQUEST_INTERVAL,
|
||||
MIN_API_TIMEOUT,
|
||||
MAX_API_TIMEOUT,
|
||||
DEFAULT_NAME_PREFIX,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
@@ -131,6 +135,10 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(CONF_API_TIMEOUT, default=DEFAULT_API_TIMEOUT): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=DEFAULT_CONTEXT_MESSAGES
|
||||
@@ -182,6 +190,10 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(CONF_API_TIMEOUT, default=input_copy.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=input_copy.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||
@@ -224,6 +236,10 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(CONF_API_TIMEOUT, default=input_copy.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=input_copy.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||
@@ -282,6 +298,10 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(CONF_API_TIMEOUT, default=input_copy.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=input_copy.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||
@@ -433,6 +453,7 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
CONF_TEMPERATURE: user_input.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
|
||||
CONF_MAX_TOKENS: user_input.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
|
||||
CONF_REQUEST_INTERVAL: user_input.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL),
|
||||
CONF_API_TIMEOUT: user_input.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT),
|
||||
CONF_CONTEXT_MESSAGES: user_input.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES),
|
||||
CONF_MAX_HISTORY_SIZE: user_input.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY),
|
||||
}
|
||||
@@ -504,6 +525,13 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_API_TIMEOUT,
|
||||
default=current_data.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=current_data.get(
|
||||
|
||||
@@ -61,6 +61,7 @@ CONF_TEMPERATURE: Final = "temperature"
|
||||
CONF_MAX_TOKENS: Final = "max_tokens"
|
||||
CONF_API_ENDPOINT: Final = "api_endpoint"
|
||||
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
||||
CONF_API_TIMEOUT: Final = "api_timeout"
|
||||
CONF_INSTANCE: Final = "instance"
|
||||
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
|
||||
CONF_IS_ANTHROPIC: Final = "is_anthropic"
|
||||
@@ -79,6 +80,7 @@ DEFAULT_TEMPERATURE: Final = 0.1
|
||||
DEFAULT_MAX_TOKENS: Final = 1000
|
||||
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
||||
DEFAULT_TIMEOUT: Final = 30
|
||||
DEFAULT_API_TIMEOUT: Final = 30
|
||||
DEFAULT_MAX_HISTORY: Final = 50
|
||||
DEFAULT_NAME: Final = "HA Text AI"
|
||||
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||
@@ -93,9 +95,11 @@ MIN_MAX_TOKENS: Final = 1
|
||||
MAX_MAX_TOKENS: Final = 100000
|
||||
MIN_REQUEST_INTERVAL: Final = 0.1
|
||||
MAX_REQUEST_INTERVAL: Final = 60.0
|
||||
MIN_API_TIMEOUT: Final = 5
|
||||
MAX_API_TIMEOUT: Final = 600
|
||||
|
||||
# API constants
|
||||
API_TIMEOUT: Final = 30
|
||||
API_TIMEOUT: Final = 30 # Legacy constant, use CONF_API_TIMEOUT from config
|
||||
API_RETRY_COUNT: Final = 3
|
||||
|
||||
# Service names
|
||||
@@ -232,6 +236,10 @@ CONFIG_SCHEMA = vol.Schema({
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL, max=MAX_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(CONF_API_TIMEOUT, default=DEFAULT_API_TIMEOUT): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||
),
|
||||
vol.Optional(CONF_MAX_HISTORY_SIZE, default=DEFAULT_MAX_HISTORY): vol.All( # Correct usage
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100),
|
||||
|
||||
@@ -37,6 +37,7 @@ from .const import (
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_TEMPERATURE,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
DEFAULT_API_TIMEOUT,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
ABSOLUTE_MAX_HISTORY_SIZE,
|
||||
MAX_ATTRIBUTE_SIZE,
|
||||
@@ -46,19 +47,6 @@ from .const import (
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
def _check_memory_available(self):
|
||||
"""Check if enough memory is available."""
|
||||
memory = psutil.virtual_memory()
|
||||
|
||||
# Log the total and available memory
|
||||
_LOGGER.debug("Total memory: %s, Available memory: %s", memory.total, memory.available)
|
||||
|
||||
if memory.available > 1024 * 1024 * 100: # 100MB
|
||||
_LOGGER.debug("Sufficient memory available: %s bytes", memory.available)
|
||||
return True
|
||||
else:
|
||||
_LOGGER.warning("Insufficient memory available: %s bytes", memory.available)
|
||||
return False
|
||||
|
||||
class AsyncFileHandler:
|
||||
"""Async context manager for file operations."""
|
||||
@@ -89,6 +77,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
max_history_size: int = DEFAULT_MAX_HISTORY,
|
||||
context_messages: int = DEFAULT_CONTEXT_MESSAGES,
|
||||
is_anthropic: bool = False,
|
||||
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||
) -> None:
|
||||
"""Initialize coordinator."""
|
||||
self.instance_name = instance_name
|
||||
@@ -128,6 +117,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
ABSOLUTE_MAX_HISTORY_SIZE
|
||||
)
|
||||
self.is_anthropic = is_anthropic
|
||||
self.api_timeout = api_timeout
|
||||
|
||||
# Initialize essential attributes
|
||||
self._is_processing = False
|
||||
@@ -549,25 +539,57 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
return 0
|
||||
|
||||
def _sync_write_history_entry(self, entry: dict) -> None:
|
||||
"""Synchronous method to write history entry."""
|
||||
"""Synchronous method to write history entry with enhanced error handling."""
|
||||
try:
|
||||
history = []
|
||||
if os.path.exists(self._history_file):
|
||||
with open(self._history_file, 'r') as f:
|
||||
content = f.read()
|
||||
if content:
|
||||
history = json.loads(content)
|
||||
try:
|
||||
with open(self._history_file, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
if content.strip():
|
||||
history = json.loads(content)
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||
_LOGGER.warning(f"Corrupted history file, creating new: {e}")
|
||||
# Backup corrupted file
|
||||
backup_path = f"{self._history_file}.corrupted.{dt_util.utcnow().strftime('%Y%m%d_%H%M%S')}"
|
||||
try:
|
||||
os.rename(self._history_file, backup_path)
|
||||
_LOGGER.info(f"Corrupted history backed up to: {backup_path}")
|
||||
except OSError:
|
||||
pass
|
||||
except PermissionError as e:
|
||||
_LOGGER.error(f"Permission denied reading history file: {e}")
|
||||
raise
|
||||
except OSError as e:
|
||||
_LOGGER.error(f"OS error reading history file: {e}")
|
||||
raise
|
||||
|
||||
history.append(entry)
|
||||
|
||||
if len(history) > self.max_history_size:
|
||||
history = history[-self.max_history_size:]
|
||||
|
||||
with open(self._history_file, 'w') as f:
|
||||
json.dump(history, f, indent=2)
|
||||
# Write with atomic operation
|
||||
temp_file = f"{self._history_file}.tmp"
|
||||
try:
|
||||
with open(temp_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(history, f, indent=2, ensure_ascii=False)
|
||||
os.replace(temp_file, self._history_file)
|
||||
except PermissionError as e:
|
||||
_LOGGER.error(f"Permission denied writing history file: {e}")
|
||||
raise
|
||||
except OSError as e:
|
||||
_LOGGER.error(f"OS error writing history file: {e}")
|
||||
# Clean up temp file if it exists
|
||||
try:
|
||||
os.remove(temp_file)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
_LOGGER.error(f"Synchronous history entry writing failed: {e}")
|
||||
raise
|
||||
|
||||
async def _rotate_history(self) -> None:
|
||||
"""Rotate conversation history with file management."""
|
||||
@@ -897,29 +919,44 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
async def async_process_message(self, question: str, **kwargs) -> dict:
|
||||
"""Process message using the AI client."""
|
||||
try:
|
||||
async with asyncio.timeout(60): # 60 second timeout
|
||||
async with asyncio.timeout(self.api_timeout):
|
||||
if self.is_anthropic:
|
||||
response = await self._process_anthropic_message(question, **kwargs)
|
||||
else:
|
||||
response = await self._process_openai_message(question, **kwargs)
|
||||
|
||||
# Add timestamp and model information to response
|
||||
timestamp = dt_util.utcnow().isoformat()
|
||||
model_used = kwargs.get("model", self.model)
|
||||
|
||||
# Enhance response with metadata
|
||||
enhanced_response = {
|
||||
"content": response["content"],
|
||||
"tokens": response.get("tokens", {}),
|
||||
"model": model_used,
|
||||
"timestamp": timestamp,
|
||||
"instance": self.instance_name,
|
||||
"question": question,
|
||||
"success": True
|
||||
}
|
||||
|
||||
self.last_response = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"timestamp": timestamp,
|
||||
"question": question,
|
||||
"response": response["content"],
|
||||
"model": kwargs.get("model", self.model),
|
||||
"model": model_used,
|
||||
"instance": self.instance_name,
|
||||
"normalized_name": self.normalized_name,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
return response
|
||||
return enhanced_response
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
raise HomeAssistantError("Request timed out")
|
||||
|
||||
except Exception as err:
|
||||
self._handle_error(err)
|
||||
await self._handle_error(err)
|
||||
raise
|
||||
|
||||
async def _process_anthropic_message(self, question: str, **kwargs) -> dict:
|
||||
@@ -1051,15 +1088,84 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
_LOGGER.error(f"Error clearing history: {e}")
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def async_get_history(self) -> List[Dict[str, str]]:
|
||||
"""Get conversation history."""
|
||||
return self._conversation_history
|
||||
async def async_get_history(
|
||||
self,
|
||||
limit: Optional[int] = None,
|
||||
filter_model: Optional[str] = None,
|
||||
start_date: Optional[str] = None,
|
||||
include_metadata: bool = False,
|
||||
sort_order: str = "newest"
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Get conversation history with optional filtering and sorting."""
|
||||
try:
|
||||
history = self._conversation_history.copy()
|
||||
|
||||
# Filter by model if specified
|
||||
if filter_model:
|
||||
history = [entry for entry in history if entry.get("model") == filter_model]
|
||||
|
||||
# Filter by start date if specified
|
||||
if start_date:
|
||||
try:
|
||||
from datetime import datetime
|
||||
start_dt = datetime.fromisoformat(start_date.replace('Z', '+00:00'))
|
||||
history = [
|
||||
entry for entry in history
|
||||
if datetime.fromisoformat(entry["timestamp"].replace('Z', '+00:00')) >= start_dt
|
||||
]
|
||||
except (ValueError, KeyError) as e:
|
||||
_LOGGER.warning(f"Invalid start_date format: {start_date}. Error: {e}")
|
||||
|
||||
# Sort history
|
||||
if sort_order == "oldest":
|
||||
history.sort(key=lambda x: x.get("timestamp", ""))
|
||||
else: # newest (default)
|
||||
history.sort(key=lambda x: x.get("timestamp", ""), reverse=True)
|
||||
|
||||
# Apply limit
|
||||
if limit and limit > 0:
|
||||
history = history[:limit]
|
||||
|
||||
# Add metadata if requested
|
||||
if include_metadata:
|
||||
for entry in history:
|
||||
entry["metadata"] = {
|
||||
"entry_size": len(str(entry)),
|
||||
"question_length": len(entry.get("question", "")),
|
||||
"response_length": len(entry.get("response", "")),
|
||||
"model_used": entry.get("model", self.model),
|
||||
"instance": self.instance_name
|
||||
}
|
||||
|
||||
return history
|
||||
|
||||
except Exception as e:
|
||||
_LOGGER.error(f"Error getting history: {e}")
|
||||
return []
|
||||
|
||||
async def async_set_system_prompt(self, prompt: str) -> None:
|
||||
"""Set system prompt."""
|
||||
self._system_prompt = prompt
|
||||
await self.async_update_ha_state()
|
||||
|
||||
def _check_memory_available(self) -> bool:
|
||||
"""Check if enough memory is available."""
|
||||
try:
|
||||
memory = psutil.virtual_memory()
|
||||
|
||||
# Log the total and available memory
|
||||
_LOGGER.debug("Total memory: %s, Available memory: %s", memory.total, memory.available)
|
||||
|
||||
if memory.available > 1024 * 1024 * 100: # 100MB
|
||||
_LOGGER.debug("Sufficient memory available: %s bytes", memory.available)
|
||||
return True
|
||||
else:
|
||||
_LOGGER.warning("Insufficient memory available: %s bytes", memory.available)
|
||||
return False
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error checking memory availability: %s", e)
|
||||
return True # Assume memory is available if check fails
|
||||
|
||||
async def async_shutdown(self) -> None:
|
||||
"""Shutdown coordinator."""
|
||||
_LOGGER.debug(f"Shutting down coordinator for {self.instance_name}")
|
||||
|
||||
@@ -24,6 +24,6 @@
|
||||
"single_config_entry": false,
|
||||
"ssdp": [],
|
||||
"usb": [],
|
||||
"version": "2.1.7",
|
||||
"version": "2.2.0",
|
||||
"zeroconf": []
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ ask_question:
|
||||
description: >-
|
||||
Send a question to the AI model and receive a detailed response.
|
||||
The response will be stored in the conversation history and can be retrieved later.
|
||||
This service now returns response data directly, eliminating the need to read from sensors.
|
||||
fields:
|
||||
instance:
|
||||
name: Instance
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
|
||||
"max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
|
||||
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
|
||||
"api_timeout": "API-Anfrage Timeout in Sekunden (5-600)",
|
||||
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||
}
|
||||
@@ -37,6 +38,7 @@
|
||||
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
||||
"api_provider": "API-Anbieter",
|
||||
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
|
||||
"api_timeout": "API-Anfrage Timeout in Sekunden (5-600)",
|
||||
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||
}
|
||||
@@ -79,6 +81,7 @@
|
||||
"temperature": "Kreativität der Antwort (0-2)",
|
||||
"max_tokens": "Maximale Länge der Antwort (1-100000)",
|
||||
"request_interval": "Minimale Anfrageintervall (0,1-60 Sekunden)",
|
||||
"api_timeout": "API-Anfrage Timeout in Sekunden (5-600)",
|
||||
"context_messages": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)",
|
||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||
}
|
||||
@@ -92,13 +95,13 @@
|
||||
"anthropic": "Anthropic (compatible)",
|
||||
"deepseek": "DeepSeek",
|
||||
"gemini": "Google Gemini"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Frage stellen (HA Text AI)",
|
||||
"description": "Stellen Sie eine Frage an das AI-Modell und erhalten Sie eine detaillierte Antwort. Die Antwort wird im Gesprächsverlauf gespeichert und kann später abgerufen werden.",
|
||||
"description": "Stellen Sie eine Frage an das AI-Modell und erhalten Sie eine detaillierte Antwort. Dieser Service gibt jetzt Antwortdaten direkt zurück, wodurch separate Textsensoren und die 255-Zeichen-Begrenzung überflüssig werden. Die Antwort wird auch im Gesprächsverlauf gespeichert.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instanz",
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"temperature": "Response creativity (0-2, lower = more focused)",
|
||||
"max_tokens": "Maximum response length (1-100000 tokens)",
|
||||
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
||||
"api_timeout": "API request timeout in seconds (5-600)",
|
||||
"context_messages": "Number of context messages to retain (1-20)",
|
||||
"max_history_size": "Maximum conversation history size (1-100)"
|
||||
}
|
||||
@@ -37,6 +38,7 @@
|
||||
"api_endpoint": "Custom API endpoint URL (optional)",
|
||||
"api_provider": "API Provider",
|
||||
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
||||
"api_timeout": "API request timeout in seconds (5-600)",
|
||||
"context_messages": "Number of context messages to retain (1-20)",
|
||||
"max_history_size": "Maximum conversation history size (1-100)"
|
||||
}
|
||||
@@ -79,6 +81,7 @@
|
||||
"temperature": "Response creativity (0-2)",
|
||||
"max_tokens": "Maximum response length (1-100000)",
|
||||
"request_interval": "Minimum request interval (0.1-60 seconds)",
|
||||
"api_timeout": "API request timeout in seconds (5-600)",
|
||||
"context_messages": "Number of previous messages to include in context (1-20)",
|
||||
"max_history_size": "Maximum conversation history size (1-100)"
|
||||
}
|
||||
@@ -92,13 +95,13 @@
|
||||
"anthropic": "Anthropic (compatible)",
|
||||
"deepseek": "DeepSeek",
|
||||
"gemini": "Google Gemini"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Ask Question (HA Text AI)",
|
||||
"description": "Send a question to the AI model and receive a detailed response. The response will be stored in the conversation history and can be retrieved later.",
|
||||
"description": "Send a question to the AI model and receive a detailed response. This service now returns response data directly, eliminating the need for separate text sensors and the 255-character limitation. The response will also be stored in the conversation history.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instance",
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
|
||||
"max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
|
||||
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
||||
"api_timeout": "Tiempo de espera de solicitud API en segundos (5-600)",
|
||||
"context_messages": "Número de mensajes de contexto a retener (1-20)",
|
||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||
}
|
||||
@@ -37,6 +38,7 @@
|
||||
"api_endpoint": "URL del endpoint de API personalizado (opcional)",
|
||||
"api_provider": "Proveedor de API",
|
||||
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
||||
"api_timeout": "Tiempo de espera de solicitud API en segundos (5-600)",
|
||||
"context_messages": "Número de mensajes de contexto a retener (1-20)",
|
||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||
}
|
||||
@@ -79,6 +81,7 @@
|
||||
"temperature": "Creatividad de la respuesta (0-2)",
|
||||
"max_tokens": "Longitud máxima de la respuesta (1-100000)",
|
||||
"request_interval": "Intervalo mínimo de solicitud (0.1-60 segundos)",
|
||||
"api_timeout": "Tiempo de espera de solicitud API en segundos (5-600)",
|
||||
"context_messages": "Número de mensajes anteriores a incluir en el contexto (1-20)",
|
||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||
}
|
||||
@@ -92,13 +95,13 @@
|
||||
"anthropic": "Anthropic (compatible)",
|
||||
"deepseek": "DeepSeek",
|
||||
"gemini": "Google Gemini"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"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. Este servicio ahora devuelve datos de respuesta directamente, eliminando la necesidad de sensores de texto separados y la limitación de 255 caracteres. La respuesta también se almacenará en el historial de conversación.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instancia",
|
||||
|
||||
@@ -1,15 +1,6 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "एआई प्रदाता चुनें",
|
||||
"description": "इस उदाहरण के लिए किस एआई सेवा प्रदाता का उपयोग करना है, चुनें।",
|
||||
"data": {
|
||||
"api_provider": "एपीआई प्रदाता",
|
||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||
}
|
||||
},
|
||||
"provider": {
|
||||
"title": "प्रदाता सेटिंग्स",
|
||||
"description": "आपके द्वारा चुने गए एआई प्रदाता के लिए कनेक्शन विवरण प्रदान करें।",
|
||||
@@ -21,6 +12,7 @@
|
||||
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
||||
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
||||
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||
}
|
||||
@@ -37,6 +29,7 @@
|
||||
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
||||
"api_provider": "एपीआई प्रदाता",
|
||||
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||
}
|
||||
@@ -79,6 +72,7 @@
|
||||
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
|
||||
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
|
||||
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
|
||||
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
|
||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||
}
|
||||
@@ -98,7 +92,7 @@
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "प्रश्न पूछें (HA Text AI)",
|
||||
"description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
|
||||
"description": "AI मॉडल को प्रश्न भेजें और विस्तृत उत्तर प्राप्त करें। यह सेवा अब प्रत्यक्ष रूप से प्रतिक्रिया डेटा वापस करती है, अलग टेक्स्ट सेंसर की आवश्यकता और 255 वर्ण की सीमा को समाप्त करती है। प्रतिक्रिया को बातचीत के इतिहास में भी संग्रहीत किया जाएगा।",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "उदाहरण",
|
||||
@@ -295,4 +289,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
||||
"max_tokens": "Lunghezza massima della risposta (1-100000 token)",
|
||||
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
||||
"api_timeout": "Timeout della richiesta API in secondi (5-600)",
|
||||
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||
}
|
||||
@@ -37,6 +38,7 @@
|
||||
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
|
||||
"api_provider": "Fornitore API",
|
||||
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
||||
"api_timeout": "Timeout della richiesta API in secondi (5-600)",
|
||||
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||
}
|
||||
@@ -79,6 +81,7 @@
|
||||
"temperature": "Creatività della risposta (0-2)",
|
||||
"max_tokens": "Lunghezza massima della risposta (1-100000)",
|
||||
"request_interval": "Intervallo minimo di richiesta (0.1-60 secondi)",
|
||||
"api_timeout": "Timeout della richiesta API in secondi (5-600)",
|
||||
"context_messages": "Numero di messaggi precedenti da includere nel contesto (1-20)",
|
||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||
}
|
||||
@@ -98,7 +101,7 @@
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Fai una domanda (HA Text AI)",
|
||||
"description": "Invia una domanda al modello AI e ricevi una risposta dettagliata. La risposta sarà memorizzata nella cronologia delle conversazioni e potrà essere recuperata in seguito.",
|
||||
"description": "Invia una domanda al modello AI e ricevi una risposta dettagliata. Questo servizio ora restituisce i dati di risposta direttamente, eliminando la necessità di sensori di testo separati e la limitazione di 255 caratteri. La risposta sarà anche memorizzata nella cronologia delle conversazioni.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanze",
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
||||
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||
}
|
||||
@@ -37,6 +38,7 @@
|
||||
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
||||
"api_provider": "Провайдер API",
|
||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||
}
|
||||
@@ -79,6 +81,7 @@
|
||||
"temperature": "Креативность ответа (0-2)",
|
||||
"max_tokens": "Максимальная длина ответа (1-100000)",
|
||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
|
||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||
}
|
||||
@@ -98,7 +101,7 @@
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Задать вопрос (HA Text AI)",
|
||||
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.",
|
||||
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Сервис теперь возвращает данные ответа напрямую, устраняя необходимость в отдельных текстовых сенсорах и ограничение в 255 символов. Ответ также будет сохранен в истории разговора.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Экземпляр",
|
||||
|
||||
@@ -1,15 +1,6 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Изаберите AI провајдера",
|
||||
"description": "Изаберите који AI сервис провајдер да користите за ову инстанцу.",
|
||||
"data": {
|
||||
"api_provider": "API провајдер",
|
||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||
}
|
||||
},
|
||||
"provider": {
|
||||
"title": "Подешавања провајдера",
|
||||
"description": "Обезбедите детаље о вези за изабраног AI провајдера.",
|
||||
@@ -21,6 +12,7 @@
|
||||
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
||||
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||
}
|
||||
@@ -37,6 +29,7 @@
|
||||
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
||||
"api_provider": "API провајдер",
|
||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||
}
|
||||
@@ -79,6 +72,7 @@
|
||||
"temperature": "Креативност одговора (0-2)",
|
||||
"max_tokens": "Максимална дужина одговора (1-100000)",
|
||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
|
||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||
}
|
||||
@@ -98,7 +92,7 @@
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Поставите питање (HA Text AI)",
|
||||
"description": "Пошаљите питање AI моделу и примите детаљан одговор. Одговор ће бити сачуван у историји разговора и може се касније повратити.",
|
||||
"description": "Пошаљите питање AI моделу и добијте детаљан одговор. Овај сервис сада враћа податке одговора директно, елиминишући потребу за засебним текстуалним сензорима и ограничење од 255 карактера. Одговор ће такође бити сачуван у историји разговора.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанца",
|
||||
@@ -295,4 +289,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,6 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "选择AI提供者",
|
||||
"description": "选择要用于此实例的AI服务提供者。",
|
||||
"data": {
|
||||
"api_provider": "API提供者",
|
||||
"context_messages": "保留的上下文消息数量(1-20)",
|
||||
"max_history_size": "最大对话历史大小(1-100)"
|
||||
}
|
||||
},
|
||||
"provider": {
|
||||
"title": "提供者设置",
|
||||
"description": "提供所选AI提供者的连接详细信息。",
|
||||
@@ -21,6 +12,7 @@
|
||||
"temperature": "响应创造力(0-2,越低越专注)",
|
||||
"max_tokens": "最大响应长度(1-100000个标记)",
|
||||
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||
"api_timeout": "API请求超时时间(5-600秒)",
|
||||
"context_messages": "保留的上下文消息数量(1-20)",
|
||||
"max_history_size": "最大对话历史大小(1-100)"
|
||||
}
|
||||
@@ -37,6 +29,7 @@
|
||||
"api_endpoint": "自定义API端点URL(可选)",
|
||||
"api_provider": "API提供者",
|
||||
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||
"api_timeout": "API请求超时时间(5-600秒)",
|
||||
"context_messages": "保留的上下文消息数量(1-20)",
|
||||
"max_history_size": "最大对话历史大小(1-100)"
|
||||
}
|
||||
@@ -79,6 +72,7 @@
|
||||
"temperature": "响应创造力(0-2)",
|
||||
"max_tokens": "最大响应长度(1-100000)",
|
||||
"request_interval": "最小请求间隔(0.1-60秒)",
|
||||
"api_timeout": "API请求超时时间(5-600秒)",
|
||||
"context_messages": "要包含在上下文中的先前消息数量(1-20)",
|
||||
"max_history_size": "最大对话历史大小(1-100)"
|
||||
}
|
||||
@@ -98,7 +92,7 @@
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "提问 (HA Text AI)",
|
||||
"description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。",
|
||||
"description": "向AI模型发送问题并获得详细回答。此服务现在直接返回响应数据,消除了对单独文本传感器的需要和255字符限制。响应也将存储在对话历史中。",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "实例",
|
||||
@@ -295,4 +289,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user