mirror of
https://github.com/smkrv/ha-text-ai.git
synced 2026-07-22 07:03:58 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43cbac2d04 | ||
|
|
986c78dd90 | ||
|
|
0859c35aec | ||
|
|
922fefbd43 | ||
|
|
a5ac100b06 | ||
|
|
ef579af7c1 | ||
|
|
3097106e93 | ||
|
|
35073960b8 | ||
|
|
8d0e0b5e44 | ||
|
|
e91c3701c5 | ||
|
|
7f62101b3e | ||
|
|
3729c3736f | ||
|
|
f5ce5e459a | ||
|
|
4064486b1e | ||
|
|
185778dbd0 | ||
|
|
83a255dee0 | ||
|
|
6b66dd6a4d | ||
|
|
bd82f23120 |
@@ -1,5 +1,6 @@
|
|||||||
name: Validate with hassfest
|
name: Validate with hassfest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build and upload release asset
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event.release.tag_name }}
|
||||||
|
|
||||||
|
- name: Create zip archive
|
||||||
|
run: |
|
||||||
|
cd custom_components
|
||||||
|
zip -r ../ha_text_ai.zip ha_text_ai \
|
||||||
|
-x "ha_text_ai/__pycache__/*" \
|
||||||
|
-x "*.pyc" \
|
||||||
|
-x "*.pyo" \
|
||||||
|
-x "*/__pycache__/*" \
|
||||||
|
-x "*.DS_Store"
|
||||||
|
|
||||||
|
- name: Upload release asset
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.event.release.tag_name }}
|
||||||
|
files: ha_text_ai.zip
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
name: Validate
|
name: Validate
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)
|
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)
|
||||||
       
|
       
|
||||||
|
|
||||||
|
|
||||||
<img src="https://github.com/smkrv/ha-text-ai/blob/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
|
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
||||||
</div>
|
</div>
|
||||||
@@ -106,7 +106,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
|
|
||||||
## 📋 Prerequisites
|
## 📋 Prerequisites
|
||||||
|
|
||||||
- Home Assistant 2024.2.2 or later
|
- Home Assistant 2024.12.0 or later (recommended for best compatibility)
|
||||||
- Active API key from:
|
- Active API key from:
|
||||||
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
||||||
- Anthropic ([Get key](https://console.anthropic.com/))
|
- Anthropic ([Get key](https://console.anthropic.com/))
|
||||||
@@ -120,7 +120,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
## Configuration Options
|
## Configuration Options
|
||||||
|
|
||||||
### 🔧 **Core Configuration Settings**
|
### 🔧 **Core Configuration Settings**
|
||||||
- 🌐 **API Provider**: OpenAI/Anthropic/DeepSeek
|
- 🌐 **API Provider**: OpenAI/Anthropic/DeepSeek/Gemini
|
||||||
- 🔑 **API Key**: Provider-specific authentication
|
- 🔑 **API Key**: Provider-specific authentication
|
||||||
- 🤖 **Model Selection**: Flexible, provider-specific models
|
- 🤖 **Model Selection**: Flexible, provider-specific models
|
||||||
- 🌡️ **Temperature**: Creativity control (0.0-2.0)
|
- 🌡️ **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
|
- 💾 **History Size**: Number of messages to retain
|
||||||
- 🌍 **Custom API Endpoint**: Optional advanced configuration
|
- 🌍 **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>
|
<details>
|
||||||
<summary>🌐 Potentially Compatible Providers</summary>
|
<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>
|
<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
|
1. Open HACS in Home Assistant
|
||||||
2. Click on "Integrations"
|
2. Click on "Integrations"
|
||||||
3. Click "..." in top right corner
|
3. Search for "HA Text AI"
|
||||||
4. Select "Custom repositories"
|
4. Click "Download"
|
||||||
5. Add repository URL: `https://github.com/smkrv/ha-text-ai`
|
5. Restart Home Assistant
|
||||||
6. Choose "Integration" as category
|
|
||||||
7. Click "Download"
|
**Alternative Method (Custom Repository):**
|
||||||
8. Restart Home Assistant
|
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
|
### Manual Installation
|
||||||
1. Download the latest release
|
1. Download the latest release
|
||||||
@@ -196,7 +220,7 @@ To be compatible, a provider should support:
|
|||||||
ha_text_ai:
|
ha_text_ai:
|
||||||
api_provider: openai # Required
|
api_provider: openai # Required
|
||||||
api_key: !secret ai_api_key # Required
|
api_key: !secret ai_api_key # Required
|
||||||
model: gpt-4o-mini # Strongly recommended
|
model: gpt-4o # Strongly recommended
|
||||||
temperature: 0.7 # Optional
|
temperature: 0.7 # Optional
|
||||||
max_tokens: 1000 # Optional
|
max_tokens: 1000 # Optional
|
||||||
request_interval: 1.0 # Optional
|
request_interval: 1.0 # Optional
|
||||||
@@ -213,7 +237,7 @@ sensor:
|
|||||||
- platform: ha_text_ai
|
- platform: ha_text_ai
|
||||||
name: "My AI Assistant" # Required, unique identifier
|
name: "My AI Assistant" # Required, unique identifier
|
||||||
api_provider: openai # Optional (inherits from platform)
|
api_provider: openai # Optional (inherits from platform)
|
||||||
model: "gpt-4o-mini" # Optional
|
model: "gpt-4o" # Optional
|
||||||
temperature: 0.7 # Optional
|
temperature: 0.7 # Optional
|
||||||
max_tokens: 1000 # Optional
|
max_tokens: 1000 # Optional
|
||||||
```
|
```
|
||||||
@@ -224,16 +248,16 @@ sensor:
|
|||||||
|
|
||||||
| Parameter | Type | Required | Default | Description |
|
| 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 |
|
| `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 |
|
| `model` | String | ⚠️ | gpt-4o-mini | Strongly recommended: Specific AI model to use. Default varies by provider |
|
||||||
| `temperature` | Float | ❌ | 0.7 | Response creativity level (0.0-2.0) |
|
| `temperature` | Float | ❌ | 0.1 | Response creativity level (0.0-2.0) |
|
||||||
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
|
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
|
||||||
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
|
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
|
||||||
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
|
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
|
||||||
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
|
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
|
||||||
| `max_history_size` | Integer | ❌ | 100 | Maximum number of conversation entries to store |
|
| `max_history_size` | Integer | ❌ | 50 | Maximum number of conversation entries to store |
|
||||||
| `history_file_size` | Integer | ⚠️ | 1 | Maximum history file size in MB |
|
| `context_messages` | Integer | ❌ | 5 | Number of previous messages to include in context (1-20) |
|
||||||
|
|
||||||
#### Sensor Configuration
|
#### Sensor Configuration
|
||||||
|
|
||||||
@@ -242,9 +266,9 @@ sensor:
|
|||||||
| `platform` | String | ✅ | - | Must be `ha_text_ai` |
|
| `platform` | String | ✅ | - | Must be `ha_text_ai` |
|
||||||
| `name` | String | ✅ | - | Unique sensor identifier |
|
| `name` | String | ✅ | - | Unique sensor identifier |
|
||||||
| `api_provider` | String | ❌ | Platform setting | Override global provider |
|
| `api_provider` | String | ❌ | Platform setting | Override global provider |
|
||||||
| `model` | String | ⚠️ | Platform setting | Recommended: Override global model. If not specified, uses platform or provider default |
|
| `model` | String | ⚠️ | Provider default | Recommended: Override global model (gpt-4o-mini, deepseek-chat, gemini-2.0-flash) |
|
||||||
| `temperature` | Float | ❌ | Platform setting | Override global temperature |
|
| `temperature` | Float | ❌ | 0.1 | Override global temperature |
|
||||||
| `max_tokens` | Integer | ❌ | Platform setting | Override global max tokens |
|
| `max_tokens` | Integer | ❌ | 1000 | Override global max tokens |
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
@@ -265,7 +289,7 @@ sensor:
|
|||||||
service: ha_text_ai.ask_question
|
service: ha_text_ai.ask_question
|
||||||
data:
|
data:
|
||||||
question: "What's the optimal temperature for sleeping?"
|
question: "What's the optimal temperature for sleeping?"
|
||||||
model: "claude-3-sonnet" # optional
|
model: "claude-3.5-sonnet" # optional
|
||||||
temperature: 0.5 # optional
|
temperature: 0.5 # optional
|
||||||
max_tokens: 500 # optional
|
max_tokens: 500 # optional
|
||||||
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
||||||
@@ -281,10 +305,10 @@ response_text: "The optimal sleeping temperature is 65-68°F (18-20°C)..."
|
|||||||
tokens_used: 150
|
tokens_used: 150
|
||||||
prompt_tokens: 50
|
prompt_tokens: 50
|
||||||
completion_tokens: 100
|
completion_tokens: 100
|
||||||
model_used: "claude-3-sonnet"
|
model_used: "claude-3.5-sonnet"
|
||||||
instance: "sensor.ha_text_ai_gpt"
|
instance: "sensor.ha_text_ai_gpt"
|
||||||
question: "What's the optimal temperature for sleeping?"
|
question: "What's the optimal temperature for sleeping?"
|
||||||
timestamp: "2025-01-09T16:57:00.000Z"
|
timestamp: "2025-02-09T16:57:00.000Z"
|
||||||
success: true
|
success: true
|
||||||
# error: "Error message" (only present if success: false)
|
# error: "Error message" (only present if success: false)
|
||||||
```
|
```
|
||||||
@@ -313,8 +337,11 @@ data:
|
|||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.get_history
|
service: ha_text_ai.get_history
|
||||||
data:
|
data:
|
||||||
limit: 5 # optional
|
limit: 5 # optional, number of conversations to return (1-100)
|
||||||
filter_model: "gpt-4o" # optional
|
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
|
instance: sensor.ha_text_ai_gpt
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -626,10 +653,10 @@ Conversation history stored in `.storage/ha_text_ai_history/` directory:
|
|||||||
## 📘 FAQ
|
## 📘 FAQ
|
||||||
|
|
||||||
**Q: Which AI providers are supported?**
|
**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?**
|
**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?**
|
**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.
|
A: Depends on your API provider's plan. We recommend monitoring usage and implementing request throttling via `request_interval` configuration.
|
||||||
@@ -640,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?**
|
**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.
|
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?**
|
**Q: What are the token limits for different models?**
|
||||||
A: Use GPT-3.5-Turbo for most queries, implement caching, and optimize token usage.
|
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?**
|
**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.
|
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.
|
||||||
@@ -707,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"><img src="https://github.com/smkrv/ha-text-ai/blob/2aaf3405759eb2d97624834594e24ace896131df/assets/images/icons/footer_icon.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div>
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
Made with ❤️ for the Home Assistant Community,
|
Made with ❤️ for the Home Assistant Community
|
||||||
utilizing Claude 3.5 Sonnet, Gemini Pro 1.5, and Qwen 2.5 Coder 32B Instruct.
|
|
||||||
|
|
||||||
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ from .const import (
|
|||||||
CONF_MAX_TOKENS,
|
CONF_MAX_TOKENS,
|
||||||
CONF_API_ENDPOINT,
|
CONF_API_ENDPOINT,
|
||||||
CONF_REQUEST_INTERVAL,
|
CONF_REQUEST_INTERVAL,
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
CONF_API_PROVIDER,
|
CONF_API_PROVIDER,
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
API_PROVIDER_OPENAI,
|
API_PROVIDER_OPENAI,
|
||||||
@@ -51,8 +52,8 @@ from .const import (
|
|||||||
DEFAULT_DEEPSEEK_ENDPOINT,
|
DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
DEFAULT_GEMINI_ENDPOINT,
|
DEFAULT_GEMINI_ENDPOINT,
|
||||||
DEFAULT_REQUEST_INTERVAL,
|
DEFAULT_REQUEST_INTERVAL,
|
||||||
|
DEFAULT_API_TIMEOUT,
|
||||||
DEFAULT_CONTEXT_MESSAGES,
|
DEFAULT_CONTEXT_MESSAGES,
|
||||||
API_TIMEOUT,
|
|
||||||
SERVICE_ASK_QUESTION,
|
SERVICE_ASK_QUESTION,
|
||||||
SERVICE_CLEAR_HISTORY,
|
SERVICE_CLEAR_HISTORY,
|
||||||
SERVICE_GET_HISTORY,
|
SERVICE_GET_HISTORY,
|
||||||
@@ -75,6 +76,8 @@ SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
|||||||
vol.Optional("temperature"): cv.positive_float,
|
vol.Optional("temperature"): cv.positive_float,
|
||||||
vol.Optional("max_tokens"): cv.positive_int,
|
vol.Optional("max_tokens"): cv.positive_int,
|
||||||
vol.Optional("context_messages"): cv.positive_int,
|
vol.Optional("context_messages"): cv.positive_int,
|
||||||
|
vol.Optional("structured_output", default=False): cv.boolean,
|
||||||
|
vol.Optional("json_schema"): cv.string,
|
||||||
})
|
})
|
||||||
|
|
||||||
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||||
@@ -86,6 +89,9 @@ SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
|
|||||||
vol.Required("instance"): cv.string,
|
vol.Required("instance"): cv.string,
|
||||||
vol.Optional("limit"): cv.positive_int,
|
vol.Optional("limit"): cv.positive_int,
|
||||||
vol.Optional("filter_model"): cv.string,
|
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:
|
def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAICoordinator:
|
||||||
@@ -123,6 +129,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||||||
max_tokens=call.data.get("max_tokens"),
|
max_tokens=call.data.get("max_tokens"),
|
||||||
system_prompt=call.data.get("system_prompt"),
|
system_prompt=call.data.get("system_prompt"),
|
||||||
context_messages=call.data.get("context_messages"),
|
context_messages=call.data.get("context_messages"),
|
||||||
|
structured_output=call.data.get("structured_output", False),
|
||||||
|
json_schema=call.data.get("json_schema"),
|
||||||
)
|
)
|
||||||
|
|
||||||
# Return structured response data
|
# Return structured response data
|
||||||
@@ -168,7 +176,10 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||||
return await coordinator.async_get_history(
|
return await coordinator.async_get_history(
|
||||||
limit=call.data.get("limit"),
|
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:
|
except Exception as err:
|
||||||
_LOGGER.error("Error getting history: %s", str(err))
|
_LOGGER.error("Error getting history: %s", str(err))
|
||||||
@@ -262,7 +273,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||||||
|
|
||||||
return True
|
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."""
|
"""Check API availability for different providers."""
|
||||||
try:
|
try:
|
||||||
if provider == API_PROVIDER_GEMINI:
|
if provider == API_PROVIDER_GEMINI:
|
||||||
@@ -279,7 +290,7 @@ async def async_check_api(session, endpoint: str, headers: dict, provider: str)
|
|||||||
else: # OpenAI
|
else: # OpenAI
|
||||||
check_url = f"{endpoint}/models"
|
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:
|
async with session.get(check_url, headers=headers) as response:
|
||||||
if response.status in [200, 404]:
|
if response.status in [200, 404]:
|
||||||
return True
|
return True
|
||||||
@@ -301,26 +312,42 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
_LOGGER.debug(f"Setting up HA Text AI entry: {entry.data}")
|
_LOGGER.debug(f"Setting up HA Text AI entry: {entry.data}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if CONF_API_PROVIDER not in entry.data:
|
# Get provider from data or options (options takes precedence)
|
||||||
|
config = {**entry.data, **entry.options}
|
||||||
|
api_provider = config.get(CONF_API_PROVIDER)
|
||||||
|
|
||||||
|
if not api_provider:
|
||||||
_LOGGER.error("API provider not specified")
|
_LOGGER.error("API provider not specified")
|
||||||
raise ConfigEntryNotReady("API provider is required")
|
raise ConfigEntryNotReady("API provider is required")
|
||||||
|
|
||||||
# Get configuration
|
|
||||||
session = aiohttp_client.async_get_clientsession(hass)
|
session = aiohttp_client.async_get_clientsession(hass)
|
||||||
api_provider = entry.data.get(CONF_API_PROVIDER)
|
|
||||||
model = entry.data.get(CONF_MODEL, DEFAULT_MODEL)
|
# Get default endpoint based on provider
|
||||||
endpoint = entry.data.get(
|
default_endpoint = {
|
||||||
CONF_API_ENDPOINT,
|
API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
|
||||||
DEFAULT_OPENAI_ENDPOINT if api_provider == API_PROVIDER_OPENAI
|
API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
else DEFAULT_ANTHROPIC_ENDPOINT
|
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
).rstrip('/')
|
API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
|
||||||
api_key = entry.data[CONF_API_KEY]
|
}.get(api_provider, DEFAULT_OPENAI_ENDPOINT)
|
||||||
|
|
||||||
|
# Get default model based on provider
|
||||||
|
default_model = (
|
||||||
|
DEFAULT_DEEPSEEK_MODEL if api_provider == API_PROVIDER_DEEPSEEK else
|
||||||
|
DEFAULT_GEMINI_MODEL if api_provider == API_PROVIDER_GEMINI else
|
||||||
|
DEFAULT_MODEL
|
||||||
|
)
|
||||||
|
|
||||||
|
model = config.get(CONF_MODEL, default_model)
|
||||||
|
endpoint = config.get(CONF_API_ENDPOINT, default_endpoint).rstrip('/')
|
||||||
|
# API key can now be updated via options
|
||||||
|
api_key = config.get(CONF_API_KEY, entry.data.get(CONF_API_KEY))
|
||||||
instance_name = entry.data.get(CONF_NAME, entry.entry_id)
|
instance_name = entry.data.get(CONF_NAME, entry.entry_id)
|
||||||
request_interval = entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
request_interval = config.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||||
max_tokens = entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
api_timeout = config.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
|
||||||
temperature = entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
max_tokens = config.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||||
max_history_size = entry.data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
temperature = config.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||||
context_messages = entry.data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
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
|
is_anthropic = api_provider == API_PROVIDER_ANTHROPIC
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
@@ -334,7 +361,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
else:
|
else:
|
||||||
headers["Authorization"] = f"Bearer {api_key}"
|
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")
|
raise ConfigEntryNotReady("API connection failed")
|
||||||
|
|
||||||
_LOGGER.debug("Creating API client for %s with endpoint %s", api_provider, endpoint)
|
_LOGGER.debug("Creating API client for %s with endpoint %s", api_provider, endpoint)
|
||||||
@@ -345,6 +372,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
headers=headers,
|
headers=headers,
|
||||||
api_provider=api_provider,
|
api_provider=api_provider,
|
||||||
model=model,
|
model=model,
|
||||||
|
api_timeout=api_timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
coordinator = HATextAICoordinator(
|
coordinator = HATextAICoordinator(
|
||||||
@@ -358,6 +386,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
max_history_size=max_history_size,
|
max_history_size=max_history_size,
|
||||||
context_messages=context_messages,
|
context_messages=context_messages,
|
||||||
is_anthropic=is_anthropic,
|
is_anthropic=is_anthropic,
|
||||||
|
api_timeout=api_timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER.debug(f"Created coordinator for {instance_name}")
|
_LOGGER.debug(f"Created coordinator for {instance_name}")
|
||||||
@@ -371,6 +400,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
# Set up platforms
|
# Set up platforms
|
||||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||||
|
|
||||||
|
# Register update listener for options changes
|
||||||
|
entry.async_on_unload(entry.add_update_listener(async_update_options))
|
||||||
|
|
||||||
_LOGGER.debug(f"Setup completed for {instance_name}")
|
_LOGGER.debug(f"Setup completed for {instance_name}")
|
||||||
|
|
||||||
return True
|
return True
|
||||||
@@ -379,6 +411,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
_LOGGER.exception(f"Error setting up HA Text AI: {err}")
|
_LOGGER.exception(f"Error setting up HA Text AI: {err}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||||
|
"""Handle options update - reload the config entry."""
|
||||||
|
_LOGGER.info("Options updated for %s, reloading integration", entry.title)
|
||||||
|
await hass.config_entries.async_reload(entry.entry_id)
|
||||||
|
|
||||||
|
|
||||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||||
"""Unload a config entry."""
|
"""Unload a config entry."""
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from datetime import datetime, timedelta
|
|||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.exceptions import HomeAssistantError
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
from .const import (
|
from .const import (
|
||||||
API_TIMEOUT,
|
DEFAULT_API_TIMEOUT,
|
||||||
API_RETRY_COUNT,
|
API_RETRY_COUNT,
|
||||||
API_PROVIDER_ANTHROPIC,
|
API_PROVIDER_ANTHROPIC,
|
||||||
API_PROVIDER_DEEPSEEK,
|
API_PROVIDER_DEEPSEEK,
|
||||||
@@ -41,6 +41,7 @@ class APIClient:
|
|||||||
headers: Dict[str, str],
|
headers: Dict[str, str],
|
||||||
api_provider: str,
|
api_provider: str,
|
||||||
model: str,
|
model: str,
|
||||||
|
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize API client."""
|
"""Initialize API client."""
|
||||||
self.session = session
|
self.session = session
|
||||||
@@ -48,7 +49,8 @@ class APIClient:
|
|||||||
self.headers = headers
|
self.headers = headers
|
||||||
self.api_provider = api_provider
|
self.api_provider = api_provider
|
||||||
self.model = model
|
self.model = model
|
||||||
self.timeout = ClientTimeout(total=API_TIMEOUT)
|
self.api_timeout = api_timeout
|
||||||
|
self.timeout = ClientTimeout(total=api_timeout)
|
||||||
self._closed = False
|
self._closed = False
|
||||||
|
|
||||||
async def __aenter__(self):
|
async def __aenter__(self):
|
||||||
@@ -93,7 +95,7 @@ class APIClient:
|
|||||||
|
|
||||||
for attempt in range(API_RETRY_COUNT):
|
for attempt in range(API_RETRY_COUNT):
|
||||||
try:
|
try:
|
||||||
async with timeout(API_TIMEOUT):
|
async with timeout(self.api_timeout):
|
||||||
async with self.session.post(
|
async with self.session.post(
|
||||||
url,
|
url,
|
||||||
json=payload,
|
json=payload,
|
||||||
@@ -125,6 +127,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using appropriate API."""
|
"""Create completion using appropriate API."""
|
||||||
try:
|
try:
|
||||||
@@ -132,19 +136,23 @@ class APIClient:
|
|||||||
|
|
||||||
if self.api_provider == API_PROVIDER_ANTHROPIC:
|
if self.api_provider == API_PROVIDER_ANTHROPIC:
|
||||||
return await self._create_anthropic_completion(
|
return await self._create_anthropic_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
elif self.api_provider == API_PROVIDER_DEEPSEEK:
|
elif self.api_provider == API_PROVIDER_DEEPSEEK:
|
||||||
return await self._create_deepseek_completion(
|
return await self._create_deepseek_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
elif self.api_provider == API_PROVIDER_GEMINI:
|
elif self.api_provider == API_PROVIDER_GEMINI:
|
||||||
return await self._create_gemini_completion(
|
return await self._create_gemini_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
return await self._create_openai_completion(
|
return await self._create_openai_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_LOGGER.error("API request failed: %s", str(e))
|
_LOGGER.error("API request failed: %s", str(e))
|
||||||
@@ -156,6 +164,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using DeepSeek API."""
|
"""Create completion using DeepSeek API."""
|
||||||
url = f"{self.endpoint}/chat/completions"
|
url = f"{self.endpoint}/chat/completions"
|
||||||
@@ -167,6 +177,24 @@ class APIClient:
|
|||||||
"stream": False
|
"stream": False
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Add structured output format if enabled (DeepSeek is OpenAI-compatible)
|
||||||
|
if structured_output and json_schema:
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
schema = json.loads(json_schema)
|
||||||
|
payload["response_format"] = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "structured_response",
|
||||||
|
"strict": True,
|
||||||
|
"schema": schema
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_LOGGER.debug("DeepSeek structured output enabled with schema")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Falling back to json_object mode.")
|
||||||
|
payload["response_format"] = {"type": "json_object"}
|
||||||
|
|
||||||
data = await self._make_request(url, payload)
|
data = await self._make_request(url, payload)
|
||||||
return {
|
return {
|
||||||
"choices": [
|
"choices": [
|
||||||
@@ -187,6 +215,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using OpenAI API."""
|
"""Create completion using OpenAI API."""
|
||||||
url = f"{self.endpoint}/chat/completions"
|
url = f"{self.endpoint}/chat/completions"
|
||||||
@@ -197,6 +227,24 @@ class APIClient:
|
|||||||
"max_tokens": max_tokens,
|
"max_tokens": max_tokens,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Add structured output format if enabled
|
||||||
|
if structured_output and json_schema:
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
schema = json.loads(json_schema)
|
||||||
|
payload["response_format"] = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "structured_response",
|
||||||
|
"strict": True,
|
||||||
|
"schema": schema
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_LOGGER.debug("OpenAI structured output enabled with schema")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Falling back to json_object mode.")
|
||||||
|
payload["response_format"] = {"type": "json_object"}
|
||||||
|
|
||||||
data = await self._make_request(url, payload)
|
data = await self._make_request(url, payload)
|
||||||
return {
|
return {
|
||||||
"choices": [
|
"choices": [
|
||||||
@@ -217,6 +265,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using Anthropic API."""
|
"""Create completion using Anthropic API."""
|
||||||
url = f"{self.endpoint}/v1/messages"
|
url = f"{self.endpoint}/v1/messages"
|
||||||
@@ -232,6 +282,20 @@ class APIClient:
|
|||||||
else:
|
else:
|
||||||
filtered_messages.append(msg)
|
filtered_messages.append(msg)
|
||||||
|
|
||||||
|
# For Anthropic, add structured output instruction to system prompt
|
||||||
|
if structured_output and json_schema:
|
||||||
|
schema_instruction = (
|
||||||
|
f"\n\nIMPORTANT: You MUST respond ONLY with valid JSON that matches "
|
||||||
|
f"this JSON Schema:\n{json_schema}\n"
|
||||||
|
f"Do not include any text before or after the JSON. "
|
||||||
|
f"Do not wrap the JSON in markdown code blocks."
|
||||||
|
)
|
||||||
|
if system_prompt:
|
||||||
|
system_prompt += schema_instruction
|
||||||
|
else:
|
||||||
|
system_prompt = schema_instruction.strip()
|
||||||
|
_LOGGER.debug("Anthropic structured output enabled via system prompt")
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"model": model,
|
"model": model,
|
||||||
"messages": filtered_messages,
|
"messages": filtered_messages,
|
||||||
@@ -271,6 +335,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using Gemini API with google-genai library.
|
"""Create completion using Gemini API with google-genai library.
|
||||||
|
|
||||||
@@ -279,6 +345,8 @@ class APIClient:
|
|||||||
messages: List of message dictionaries with role and content
|
messages: List of message dictionaries with role and content
|
||||||
temperature: Sampling temperature between 0.0 and 2.0
|
temperature: Sampling temperature between 0.0 and 2.0
|
||||||
max_tokens: Maximum number of tokens to generate
|
max_tokens: Maximum number of tokens to generate
|
||||||
|
structured_output: Enable JSON structured output mode
|
||||||
|
json_schema: JSON Schema for structured output validation
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Dictionary with response content and token usage
|
Dictionary with response content and token usage
|
||||||
@@ -317,6 +385,16 @@ class APIClient:
|
|||||||
"parts": [{"text": msg['content']}]
|
"parts": [{"text": msg['content']}]
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# Parse JSON schema if structured output is enabled
|
||||||
|
parsed_schema = None
|
||||||
|
if structured_output and json_schema:
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
parsed_schema = json.loads(json_schema)
|
||||||
|
_LOGGER.debug("Gemini structured output enabled with schema")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Structured output disabled.")
|
||||||
|
|
||||||
# Create configuration
|
# Create configuration
|
||||||
def create_config():
|
def create_config():
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
@@ -329,6 +407,11 @@ class APIClient:
|
|||||||
if system_instruction:
|
if system_instruction:
|
||||||
config.system_instruction = system_instruction.strip()
|
config.system_instruction = system_instruction.strip()
|
||||||
|
|
||||||
|
# Add structured output configuration for Gemini
|
||||||
|
if structured_output and parsed_schema:
|
||||||
|
config.response_mime_type = "application/json"
|
||||||
|
config.response_schema = parsed_schema
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
config = await asyncio.to_thread(create_config)
|
config = await asyncio.to_thread(create_config)
|
||||||
@@ -405,4 +488,5 @@ class APIClient:
|
|||||||
async def shutdown(self) -> None:
|
async def shutdown(self) -> None:
|
||||||
"""Shutdown API client."""
|
"""Shutdown API client."""
|
||||||
_LOGGER.debug("Shutting down API client")
|
_LOGGER.debug("Shutting down API client")
|
||||||
await self.session.close()
|
self._closed = True
|
||||||
|
# Do NOT close the shared Home Assistant session
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ from .const import (
|
|||||||
CONF_MAX_TOKENS,
|
CONF_MAX_TOKENS,
|
||||||
CONF_API_ENDPOINT,
|
CONF_API_ENDPOINT,
|
||||||
CONF_REQUEST_INTERVAL,
|
CONF_REQUEST_INTERVAL,
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
CONF_API_PROVIDER,
|
CONF_API_PROVIDER,
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
API_PROVIDER_OPENAI,
|
API_PROVIDER_OPENAI,
|
||||||
@@ -38,6 +39,7 @@ from .const import (
|
|||||||
DEFAULT_TEMPERATURE,
|
DEFAULT_TEMPERATURE,
|
||||||
DEFAULT_MAX_TOKENS,
|
DEFAULT_MAX_TOKENS,
|
||||||
DEFAULT_REQUEST_INTERVAL,
|
DEFAULT_REQUEST_INTERVAL,
|
||||||
|
DEFAULT_API_TIMEOUT,
|
||||||
DEFAULT_OPENAI_ENDPOINT,
|
DEFAULT_OPENAI_ENDPOINT,
|
||||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
DEFAULT_DEEPSEEK_ENDPOINT,
|
DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
@@ -48,6 +50,8 @@ from .const import (
|
|||||||
MIN_MAX_TOKENS,
|
MIN_MAX_TOKENS,
|
||||||
MAX_MAX_TOKENS,
|
MAX_MAX_TOKENS,
|
||||||
MIN_REQUEST_INTERVAL,
|
MIN_REQUEST_INTERVAL,
|
||||||
|
MIN_API_TIMEOUT,
|
||||||
|
MAX_API_TIMEOUT,
|
||||||
DEFAULT_NAME_PREFIX,
|
DEFAULT_NAME_PREFIX,
|
||||||
DEFAULT_MAX_HISTORY,
|
DEFAULT_MAX_HISTORY,
|
||||||
CONF_MAX_HISTORY_SIZE,
|
CONF_MAX_HISTORY_SIZE,
|
||||||
@@ -131,6 +135,10 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
vol.Coerce(float),
|
vol.Coerce(float),
|
||||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
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(
|
vol.Optional(
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
default=DEFAULT_CONTEXT_MESSAGES
|
default=DEFAULT_CONTEXT_MESSAGES
|
||||||
@@ -182,6 +190,10 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
vol.Coerce(float),
|
vol.Coerce(float),
|
||||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
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(
|
vol.Optional(
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
default=input_copy.get(CONF_CONTEXT_MESSAGES, DEFAULT_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.Coerce(float),
|
||||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
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(
|
vol.Optional(
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
default=input_copy.get(CONF_CONTEXT_MESSAGES, DEFAULT_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.Coerce(float),
|
||||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
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(
|
vol.Optional(
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
default=input_copy.get(CONF_CONTEXT_MESSAGES, DEFAULT_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_TEMPERATURE: user_input.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
|
||||||
CONF_MAX_TOKENS: user_input.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
|
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_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_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),
|
CONF_MAX_HISTORY_SIZE: user_input.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY),
|
||||||
}
|
}
|
||||||
@@ -452,77 +473,229 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
@callback
|
@callback
|
||||||
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
|
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
|
||||||
"""Get the options flow for this handler."""
|
"""Get the options flow for this handler."""
|
||||||
return OptionsFlowHandler(config_entry)
|
return OptionsFlowHandler()
|
||||||
|
|
||||||
|
|
||||||
class OptionsFlowHandler(config_entries.OptionsFlow):
|
class OptionsFlowHandler(config_entries.OptionsFlow):
|
||||||
"""Handle options flow."""
|
"""Handle options flow."""
|
||||||
|
|
||||||
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
|
def __init__(self) -> None:
|
||||||
"""Initialize options flow."""
|
"""Initialize options flow."""
|
||||||
self.config_entry = config_entry
|
self._errors = {}
|
||||||
|
self._selected_provider = None
|
||||||
|
|
||||||
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
def _get_default_endpoint(self, provider: str) -> str:
|
||||||
"""Manage the options."""
|
"""Get default endpoint for provider."""
|
||||||
if user_input is not None:
|
return {
|
||||||
return self.async_create_entry(title="", data=user_input)
|
API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
|
||||||
|
API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
|
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
|
API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
|
||||||
|
}.get(provider, DEFAULT_OPENAI_ENDPOINT)
|
||||||
|
|
||||||
current_data = {**self.config_entry.data, **self.config_entry.options}
|
def _get_default_model(self, provider: str) -> str:
|
||||||
provider = current_data.get(CONF_API_PROVIDER)
|
"""Get default model for provider."""
|
||||||
|
return (
|
||||||
default_model = (
|
|
||||||
DEFAULT_DEEPSEEK_MODEL if provider == API_PROVIDER_DEEPSEEK else
|
DEFAULT_DEEPSEEK_MODEL if provider == API_PROVIDER_DEEPSEEK else
|
||||||
DEFAULT_GEMINI_MODEL if provider == API_PROVIDER_GEMINI else
|
DEFAULT_GEMINI_MODEL if provider == API_PROVIDER_GEMINI else
|
||||||
DEFAULT_MODEL
|
DEFAULT_MODEL
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _get_api_headers(self, api_key: str, provider: str) -> Dict[str, str]:
|
||||||
|
"""Get API headers based on provider."""
|
||||||
|
if provider == API_PROVIDER_ANTHROPIC:
|
||||||
|
return {
|
||||||
|
"x-api-key": api_key,
|
||||||
|
"anthropic-version": "2023-06-01",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _async_validate_api(self, provider: str, api_key: str, endpoint: str) -> bool:
|
||||||
|
"""Validate API connection."""
|
||||||
|
try:
|
||||||
|
if not api_key:
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
|
||||||
|
# For Gemini, just check if API key is present
|
||||||
|
if provider == API_PROVIDER_GEMINI:
|
||||||
|
return True
|
||||||
|
|
||||||
|
session = async_get_clientsession(self.hass)
|
||||||
|
headers = self._get_api_headers(api_key, provider)
|
||||||
|
endpoint = endpoint.rstrip('/')
|
||||||
|
|
||||||
|
check_url = (
|
||||||
|
f"{endpoint}/v1/models" if provider == API_PROVIDER_ANTHROPIC
|
||||||
|
else f"{endpoint}/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
async with session.get(check_url, headers=headers) as response:
|
||||||
|
if response.status == 401:
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
elif response.status not in [200, 404]:
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as err:
|
||||||
|
_LOGGER.error("API validation error: %s", str(err))
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||||
|
"""Handle provider selection step."""
|
||||||
|
current_data = {**self.config_entry.data, **self.config_entry.options}
|
||||||
|
current_provider = current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
self._selected_provider = user_input.get(CONF_API_PROVIDER, current_provider)
|
||||||
|
return await self.async_step_settings()
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="init",
|
step_id="init",
|
||||||
data_schema=vol.Schema({
|
data_schema=vol.Schema({
|
||||||
vol.Optional(
|
vol.Required(
|
||||||
CONF_MODEL,
|
CONF_API_PROVIDER,
|
||||||
default=current_data.get(CONF_MODEL, default_model)
|
default=current_provider
|
||||||
): str,
|
): selector.SelectSelector(
|
||||||
vol.Optional(
|
selector.SelectSelectorConfig(
|
||||||
CONF_TEMPERATURE,
|
options=API_PROVIDERS,
|
||||||
default=current_data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
translation_key="api_provider"
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(float),
|
|
||||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
|
||||||
),
|
|
||||||
vol.Optional(
|
|
||||||
CONF_MAX_TOKENS,
|
|
||||||
default=current_data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(int),
|
|
||||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
|
||||||
),
|
|
||||||
vol.Optional(
|
|
||||||
CONF_REQUEST_INTERVAL,
|
|
||||||
default=current_data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(float),
|
|
||||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
|
||||||
),
|
|
||||||
vol.Optional(
|
|
||||||
CONF_CONTEXT_MESSAGES,
|
|
||||||
default=current_data.get(
|
|
||||||
CONF_CONTEXT_MESSAGES,
|
|
||||||
DEFAULT_CONTEXT_MESSAGES
|
|
||||||
)
|
)
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(int),
|
|
||||||
vol.Range(min=1, max=20)
|
|
||||||
),
|
),
|
||||||
vol.Optional(
|
}),
|
||||||
CONF_MAX_HISTORY_SIZE,
|
description_placeholders={
|
||||||
default=current_data.get(
|
"current_provider": current_provider
|
||||||
CONF_MAX_HISTORY_SIZE,
|
}
|
||||||
DEFAULT_MAX_HISTORY
|
|
||||||
)
|
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(int),
|
|
||||||
vol.Range(min=1, max=100)
|
|
||||||
),
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def async_step_settings(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||||
|
"""Handle settings configuration step."""
|
||||||
|
self._errors = {}
|
||||||
|
current_data = {**self.config_entry.data, **self.config_entry.options}
|
||||||
|
provider = self._selected_provider or current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
|
||||||
|
|
||||||
|
# Determine if provider changed to show appropriate defaults
|
||||||
|
provider_changed = provider != current_data.get(CONF_API_PROVIDER)
|
||||||
|
|
||||||
|
# Use new defaults if provider changed, otherwise use current values
|
||||||
|
if provider_changed:
|
||||||
|
default_endpoint = self._get_default_endpoint(provider)
|
||||||
|
default_model = self._get_default_model(provider)
|
||||||
|
else:
|
||||||
|
default_endpoint = current_data.get(CONF_API_ENDPOINT, self._get_default_endpoint(provider))
|
||||||
|
default_model = current_data.get(CONF_MODEL, self._get_default_model(provider))
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
# Validate API connection
|
||||||
|
api_key = user_input.get(CONF_API_KEY, current_data.get(CONF_API_KEY, ""))
|
||||||
|
endpoint = user_input.get(CONF_API_ENDPOINT, default_endpoint)
|
||||||
|
|
||||||
|
if await self._async_validate_api(provider, api_key, endpoint):
|
||||||
|
# Merge with provider selection
|
||||||
|
final_data = {
|
||||||
|
CONF_API_PROVIDER: provider,
|
||||||
|
**user_input
|
||||||
|
}
|
||||||
|
return self.async_create_entry(title="", data=final_data)
|
||||||
|
|
||||||
|
# Show form again with errors
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="settings",
|
||||||
|
data_schema=self._get_settings_schema(
|
||||||
|
provider=provider,
|
||||||
|
current_data=current_data,
|
||||||
|
user_input=user_input,
|
||||||
|
default_endpoint=default_endpoint,
|
||||||
|
default_model=default_model,
|
||||||
|
),
|
||||||
|
errors=self._errors
|
||||||
|
)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="settings",
|
||||||
|
data_schema=self._get_settings_schema(
|
||||||
|
provider=provider,
|
||||||
|
current_data=current_data,
|
||||||
|
user_input=None,
|
||||||
|
default_endpoint=default_endpoint,
|
||||||
|
default_model=default_model,
|
||||||
|
),
|
||||||
|
description_placeholders={
|
||||||
|
"provider": provider
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_settings_schema(
|
||||||
|
self,
|
||||||
|
provider: str,
|
||||||
|
current_data: Dict[str, Any],
|
||||||
|
user_input: Optional[Dict[str, Any]],
|
||||||
|
default_endpoint: str,
|
||||||
|
default_model: str,
|
||||||
|
) -> vol.Schema:
|
||||||
|
"""Build settings schema."""
|
||||||
|
data = user_input or current_data
|
||||||
|
|
||||||
|
return vol.Schema({
|
||||||
|
vol.Required(
|
||||||
|
CONF_API_KEY,
|
||||||
|
default=data.get(CONF_API_KEY, "")
|
||||||
|
): str,
|
||||||
|
vol.Required(
|
||||||
|
CONF_API_ENDPOINT,
|
||||||
|
default=data.get(CONF_API_ENDPOINT, default_endpoint)
|
||||||
|
): str,
|
||||||
|
vol.Required(
|
||||||
|
CONF_MODEL,
|
||||||
|
default=data.get(CONF_MODEL, default_model)
|
||||||
|
): str,
|
||||||
|
vol.Optional(
|
||||||
|
CONF_TEMPERATURE,
|
||||||
|
default=data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(float),
|
||||||
|
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_MAX_TOKENS,
|
||||||
|
default=data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_REQUEST_INTERVAL,
|
||||||
|
default=data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(float),
|
||||||
|
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
|
default=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=data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=1, max=20)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_MAX_HISTORY_SIZE,
|
||||||
|
default=data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=1, max=100)
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|||||||
@@ -61,10 +61,13 @@ CONF_TEMPERATURE: Final = "temperature"
|
|||||||
CONF_MAX_TOKENS: Final = "max_tokens"
|
CONF_MAX_TOKENS: Final = "max_tokens"
|
||||||
CONF_API_ENDPOINT: Final = "api_endpoint"
|
CONF_API_ENDPOINT: Final = "api_endpoint"
|
||||||
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
||||||
|
CONF_API_TIMEOUT: Final = "api_timeout"
|
||||||
CONF_INSTANCE: Final = "instance"
|
CONF_INSTANCE: Final = "instance"
|
||||||
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
|
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
|
||||||
CONF_IS_ANTHROPIC: Final = "is_anthropic"
|
CONF_IS_ANTHROPIC: Final = "is_anthropic"
|
||||||
CONF_CONTEXT_MESSAGES: Final = "context_messages"
|
CONF_CONTEXT_MESSAGES: Final = "context_messages"
|
||||||
|
CONF_STRUCTURED_OUTPUT: Final = "structured_output"
|
||||||
|
CONF_JSON_SCHEMA: Final = "json_schema"
|
||||||
|
|
||||||
ABSOLUTE_MAX_HISTORY_SIZE = 500
|
ABSOLUTE_MAX_HISTORY_SIZE = 500
|
||||||
MAX_ATTRIBUTE_SIZE = 4 * 1024
|
MAX_ATTRIBUTE_SIZE = 4 * 1024
|
||||||
@@ -79,6 +82,7 @@ DEFAULT_TEMPERATURE: Final = 0.1
|
|||||||
DEFAULT_MAX_TOKENS: Final = 1000
|
DEFAULT_MAX_TOKENS: Final = 1000
|
||||||
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
||||||
DEFAULT_TIMEOUT: Final = 30
|
DEFAULT_TIMEOUT: Final = 30
|
||||||
|
DEFAULT_API_TIMEOUT: Final = 30
|
||||||
DEFAULT_MAX_HISTORY: Final = 50
|
DEFAULT_MAX_HISTORY: Final = 50
|
||||||
DEFAULT_NAME: Final = "HA Text AI"
|
DEFAULT_NAME: Final = "HA Text AI"
|
||||||
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||||
@@ -93,9 +97,11 @@ MIN_MAX_TOKENS: Final = 1
|
|||||||
MAX_MAX_TOKENS: Final = 100000
|
MAX_MAX_TOKENS: Final = 100000
|
||||||
MIN_REQUEST_INTERVAL: Final = 0.1
|
MIN_REQUEST_INTERVAL: Final = 0.1
|
||||||
MAX_REQUEST_INTERVAL: Final = 60.0
|
MAX_REQUEST_INTERVAL: Final = 60.0
|
||||||
|
MIN_API_TIMEOUT: Final = 5
|
||||||
|
MAX_API_TIMEOUT: Final = 600
|
||||||
|
|
||||||
# API constants
|
# API constants
|
||||||
API_TIMEOUT: Final = 30
|
API_TIMEOUT: Final = 30 # Legacy constant, use CONF_API_TIMEOUT from config
|
||||||
API_RETRY_COUNT: Final = 3
|
API_RETRY_COUNT: Final = 3
|
||||||
|
|
||||||
# Service names
|
# Service names
|
||||||
@@ -195,7 +201,9 @@ SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
|||||||
vol.Optional("context_messages"): vol.All(
|
vol.Optional("context_messages"): vol.All(
|
||||||
vol.Coerce(int),
|
vol.Coerce(int),
|
||||||
vol.Range(min=1, max=20)
|
vol.Range(min=1, max=20)
|
||||||
)
|
),
|
||||||
|
vol.Optional(CONF_STRUCTURED_OUTPUT, default=False): cv.boolean,
|
||||||
|
vol.Optional(CONF_JSON_SCHEMA): cv.string,
|
||||||
})
|
})
|
||||||
|
|
||||||
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||||
@@ -232,6 +240,10 @@ CONFIG_SCHEMA = vol.Schema({
|
|||||||
vol.Coerce(float),
|
vol.Coerce(float),
|
||||||
vol.Range(min=MIN_REQUEST_INTERVAL, max=MAX_REQUEST_INTERVAL)
|
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.Optional(CONF_MAX_HISTORY_SIZE, default=DEFAULT_MAX_HISTORY): vol.All( # Correct usage
|
||||||
vol.Coerce(int),
|
vol.Coerce(int),
|
||||||
vol.Range(min=1, max=100),
|
vol.Range(min=1, max=100),
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ from .const import (
|
|||||||
DEFAULT_MAX_TOKENS,
|
DEFAULT_MAX_TOKENS,
|
||||||
DEFAULT_TEMPERATURE,
|
DEFAULT_TEMPERATURE,
|
||||||
DEFAULT_MAX_HISTORY,
|
DEFAULT_MAX_HISTORY,
|
||||||
|
DEFAULT_API_TIMEOUT,
|
||||||
DEFAULT_CONTEXT_MESSAGES,
|
DEFAULT_CONTEXT_MESSAGES,
|
||||||
ABSOLUTE_MAX_HISTORY_SIZE,
|
ABSOLUTE_MAX_HISTORY_SIZE,
|
||||||
MAX_ATTRIBUTE_SIZE,
|
MAX_ATTRIBUTE_SIZE,
|
||||||
@@ -76,6 +77,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
max_history_size: int = DEFAULT_MAX_HISTORY,
|
max_history_size: int = DEFAULT_MAX_HISTORY,
|
||||||
context_messages: int = DEFAULT_CONTEXT_MESSAGES,
|
context_messages: int = DEFAULT_CONTEXT_MESSAGES,
|
||||||
is_anthropic: bool = False,
|
is_anthropic: bool = False,
|
||||||
|
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize coordinator."""
|
"""Initialize coordinator."""
|
||||||
self.instance_name = instance_name
|
self.instance_name = instance_name
|
||||||
@@ -115,6 +117,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
ABSOLUTE_MAX_HISTORY_SIZE
|
ABSOLUTE_MAX_HISTORY_SIZE
|
||||||
)
|
)
|
||||||
self.is_anthropic = is_anthropic
|
self.is_anthropic = is_anthropic
|
||||||
|
self.api_timeout = api_timeout
|
||||||
|
|
||||||
# Initialize essential attributes
|
# Initialize essential attributes
|
||||||
self._is_processing = False
|
self._is_processing = False
|
||||||
@@ -186,16 +189,10 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
# Maximum history file size (1 MB) from const.py
|
# Maximum history file size (1 MB) from const.py
|
||||||
self._max_history_file_size = MAX_HISTORY_FILE_SIZE
|
self._max_history_file_size = MAX_HISTORY_FILE_SIZE
|
||||||
|
|
||||||
# Asynchronous file initialization
|
self.context_messages = context_messages
|
||||||
hass.async_create_task(self.async_initialize_history_file())
|
|
||||||
|
|
||||||
_LOGGER.info(f"Initialized HA Text AI coordinator with instance: {instance_name}")
|
_LOGGER.info(f"Initialized HA Text AI coordinator with instance: {instance_name}")
|
||||||
|
|
||||||
# Register instance
|
|
||||||
self.hass.data.setdefault(DOMAIN, {})
|
|
||||||
self.hass.data[DOMAIN][instance_name] = self
|
|
||||||
self.context_messages = context_messages
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def last_response(self) -> Dict[str, Any]:
|
def last_response(self) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
@@ -823,6 +820,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
max_tokens: Optional[int] = None,
|
max_tokens: Optional[int] = None,
|
||||||
system_prompt: Optional[str] = None,
|
system_prompt: Optional[str] = None,
|
||||||
context_messages: Optional[int] = None,
|
context_messages: Optional[int] = None,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""
|
"""
|
||||||
Process a question with optional parameters.
|
Process a question with optional parameters.
|
||||||
@@ -838,12 +837,15 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
max_tokens: Optional maximum response length
|
max_tokens: Optional maximum response length
|
||||||
system_prompt: Optional system-level instruction
|
system_prompt: Optional system-level instruction
|
||||||
context_messages: Optional number of context messages to include
|
context_messages: Optional number of context messages to include
|
||||||
|
structured_output: Enable JSON structured output mode
|
||||||
|
json_schema: JSON Schema for structured output validation
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Full response dictionary from the AI
|
Full response dictionary from the AI
|
||||||
"""
|
"""
|
||||||
return await self.async_process_question(
|
return await self.async_process_question(
|
||||||
question, model, temperature, max_tokens, system_prompt, context_messages
|
question, model, temperature, max_tokens, system_prompt, context_messages,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
|
|
||||||
async def async_process_question(
|
async def async_process_question(
|
||||||
@@ -854,6 +856,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
max_tokens: Optional[int] = None,
|
max_tokens: Optional[int] = None,
|
||||||
system_prompt: Optional[str] = None,
|
system_prompt: Optional[str] = None,
|
||||||
context_messages: Optional[int] = None,
|
context_messages: Optional[int] = None,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Process question with context management."""
|
"""Process question with context management."""
|
||||||
if self.client is None:
|
if self.client is None:
|
||||||
@@ -892,6 +896,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
"temperature": temp_temperature,
|
"temperature": temp_temperature,
|
||||||
"max_tokens": temp_max_tokens,
|
"max_tokens": temp_max_tokens,
|
||||||
"messages": messages,
|
"messages": messages,
|
||||||
|
"structured_output": structured_output,
|
||||||
|
"json_schema": json_schema,
|
||||||
}
|
}
|
||||||
|
|
||||||
response = await self.async_process_message(question, **kwargs)
|
response = await self.async_process_message(question, **kwargs)
|
||||||
@@ -906,7 +912,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
self._handle_error(err)
|
await self._handle_error(err)
|
||||||
raise HomeAssistantError(f"Failed to process question: {err}")
|
raise HomeAssistantError(f"Failed to process question: {err}")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
@@ -916,11 +922,15 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
async def async_process_message(self, question: str, **kwargs) -> dict:
|
async def async_process_message(self, question: str, **kwargs) -> dict:
|
||||||
"""Process message using the AI client."""
|
"""Process message using the AI client."""
|
||||||
try:
|
try:
|
||||||
async with asyncio.timeout(60): # 60 second timeout
|
structured_output = kwargs.pop("structured_output", False)
|
||||||
if self.is_anthropic:
|
json_schema = kwargs.pop("json_schema", None)
|
||||||
response = await self._process_anthropic_message(question, **kwargs)
|
|
||||||
else:
|
async with asyncio.timeout(self.api_timeout):
|
||||||
response = await self._process_openai_message(question, **kwargs)
|
# APIClient.create() handles provider routing internally
|
||||||
|
response = await self._process_openai_message(
|
||||||
|
question, structured_output=structured_output,
|
||||||
|
json_schema=json_schema, **kwargs
|
||||||
|
)
|
||||||
|
|
||||||
# Add timestamp and model information to response
|
# Add timestamp and model information to response
|
||||||
timestamp = dt_util.utcnow().isoformat()
|
timestamp = dt_util.utcnow().isoformat()
|
||||||
@@ -956,30 +966,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
await self._handle_error(err)
|
await self._handle_error(err)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def _process_anthropic_message(self, question: str, **kwargs) -> dict:
|
async def _process_openai_message(self, question: str, structured_output: bool = False,
|
||||||
"""Process message using Anthropic API."""
|
json_schema: Optional[str] = None, **kwargs) -> dict:
|
||||||
try:
|
|
||||||
_LOGGER.debug(f"Anthropic API call: model={kwargs['model']}, max_tokens={kwargs['max_tokens']}")
|
|
||||||
response = await self.client.messages.create(
|
|
||||||
model=kwargs["model"],
|
|
||||||
max_tokens=kwargs["max_tokens"],
|
|
||||||
messages=kwargs["messages"],
|
|
||||||
temperature=kwargs["temperature"],
|
|
||||||
)
|
|
||||||
_LOGGER.debug(f"Anthropic response: tokens={response.usage}")
|
|
||||||
return {
|
|
||||||
"content": response.content[0].text,
|
|
||||||
"tokens": {
|
|
||||||
"prompt": response.usage.input_tokens,
|
|
||||||
"completion": response.usage.output_tokens,
|
|
||||||
"total": response.usage.input_tokens + response.usage.output_tokens,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
except Exception as e:
|
|
||||||
_LOGGER.error(f"Anthropic API error: {str(e)}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def _process_openai_message(self, question: str, **kwargs) -> dict:
|
|
||||||
"""Process message using OpenAI API."""
|
"""Process message using OpenAI API."""
|
||||||
try:
|
try:
|
||||||
response = await self.client.create(
|
response = await self.client.create(
|
||||||
@@ -987,6 +975,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
messages=kwargs["messages"],
|
messages=kwargs["messages"],
|
||||||
temperature=kwargs["temperature"],
|
temperature=kwargs["temperature"],
|
||||||
max_tokens=kwargs["max_tokens"],
|
max_tokens=kwargs["max_tokens"],
|
||||||
|
structured_output=structured_output,
|
||||||
|
json_schema=json_schema,
|
||||||
)
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1085,9 +1075,60 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
|||||||
_LOGGER.error(f"Error clearing history: {e}")
|
_LOGGER.error(f"Error clearing history: {e}")
|
||||||
_LOGGER.debug(traceback.format_exc())
|
_LOGGER.debug(traceback.format_exc())
|
||||||
|
|
||||||
async def async_get_history(self) -> List[Dict[str, str]]:
|
async def async_get_history(
|
||||||
"""Get conversation history."""
|
self,
|
||||||
return self._conversation_history
|
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:
|
async def async_set_system_prompt(self, prompt: str) -> None:
|
||||||
"""Set system prompt."""
|
"""Set system prompt."""
|
||||||
|
|||||||
@@ -14,16 +14,17 @@
|
|||||||
"mqtt": [],
|
"mqtt": [],
|
||||||
"quality_scale": "silver",
|
"quality_scale": "silver",
|
||||||
"requirements": [
|
"requirements": [
|
||||||
"openai>=1.12.0",
|
"aiofiles>=23.0.0",
|
||||||
"anthropic>=0.8.0",
|
|
||||||
"google-genai>=1.16.0",
|
|
||||||
"aiohttp>=3.8.0",
|
"aiohttp>=3.8.0",
|
||||||
|
"anthropic>=0.8.0",
|
||||||
"async-timeout>=4.0.0",
|
"async-timeout>=4.0.0",
|
||||||
"certifi>=2024.2.2"
|
"certifi>=2024.2.2",
|
||||||
|
"google-genai>=1.16.0",
|
||||||
|
"openai>=1.12.0"
|
||||||
],
|
],
|
||||||
"single_config_entry": false,
|
"single_config_entry": false,
|
||||||
"ssdp": [],
|
"ssdp": [],
|
||||||
"usb": [],
|
"usb": [],
|
||||||
"version": "2.1.8",
|
"version": "2.3.0",
|
||||||
"zeroconf": []
|
"zeroconf": []
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -74,6 +74,24 @@ ask_question:
|
|||||||
step: 1
|
step: 1
|
||||||
mode: box
|
mode: box
|
||||||
|
|
||||||
|
structured_output:
|
||||||
|
name: Structured Output
|
||||||
|
description: Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema.
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
selector:
|
||||||
|
boolean: {}
|
||||||
|
|
||||||
|
json_schema:
|
||||||
|
name: JSON Schema
|
||||||
|
description: >-
|
||||||
|
JSON Schema defining the structure of the expected response.
|
||||||
|
Required when structured_output is enabled.
|
||||||
|
required: false
|
||||||
|
selector:
|
||||||
|
text:
|
||||||
|
multiline: true
|
||||||
|
|
||||||
clear_history:
|
clear_history:
|
||||||
name: Clear History
|
name: Clear History
|
||||||
description: >-
|
description: >-
|
||||||
@@ -135,7 +153,7 @@ get_history:
|
|||||||
required: false
|
required: false
|
||||||
default: false
|
default: false
|
||||||
selector:
|
selector:
|
||||||
boolean:
|
boolean: {}
|
||||||
|
|
||||||
sort_order:
|
sort_order:
|
||||||
name: Sort Order
|
name: Sort Order
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
|
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
|
||||||
"max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
|
"max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
|
||||||
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
|
"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)",
|
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +38,7 @@
|
|||||||
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
||||||
"api_provider": "API-Anbieter",
|
"api_provider": "API-Anbieter",
|
||||||
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
|
"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)",
|
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +74,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Instanzeinstellungen aktualisieren",
|
"title": "Anbieter auswählen",
|
||||||
"description": "Ändern Sie die Einstellungen für diese AI-Assistenteninstanz.",
|
"description": "Wählen Sie den AI-Anbieter für diese Instanz. Die Integration wird nach dem Speichern der Änderungen neu geladen.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "API-Anbieter"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Verbindungs- und Modelleinstellungen",
|
||||||
|
"description": "Konfigurieren Sie API-Anmeldeinformationen und Modellparameter. Änderungen werden nach dem Neuladen der Integration wirksam.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API-Schlüssel",
|
||||||
|
"api_endpoint": "API-Endpunkt-URL",
|
||||||
"model": "AI-Modell",
|
"model": "AI-Modell",
|
||||||
"temperature": "Kreativität der Antwort (0-2)",
|
"temperature": "Kreativität der Antwort (0-2)",
|
||||||
"max_tokens": "Maximale Länge der Antwort (1-100000)",
|
"max_tokens": "Maximale Länge der Antwort (1-100000)",
|
||||||
"request_interval": "Minimale Anfrageintervall (0,1-60 Sekunden)",
|
"request_interval": "Minimales 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)",
|
"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)"
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
}
|
}
|
||||||
@@ -127,6 +139,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Max Tokens",
|
"name": "Max Tokens",
|
||||||
"description": "Maximale Länge der Antwort (1-100000 Token)"
|
"description": "Maximale Länge der Antwort (1-100000 Token)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Strukturierte Ausgabe",
|
||||||
|
"description": "JSON-Strukturausgabemodus aktivieren. Bei Aktivierung antwortet die KI mit gültigem JSON, das dem angegebenen Schema entspricht."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON-Schema",
|
||||||
|
"description": "JSON-Schema, das die Struktur der erwarteten Antwort definiert. Erforderlich wenn structured_output aktiviert ist."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
"temperature": "Response creativity (0-2, lower = more focused)",
|
"temperature": "Response creativity (0-2, lower = more focused)",
|
||||||
"max_tokens": "Maximum response length (1-100000 tokens)",
|
"max_tokens": "Maximum response length (1-100000 tokens)",
|
||||||
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
"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)",
|
"context_messages": "Number of context messages to retain (1-20)",
|
||||||
"max_history_size": "Maximum conversation history size (1-100)"
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +38,7 @@
|
|||||||
"api_endpoint": "Custom API endpoint URL (optional)",
|
"api_endpoint": "Custom API endpoint URL (optional)",
|
||||||
"api_provider": "API Provider",
|
"api_provider": "API Provider",
|
||||||
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
"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)",
|
"context_messages": "Number of context messages to retain (1-20)",
|
||||||
"max_history_size": "Maximum conversation history size (1-100)"
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +74,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Update Instance Settings",
|
"title": "Select Provider",
|
||||||
"description": "Modify settings for this AI assistant instance.",
|
"description": "Choose the AI provider for this instance. The integration will reload after saving changes.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "API Provider"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Connection & Model Settings",
|
||||||
|
"description": "Configure API credentials and model parameters. Changes will take effect after the integration reloads.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API Key",
|
||||||
|
"api_endpoint": "API Endpoint URL",
|
||||||
"model": "AI model",
|
"model": "AI model",
|
||||||
"temperature": "Response creativity (0-2)",
|
"temperature": "Response creativity (0-2)",
|
||||||
"max_tokens": "Maximum response length (1-100000)",
|
"max_tokens": "Maximum response length (1-100000)",
|
||||||
"request_interval": "Minimum request interval (0.1-60 seconds)",
|
"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)",
|
"context_messages": "Number of previous messages to include in context (1-20)",
|
||||||
"max_history_size": "Maximum conversation history size (1-100)"
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
}
|
}
|
||||||
@@ -127,6 +139,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Max Tokens",
|
"name": "Max Tokens",
|
||||||
"description": "Maximum length of the response (1-100000 tokens)"
|
"description": "Maximum length of the response (1-100000 tokens)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Structured Output",
|
||||||
|
"description": "Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON Schema",
|
||||||
|
"description": "JSON Schema defining the structure of the expected response. Required when structured_output is enabled."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
|
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
|
||||||
"max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
|
"max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
|
||||||
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
"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)",
|
"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)"
|
"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_endpoint": "URL del endpoint de API personalizado (opcional)",
|
||||||
"api_provider": "Proveedor de API",
|
"api_provider": "Proveedor de API",
|
||||||
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
"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)",
|
"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)"
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +74,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Actualizar configuración de la instancia",
|
"title": "Seleccionar proveedor",
|
||||||
"description": "Modifica la configuración para esta instancia de asistente de IA.",
|
"description": "Elige el proveedor de IA para esta instancia. La integración se recargará después de guardar los cambios.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "Proveedor de API"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Configuración de conexión y modelo",
|
||||||
|
"description": "Configura las credenciales de API y los parámetros del modelo. Los cambios tendrán efecto después de recargar la integración.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "Clave API",
|
||||||
|
"api_endpoint": "URL del endpoint de API",
|
||||||
"model": "Modelo de IA",
|
"model": "Modelo de IA",
|
||||||
"temperature": "Creatividad de la respuesta (0-2)",
|
"temperature": "Creatividad de la respuesta (0-2)",
|
||||||
"max_tokens": "Longitud máxima de la respuesta (1-100000)",
|
"max_tokens": "Longitud máxima de la respuesta (1-100000)",
|
||||||
"request_interval": "Intervalo mínimo de solicitud (0.1-60 segundos)",
|
"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)",
|
"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)"
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
}
|
}
|
||||||
@@ -127,6 +139,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Máx. Tokens",
|
"name": "Máx. Tokens",
|
||||||
"description": "Longitud máxima de la respuesta (1-100000 tokens)"
|
"description": "Longitud máxima de la respuesta (1-100000 tokens)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Salida Estructurada",
|
||||||
|
"description": "Habilitar modo de salida JSON estructurada. Cuando está habilitado, la IA responderá con JSON válido que coincida con el esquema proporcionado."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "Esquema JSON",
|
||||||
|
"description": "Esquema JSON que define la estructura de la respuesta esperada. Requerido cuando structured_output está habilitado."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
||||||
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
||||||
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
}
|
}
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
||||||
"api_provider": "एपीआई प्रदाता",
|
"api_provider": "एपीआई प्रदाता",
|
||||||
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
}
|
}
|
||||||
@@ -63,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "उदाहरण सेटिंग्स अपडेट करें",
|
"title": "प्रदाता चुनें",
|
||||||
"description": "इस एआई सहायक उदाहरण के लिए सेटिंग्स संशोधित करें।",
|
"description": "इस उदाहरण के लिए एआई प्रदाता चुनें। परिवर्तन सहेजने के बाद एकीकरण पुनः लोड होगा।",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "एपीआई प्रदाता"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "कनेक्शन और मॉडल सेटिंग्स",
|
||||||
|
"description": "एपीआई क्रेडेंशियल और मॉडल पैरामीटर कॉन्फ़िगर करें। एकीकरण पुनः लोड होने के बाद परिवर्तन प्रभावी होंगे।",
|
||||||
|
"data": {
|
||||||
|
"api_key": "एपीआई कुंजी",
|
||||||
|
"api_endpoint": "एपीआई एंडपॉइंट यूआरएल",
|
||||||
"model": "एआई मॉडल",
|
"model": "एआई मॉडल",
|
||||||
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
|
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
|
||||||
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
|
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
|
||||||
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
|
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
|
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
|
||||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
}
|
}
|
||||||
@@ -118,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "अधिकतम टोकन",
|
"name": "अधिकतम टोकन",
|
||||||
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
|
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "संरचित आउटपुट",
|
||||||
|
"description": "JSON संरचित आउटपुट मोड सक्षम करें। सक्षम होने पर, AI प्रदान किए गए स्कीमा से मेल खाने वाले वैध JSON के साथ प्रतिक्रिया देगा।"
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON स्कीमा",
|
||||||
|
"description": "अपेक्षित प्रतिक्रिया की संरचना को परिभाषित करने वाला JSON स्कीमा। structured_output सक्षम होने पर आवश्यक।"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
||||||
"max_tokens": "Lunghezza massima della risposta (1-100000 token)",
|
"max_tokens": "Lunghezza massima della risposta (1-100000 token)",
|
||||||
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
"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)",
|
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +38,7 @@
|
|||||||
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
|
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
|
||||||
"api_provider": "Fornitore API",
|
"api_provider": "Fornitore API",
|
||||||
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
"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)",
|
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +74,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Aggiorna impostazioni dell'istanza",
|
"title": "Seleziona fornitore",
|
||||||
"description": "Modifica le impostazioni per questa istanza di assistente AI.",
|
"description": "Scegli il fornitore AI per questa istanza. L'integrazione verrà ricaricata dopo aver salvato le modifiche.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "Fornitore API"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Impostazioni di connessione e modello",
|
||||||
|
"description": "Configura le credenziali API e i parametri del modello. Le modifiche avranno effetto dopo il ricaricamento dell'integrazione.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "Chiave API",
|
||||||
|
"api_endpoint": "URL dell'endpoint API",
|
||||||
"model": "Modello AI",
|
"model": "Modello AI",
|
||||||
"temperature": "Creatività della risposta (0-2)",
|
"temperature": "Creatività della risposta (0-2)",
|
||||||
"max_tokens": "Lunghezza massima della risposta (1-100000)",
|
"max_tokens": "Lunghezza massima della risposta (1-100000)",
|
||||||
"request_interval": "Intervallo minimo di richiesta (0.1-60 secondi)",
|
"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)",
|
"context_messages": "Numero di messaggi precedenti da includere nel contesto (1-20)",
|
||||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
}
|
}
|
||||||
@@ -127,6 +139,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Token massimi",
|
"name": "Token massimi",
|
||||||
"description": "Lunghezza massima della risposta (1-100000 token)"
|
"description": "Lunghezza massima della risposta (1-100000 token)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Output Strutturato",
|
||||||
|
"description": "Abilita la modalità di output JSON strutturato. Quando abilitato, l'IA risponderà con JSON valido corrispondente allo schema fornito."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "Schema JSON",
|
||||||
|
"description": "Schema JSON che definisce la struttura della risposta attesa. Richiesto quando structured_output è abilitato."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
||||||
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
||||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +38,7 @@
|
|||||||
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
||||||
"api_provider": "Провайдер API",
|
"api_provider": "Провайдер API",
|
||||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +74,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Обновление настроек экземпляра",
|
"title": "Выбор провайдера",
|
||||||
"description": "Измените настройки для этого экземпляра ИИ-помощника.",
|
"description": "Выберите провайдера ИИ для этого экземпляра. Интеграция перезагрузится после сохранения изменений.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "Провайдер API"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Настройки подключения и модели",
|
||||||
|
"description": "Настройте учётные данные API и параметры модели. Изменения вступят в силу после перезагрузки интеграции.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API-ключ",
|
||||||
|
"api_endpoint": "URL конечной точки API",
|
||||||
"model": "Модель ИИ",
|
"model": "Модель ИИ",
|
||||||
"temperature": "Креативность ответа (0-2)",
|
"temperature": "Креативность ответа (0-2)",
|
||||||
"max_tokens": "Максимальная длина ответа (1-100000)",
|
"max_tokens": "Максимальная длина ответа (1-100000)",
|
||||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
|
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
|
||||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -127,6 +139,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Максимум токенов",
|
"name": "Максимум токенов",
|
||||||
"description": "Максимальная длина ответа (1-100000 токенов)"
|
"description": "Максимальная длина ответа (1-100000 токенов)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Структурированный вывод",
|
||||||
|
"description": "Включить режим структурированного JSON-вывода. При включении ИИ будет отвечать валидным JSON, соответствующим указанной схеме."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON Schema",
|
||||||
|
"description": "JSON-схема, определяющая структуру ожидаемого ответа. Обязательна при включении structured_output."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
||||||
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
||||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
||||||
"api_provider": "API провајдер",
|
"api_provider": "API провајдер",
|
||||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -63,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Ажурирајте подешавања инстанце",
|
"title": "Изаберите провајдера",
|
||||||
"description": "Измените подешавања за ову AI асистент инстанцу.",
|
"description": "Изаберите AI провајдера за ову инстанцу. Интеграција ће се поново учитати након чувања измена.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "API провајдер"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Подешавања везе и модела",
|
||||||
|
"description": "Конфигуришите API акредитиве и параметре модела. Промене ће ступити на снагу након поновног учитавања интеграције.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API кључ",
|
||||||
|
"api_endpoint": "URL API крајње тачке",
|
||||||
"model": "AI модел",
|
"model": "AI модел",
|
||||||
"temperature": "Креативност одговора (0-2)",
|
"temperature": "Креативност одговора (0-2)",
|
||||||
"max_tokens": "Максимална дужина одговора (1-100000)",
|
"max_tokens": "Максимална дужина одговора (1-100000)",
|
||||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
|
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
|
||||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -118,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Максимални токени",
|
"name": "Максимални токени",
|
||||||
"description": "Максимална дужина одговора (1-100000 токена)"
|
"description": "Максимална дужина одговора (1-100000 токена)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Структурисани излаз",
|
||||||
|
"description": "Омогући JSON структурисани излаз. Када је омогућено, AI ће одговарати валидним JSON-ом који одговара датој шеми."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON шема",
|
||||||
|
"description": "JSON шема која дефинише структуру очекиваног одговора. Обавезна када је structured_output омогућен."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
"temperature": "响应创造力(0-2,越低越专注)",
|
"temperature": "响应创造力(0-2,越低越专注)",
|
||||||
"max_tokens": "最大响应长度(1-100000个标记)",
|
"max_tokens": "最大响应长度(1-100000个标记)",
|
||||||
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
"context_messages": "保留的上下文消息数量(1-20)",
|
"context_messages": "保留的上下文消息数量(1-20)",
|
||||||
"max_history_size": "最大对话历史大小(1-100)"
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
}
|
}
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
"api_endpoint": "自定义API端点URL(可选)",
|
"api_endpoint": "自定义API端点URL(可选)",
|
||||||
"api_provider": "API提供者",
|
"api_provider": "API提供者",
|
||||||
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
"context_messages": "保留的上下文消息数量(1-20)",
|
"context_messages": "保留的上下文消息数量(1-20)",
|
||||||
"max_history_size": "最大对话历史大小(1-100)"
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
}
|
}
|
||||||
@@ -63,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "更新实例设置",
|
"title": "选择提供者",
|
||||||
"description": "修改此AI助手实例的设置。",
|
"description": "选择此实例的AI提供者。保存更改后集成将重新加载。",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "API提供者"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "连接和模型设置",
|
||||||
|
"description": "配置API凭据和模型参数。更改将在集成重新加载后生效。",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API密钥",
|
||||||
|
"api_endpoint": "API端点URL",
|
||||||
"model": "AI模型",
|
"model": "AI模型",
|
||||||
"temperature": "响应创造力(0-2)",
|
"temperature": "响应创造力(0-2)",
|
||||||
"max_tokens": "最大响应长度(1-100000)",
|
"max_tokens": "最大响应长度(1-100000)",
|
||||||
"request_interval": "最小请求间隔(0.1-60秒)",
|
"request_interval": "最小请求间隔(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
"context_messages": "要包含在上下文中的先前消息数量(1-20)",
|
"context_messages": "要包含在上下文中的先前消息数量(1-20)",
|
||||||
"max_history_size": "最大对话历史大小(1-100)"
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
}
|
}
|
||||||
@@ -118,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "最大标记数",
|
"name": "最大标记数",
|
||||||
"description": "响应的最大长度(1-100000个标记)"
|
"description": "响应的最大长度(1-100000个标记)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "结构化输出",
|
||||||
|
"description": "启用JSON结构化输出模式。启用后,AI将以符合提供的模式的有效JSON进行响应。"
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON模式",
|
||||||
|
"description": "定义预期响应结构的JSON模式。启用structured_output时必需。"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user