Compare commits

...
35 Commits
Author SHA1 Message Date
SMKRV bfd64d1122 Release v2.1.1: Token Handling Improvement and DeepSeek Support
- Completely reworked token handling mechanism
- Removed custom token calculation logic
- Direct max_tokens passing to LLM APIs
- Added support for DeepSeek provider
- Integrated deepseek-chat and deepseek-reasoner models

Thanks to @estiens for reporting token handling issues and providing valuable feedback (https://github.com/smkrv/ha-text-ai/issues/1).
2025-01-28 15:54:48 +03:00
SMKRV 82e1f0c4f9 Release v2.1.0 2024-12-13 00:06:08 +03:00
SMKRV 5c16eee6e4 fix: Read version from manifest.json 2024-12-12 16:03:15 +03:00
SMKRV e988d445a4 - Fixed version reading from manifest.json implementation 2024-12-11 22:01:01 +03:00
SMKRV f9bfb9ab7f fix: correct sw_version syntax in device_info
- Fixed version reading from manifest.json implementation
2024-12-11 21:57:27 +03:00
SMKRV 92dd1bc110 ~ 2024-12-11 00:00:12 +03:00
SMKRV 17d547325a refactor(docs): updated README services examples with more detailed configuration 2024-12-10 23:33:32 +03:00
SMKRV b8cb70217c refactor(docs): updated README shields 2024-12-10 23:27:49 +03:00
SMKRV 530d04f25d refactor(docs): updated README shields 2024-12-10 23:27:18 +03:00
SMKRV b71083b9bf bump to version 2.0.9 2024-12-10 17:25:47 +03:00
SMKRV f9f7d10f7f refactor(docs): updated README images 2024-12-10 17:21:41 +03:00
SMKRV 9f7cb20621 refactor(docs): updated README images 2024-12-10 17:19:52 +03:00
SMKRV 6fc3b23365 refactor(docs): updated README images 2024-12-10 17:18:55 +03:00
SMKRV 15c717fcb0 fix: Display only last Q&A in sensor state to prevent data truncation
- Show only the latest question and answer in sensor state
- Keep full conversation history in attributes
- Fix truncation issues in Home Assistant UI
- Maintain backwards compatibility
- No configuration changes required
2024-12-10 17:02:48 +03:00
SMKRV be06fddce1 fix: Display only last Q&A in sensor state to prevent data truncation
- Show only the latest question and answer in sensor state
- Keep full conversation history in attributes
- Fix truncation issues in Home Assistant UI
- Maintain backwards compatibility
- No configuration changes required
2024-12-10 16:19:17 +03:00
SMKRV 5f0bd861a7 docs(readme): Included note that the integration has been submitted to HACS store and is currently pending review in pull request: [pull request #2896](hacs/default#2896). 2024-12-10 00:00:18 +03:00
SMKRV 428aee46c8 docs(readme): Included note that the integration has been submitted to HACS store and is currently pending review in pull request: [pull request #2896](hacs/default#2896). 2024-12-09 23:59:51 +03:00
SMKRV 561bcf0b1d docs(Code of Conduct): Add Code of Conduct to promote community guidelines
- Implement Contributor Covenant Code of Conduct v1.4
- Establish clear expectations for community interactions
- Define standards of acceptable and unacceptable behavior
- Provide framework for reporting and addressing issues
- Emphasize inclusivity and respect for all contributors
2024-12-09 16:52:44 +03:00
SMKRV 2b1e42c665 docs(readme): Included note that the integration has been submitted to HACS store and is currently pending review in pull request: [pull request #2893](https://github.com/hacs/default/pull/2893). 2024-12-09 15:29:53 +03:00
SMKRV 2d68f29ab5 bump to version 2.0.8 2024-12-09 00:41:28 +03:00
SMKRV 19d4a93bca bump to version 2.0.8 2024-12-09 00:41:08 +03:00
SMKRV fb75c5f44e bump to version 2.0.9 2024-12-09 00:39:28 +03:00
SMKRV 52af987985 bump to version 2.0.9 2024-12-09 00:38:59 +03:00
SMKRV 162a30acdd bump to version 2.0.8-beta 2024-12-07 00:48:17 +03:00
SMKRV 898a6fc638 bump to version 2.0.8-beta 2024-12-07 00:43:53 +03:00
SMKRV 38e2362be4 bump to version 2.0.8-beta 2024-12-06 16:51:32 +03:00
SMKRV cea912d0b5 bump to version 2.0.8-beta 2024-12-06 16:51:09 +03:00
SMKRV 5ec00040c2 bump to version 2.0.8-beta 2024-12-06 16:50:26 +03:00
SMKRV 8d28fc4a0d bump to version 2.0.8-beta 2024-12-06 16:46:11 +03:00
SMKRV 7cc6587724 bump to version 2.0.8-beta 2024-12-06 16:35:26 +03:00
SMKRV bacf76e0a9 bump to version 2.0.8-beta 2024-12-06 16:33:46 +03:00
SMKRV f86c7bfd57 refactor(docs): relocate README images from misc/ to assets/ 2024-12-06 16:13:27 +03:00
SMKRV 2aaf340575 refactor(docs): relocate README images from misc/ to assets/ 2024-12-06 16:11:13 +03:00
SMKRV bae11ba85c refactor(docs): relocate README images from misc/ to assets/ 2024-12-06 16:10:04 +03:00
SMKRV 9eb7d8912c fix: sensor history attribute calculation 2024-12-06 12:26:56 +03:00
24 changed files with 413 additions and 220 deletions
+1
View File
@@ -38,3 +38,4 @@ Thumbs.db
*.psd *.psd
*.zip *.zip
*.txt *.txt
*.pdf
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
issue tracker.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+34 -9
View File
@@ -2,9 +2,11 @@
<div align="center"> <div align="center">
![GitHub release](https://img.shields.io/github/release/smkrv/ha-text-ai.svg?style=flat-square) ![GitHub last commit](https://img.shields.io/github/last-commit/smkrv/ha-text-ai.svg?style=flat-square) [![License: CC BY-NC-SA 4.0](https://img.shields.io/badge/License-CC%20BY--NC--SA%204.0-lightgrey.svg?style=flat-square)](https://creativecommons.org/licenses/by-nc-sa/4.0/) [![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=flat-square)](https://github.com/hacs/integration) ![/README.md](https://img.shields.io/badge/language-English-green?style=flat-square) ![/README_RU.md](https://img.shields.io/badge/language-Russian-green?style=flat-square) ![](https://img.shields.io/badge/language-Deutch-green?style=flat-square) ![GitHub release](https://img.shields.io/github/release/smkrv/ha-text-ai.svg?style=flat-square) ![GitHub last commit](https://img.shields.io/github/last-commit/smkrv/ha-text-ai.svg?style=flat-square) [![License: CC BY-NC-SA 4.0](https://img.shields.io/badge/License-CC%20BY--NC--SA%204.0-lightgrey.svg?style=flat-square)](https://creativecommons.org/licenses/by-nc-sa/4.0/) [![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=flat-square)](https://github.com/hacs/integration)
![Deutsch](https://img.shields.io/badge/de-Deutsch-blue?style=flat-square) ![English](https://img.shields.io/badge/en-English-blue?style=flat-square) ![Español](https://img.shields.io/badge/es-Español-blue?style=flat-square) ![हिन्दी](https://img.shields.io/badge/hi-हिन्दी-blue?style=flat-square) ![Italiano](https://img.shields.io/badge/it-Italiano-blue?style=flat-square) ![Русский](https://img.shields.io/badge/ru-Русский-blue?style=flat-square) ![Српски](https://img.shields.io/badge/sr-Српски-blue?style=flat-square) ![中文](https://img.shields.io/badge/zh-中文-blue?style=flat-square)
<img src="https://github.com/smkrv/ha-text-ai/blob/e03b5315c2cc7b489a6e1175da728075275ed614/misc/icons/logo.png" alt="HA Text AI" style="width: 80%; max-width: 640px; max-height: 150px; aspect-ratio: 2/1; object-fit: contain;"/>
<img src="https://github.com/smkrv/ha-text-ai/blob/15c717fcb0204bf4a0d4b4b4c6f0bb93e9f6c9a9/custom_components/ha_text_ai/icons/logo%402x.png" alt="HA Text AI" style="width: 50%; max-width: 256px; max-height: 128px; aspect-ratio: 2/1; object-fit: contain;"/>
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support ### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
</div> </div>
@@ -17,13 +19,11 @@ Transform your smart home experience with powerful AI assistance powered by mult
--- ---
> [!IMPORTANT] > [!IMPORTANT]
> 🚧 BETA VERSION
> Expect: potential bugs, frequent changes, incomplete features.
> 🤝 Community Driven > 🤝 Community Driven
> >
> <a href="https://community.home-assistant.io/t/ha-text-ai-transforming-home-automation-with-multi-provider-language-models/799741"><img src="https://img.shields.io/badge/Community-blue?style=for-the-badge&logo=homeassistant&logoColor=white&color=03a9f4"/></a> > <a href="https://community.home-assistant.io/t/ha-text-ai-transforming-home-automation-with-multi-provider-language-models/799741"><img src="https://img.shields.io/badge/Community-blue?style=for-the-badge&logo=homeassistant&logoColor=white&color=03a9f4"/></a>
> >
> [Screenshots](misc/screenshots/screenshot.jpg) > [Screenshots](assets/images/screenshots/screenshot.jpg)
## 🌟 Features ## 🌟 Features
@@ -89,13 +89,28 @@ Transform your smart home experience with powerful AI assistance powered by mult
</details> </details>
#### 🌐 Translations
| Code | Language | Status |
|------|----------|--------|
| 🇩🇪 de | Deutsch | Full |
| 🇬🇧 en | English | Primary |
| 🇪🇸 es | Español | Full |
| 🇮🇳 hi | हिन्दी | Full |
| 🇮🇹 it | Italiano | Full |
| 🇷🇺 ru | Русский | Full |
| 🇷🇸 sr | Српски | Full |
| 🇨🇳 zh | 中文 | Full |
## 📋 Prerequisites ## 📋 Prerequisites
- Home Assistant 2024.11 or later - Home Assistant 2024.11 or later
- 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/))
- DeepSeek 🆕 ([Get key](https://platform.deepseek.com/api_keys))
- OpenRouter ([Get key](https://openrouter.ai/keys)) - OpenRouter ([Get key](https://openrouter.ai/keys))
- Any OpenAI-compatible API provider
- Python 3.9 or newer - Python 3.9 or newer
- Stable internet connection - Stable internet connection
@@ -106,7 +121,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
- 🔑 **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)
- 📏 **Max Tokens**: Response length limit (token usage is estimated using a heuristic method based on word count and specific word characteristics, which may differ from actual token usage) - 📏 **Max Tokens**: Response length limit (passed directly to the LLM API to control the maximum length of the response)
- ⏱️ **Request Interval**: API call throttling - ⏱️ **Request Interval**: API call throttling
- 💾 **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
@@ -136,6 +151,7 @@ To be compatible, a provider should support:
- JSON request/response format - JSON request/response format
- Standard authentication method - Standard authentication method
- Similar model parameter handling - Similar model parameter handling
</details> </details>
## ⚡ Installation ## ⚡ Installation
@@ -151,6 +167,8 @@ To be compatible, a provider should support:
7. Click "Download" 7. Click "Download"
8. Restart Home Assistant 8. Restart Home Assistant
Note: Also Integration has been submitted to HACS store and is currently pending review in [pull request #2896](https://github.com/hacs/default/pull/2896).
### Manual Installation ### Manual Installation
1. Download the latest release 1. Download the latest release
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory 2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
@@ -238,12 +256,14 @@ data:
max_tokens: 500 # optional max_tokens: 500 # optional
context_messages: 10 #optional, number of previous messages to include in context, default: 5 context_messages: 10 #optional, number of previous messages to include in context, default: 5
system_prompt: "You are a sleep optimization expert" # optional system_prompt: "You are a sleep optimization expert" # optional
instance: sensor.ha_text_ai_gpt
``` ```
### set_system_prompt ### set_system_prompt
```yaml ```yaml
service: ha_text_ai.set_system_prompt service: ha_text_ai.set_system_prompt
data: data:
instance: sensor.ha_text_ai_gpt
prompt: | prompt: |
You are a home automation expert focused on: You are a home automation expert focused on:
1. Energy efficiency 1. Energy efficiency
@@ -255,6 +275,8 @@ data:
### clear_history ### clear_history
```yaml ```yaml
service: ha_text_ai.clear_history service: ha_text_ai.clear_history
data:
instance: sensor.ha_text_ai_gpt
``` ```
### get_history ### get_history
@@ -263,6 +285,7 @@ service: ha_text_ai.get_history
data: data:
limit: 5 # optional limit: 5 # optional
filter_model: "gpt-4o" # optional filter_model: "gpt-4o" # optional
instance: sensor.ha_text_ai_gpt
``` ```
### 🏷️ HA Text AI Sensor Naming Convention ### 🏷️ HA Text AI Sensor Naming Convention
@@ -299,6 +322,7 @@ automation:
- service: ha_text_ai.ask_question - service: ha_text_ai.ask_question
data: data:
question: "Home automation advice" question: "Home automation advice"
instance: sensor.ha_text_ai_gpt
- service: notify.mobile - service: notify.mobile
data: data:
message: > message: >
@@ -384,7 +408,7 @@ automation:
# Number of entries in current history file # Number of entries in current history file
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0 {{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
# Last few conversation entries (limited to 3 for performance) # Last few conversation entries (limited to 1 for performance)
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...] {{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
``` ```
@@ -507,10 +531,11 @@ If you want to say thanks financially, you can send a small token of appreciatio
--- ---
<div align="center"><img src="https://github.com/smkrv/ha-text-ai/blob/f2a41aaa2cd88adaf6929ba5f228205a315efdfa/custom_components/ha_text_ai/icons/dark_icon%402x.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div> <div align="center"><img src="https://github.com/smkrv/ha-text-ai/blob/2aaf3405759eb2d97624834594e24ace896131df/assets/images/icons/footer_icon.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div>
<div align="center"> <div align="center">
Made with ❤️ and Claude 3.5 Sonnet for the Home Assistant Community Made with ❤️ for the Home Assistant Community,
utilizing Claude 3.5 Sonnet, Gemini Pro 1.5, and Qwen 2.5 Coder 32B Instruct.
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues) [Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Before

Width:  |  Height:  |  Size: 618 KiB

After

Width:  |  Height:  |  Size: 618 KiB

Before

Width:  |  Height:  |  Size: 923 KiB

After

Width:  |  Height:  |  Size: 923 KiB

Before

Width:  |  Height:  |  Size: 339 KiB

After

Width:  |  Height:  |  Size: 339 KiB

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

+5
View File
@@ -39,11 +39,14 @@ from .const import (
CONF_CONTEXT_MESSAGES, CONF_CONTEXT_MESSAGES,
API_PROVIDER_OPENAI, API_PROVIDER_OPENAI,
API_PROVIDER_ANTHROPIC, API_PROVIDER_ANTHROPIC,
API_PROVIDER_DEEPSEEK,
DEFAULT_MODEL, DEFAULT_MODEL,
DEFAULT_DEEPSEEK_MODEL,
DEFAULT_TEMPERATURE, DEFAULT_TEMPERATURE,
DEFAULT_MAX_TOKENS, DEFAULT_MAX_TOKENS,
DEFAULT_OPENAI_ENDPOINT, DEFAULT_OPENAI_ENDPOINT,
DEFAULT_ANTHROPIC_ENDPOINT, DEFAULT_ANTHROPIC_ENDPOINT,
DEFAULT_DEEPSEEK_ENDPOINT,
DEFAULT_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL,
DEFAULT_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES,
API_TIMEOUT, API_TIMEOUT,
@@ -235,6 +238,8 @@ async def async_check_api(session, endpoint: str, headers: dict, provider: str)
try: try:
if provider == API_PROVIDER_ANTHROPIC: if provider == API_PROVIDER_ANTHROPIC:
check_url = f"{endpoint}/v1/models" check_url = f"{endpoint}/v1/models"
elif provider == API_PROVIDER_DEEPSEEK:
check_url = f"{endpoint}/models" # DeepSeek
else: # OpenAI else: # OpenAI
check_url = f"{endpoint}/models" check_url = f"{endpoint}/models"
+37 -5
View File
@@ -18,6 +18,8 @@ from .const import (
API_TIMEOUT, API_TIMEOUT,
API_RETRY_COUNT, API_RETRY_COUNT,
API_PROVIDER_ANTHROPIC, API_PROVIDER_ANTHROPIC,
API_PROVIDER_DEEPSEEK,
API_PROVIDER_OPENAI,
MIN_TEMPERATURE, MIN_TEMPERATURE,
MAX_TEMPERATURE, MAX_TEMPERATURE,
MIN_MAX_TOKENS, MIN_MAX_TOKENS,
@@ -109,19 +111,49 @@ class APIClient:
return await self._create_anthropic_completion( return await self._create_anthropic_completion(
model, messages, temperature, max_tokens model, messages, temperature, max_tokens
) )
elif self.api_provider == API_PROVIDER_DEEPSEEK:
return await self._create_deepseek_completion(
model, messages, temperature, max_tokens
)
else: else:
return await self._create_openai_completion( return await self._create_openai_completion(
model, messages, temperature, max_tokens model, messages, temperature, max_tokens
) )
except (KeyError, IndexError) as e:
if "'choices'" in str(e) or "'message'" in str(e):
raise HomeAssistantError("Failed to get a response from the AI model. Please check your internet connection and try again later.")
else:
raise
except Exception as e: except Exception as e:
_LOGGER.error("API request failed: %s", str(e)) _LOGGER.error("API request failed: %s", str(e))
raise HomeAssistantError(f"API request failed: {str(e)}") raise HomeAssistantError(f"API request failed: {str(e)}")
async def _create_deepseek_completion(
self,
model: str,
messages: List[Dict[str, str]],
temperature: float,
max_tokens: int,
) -> Dict[str, Any]:
"""Create completion using DeepSeek API."""
url = f"{self.endpoint}/chat/completions"
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"max_tokens": max_tokens,
"stream": False
}
data = await self._make_request(url, payload)
return {
"choices": [
{
"message": {"content": data["choices"][0]["message"]["content"]},
}
],
"usage": {
"prompt_tokens": data["usage"]["prompt_tokens"],
"completion_tokens": data["usage"]["completion_tokens"],
"total_tokens": data["usage"]["total_tokens"],
},
}
async def _create_openai_completion( async def _create_openai_completion(
self, self,
model: str, model: str,
+19 -11
View File
@@ -28,13 +28,16 @@ from .const import (
CONF_CONTEXT_MESSAGES, CONF_CONTEXT_MESSAGES,
API_PROVIDER_OPENAI, API_PROVIDER_OPENAI,
API_PROVIDER_ANTHROPIC, API_PROVIDER_ANTHROPIC,
API_PROVIDER_DEEPSEEK,
API_PROVIDERS, API_PROVIDERS,
DEFAULT_MODEL, DEFAULT_MODEL,
DEFAULT_DEEPSEEK_MODEL,
DEFAULT_TEMPERATURE, DEFAULT_TEMPERATURE,
DEFAULT_MAX_TOKENS, DEFAULT_MAX_TOKENS,
DEFAULT_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL,
DEFAULT_OPENAI_ENDPOINT, DEFAULT_OPENAI_ENDPOINT,
DEFAULT_ANTHROPIC_ENDPOINT, DEFAULT_ANTHROPIC_ENDPOINT,
DEFAULT_DEEPSEEK_ENDPOINT,
DEFAULT_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES,
MIN_TEMPERATURE, MIN_TEMPERATURE,
MAX_TEMPERATURE, MAX_TEMPERATURE,
@@ -90,17 +93,22 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self._errors = {} self._errors = {}
if user_input is None: if user_input is None:
default_endpoint = ( # Выбор endpoint по провайдеру
DEFAULT_OPENAI_ENDPOINT if self._provider == API_PROVIDER_OPENAI default_endpoint = {
else DEFAULT_ANTHROPIC_ENDPOINT API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
) API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
}.get(self._provider, DEFAULT_OPENAI_ENDPOINT)
# Выбор модели по умолчанию по провайдеру
default_model = DEFAULT_DEEPSEEK_MODEL if self._provider == API_PROVIDER_DEEPSEEK else DEFAULT_MODEL
return self.async_show_form( return self.async_show_form(
step_id="provider", step_id="provider",
data_schema=vol.Schema({ data_schema=vol.Schema({
vol.Required(CONF_NAME, default="my_assistant"): str, vol.Required(CONF_NAME, default="my_assistant"): str,
vol.Required(CONF_API_KEY): str, vol.Required(CONF_API_KEY): str,
vol.Required(CONF_MODEL, default=DEFAULT_MODEL): str, vol.Required(CONF_MODEL, default=default_model): str,
vol.Required(CONF_API_ENDPOINT, default=default_endpoint): str, vol.Required(CONF_API_ENDPOINT, default=default_endpoint): str,
vol.Optional(CONF_TEMPERATURE, default=DEFAULT_TEMPERATURE): vol.All( vol.Optional(CONF_TEMPERATURE, default=DEFAULT_TEMPERATURE): vol.All(
vol.Coerce(float), vol.Coerce(float),
@@ -156,15 +164,13 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
if not await self._async_validate_api(input_copy): if not await self._async_validate_api(input_copy):
return self.async_show_form( return self.async_show_form(
step_id="provider", step_id="provider",
data_schema=vol.Schema({ data_schema=vol.Schema({}),
}),
errors=self._errors errors=self._errors
) )
except Exception as e: except Exception as e:
return self.async_show_form( return self.async_show_form(
step_id="provider", step_id="provider",
data_schema=vol.Schema({ data_schema=vol.Schema({}),
}),
errors={"base": str(e)} errors={"base": str(e)}
) )
@@ -250,6 +256,8 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
unique_id = f"{DOMAIN}_{normalized_name}_{self._provider}".lower() unique_id = f"{DOMAIN}_{normalized_name}_{self._provider}".lower()
default_model = DEFAULT_DEEPSEEK_MODEL if self._provider == API_PROVIDER_DEEPSEEK else DEFAULT_MODEL
entry_data = { entry_data = {
CONF_API_PROVIDER: self._provider, CONF_API_PROVIDER: self._provider,
CONF_NAME: instance_name, CONF_NAME: instance_name,
@@ -257,7 +265,7 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
CONF_API_KEY: user_input.get(CONF_API_KEY), CONF_API_KEY: user_input.get(CONF_API_KEY),
CONF_API_ENDPOINT: user_input.get(CONF_API_ENDPOINT), CONF_API_ENDPOINT: user_input.get(CONF_API_ENDPOINT),
"unique_id": unique_id, "unique_id": unique_id,
CONF_MODEL: user_input.get(CONF_MODEL, DEFAULT_MODEL), CONF_MODEL: user_input.get(CONF_MODEL, default_model),
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),
@@ -302,7 +310,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
data_schema=vol.Schema({ data_schema=vol.Schema({
vol.Optional( vol.Optional(
CONF_MODEL, CONF_MODEL,
default=current_data.get(CONF_MODEL, DEFAULT_MODEL) default=current_data.get(CONF_MODEL, default_model)
): str, ): str,
vol.Optional( vol.Optional(
CONF_TEMPERATURE, CONF_TEMPERATURE,
+26 -2
View File
@@ -6,6 +6,8 @@ Constants for the HA text AI integration.
@github: https://github.com/smkrv/ha-text-ai @github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai @source: https://github.com/smkrv/ha-text-ai
""" """
import os
import json
from typing import Final from typing import Final
import voluptuous as vol import voluptuous as vol
from homeassistant.const import Platform, CONF_API_KEY, CONF_NAME from homeassistant.const import Platform, CONF_API_KEY, CONF_NAME
@@ -19,15 +21,34 @@ PLATFORMS: list[str] = ["sensor"]
CONF_API_PROVIDER: Final = "api_provider" CONF_API_PROVIDER: Final = "api_provider"
API_PROVIDER_OPENAI: Final = "openai" API_PROVIDER_OPENAI: Final = "openai"
API_PROVIDER_ANTHROPIC: Final = "anthropic" API_PROVIDER_ANTHROPIC: Final = "anthropic"
API_PROVIDER_DEEPSEEK: Final = "deepseek"
API_PROVIDERS: Final = [ API_PROVIDERS: Final = [
API_PROVIDER_OPENAI, API_PROVIDER_OPENAI,
API_PROVIDER_ANTHROPIC API_PROVIDER_ANTHROPIC,
API_PROVIDER_DEEPSEEK
] ]
# Read version from manifest.json
MANIFEST_PATH = os.path.join(os.path.dirname(__file__), "manifest.json")
try:
with open(MANIFEST_PATH) as manifest_file:
manifest = json.load(manifest_file)
VERSION = manifest.get("version", "unknown")
except FileNotFoundError:
VERSION = "unknown"
_LOGGER.warning("manifest.json not found at %s", MANIFEST_PATH)
except json.JSONDecodeError as err:
VERSION = "unknown"
_LOGGER.error("Error decoding JSON from manifest.json: %s", err)
except Exception as err:
VERSION = "unknown"
_LOGGER.error("Error reading manifest.json: %s", err)
# Default endpoints # Default endpoints
DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1" DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1"
DEFAULT_ANTHROPIC_ENDPOINT: Final = "https://api.anthropic.com" DEFAULT_ANTHROPIC_ENDPOINT: Final = "https://api.anthropic.com"
DEFAULT_DEEPSEEK_ENDPOINT: Final = "https://api.deepseek.com"
# Configuration constants # Configuration constants
CONF_MODEL: Final = "model" CONF_MODEL: Final = "model"
@@ -47,6 +68,7 @@ ICONS_SUBDOMAIN = "icons"
# Default values # Default values
DEFAULT_MODEL: Final = "gpt-4o-mini" DEFAULT_MODEL: Final = "gpt-4o-mini"
DEFAULT_DEEPSEEK_MODEL: Final = "deepseek-chat"
DEFAULT_TEMPERATURE: Final = 0.1 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
@@ -56,11 +78,13 @@ DEFAULT_NAME: Final = "HA Text AI"
DEFAULT_NAME_PREFIX = "ha_text_ai" DEFAULT_NAME_PREFIX = "ha_text_ai"
DEFAULT_CONTEXT_MESSAGES: Final = 5 DEFAULT_CONTEXT_MESSAGES: Final = 5
TRUNCATION_INDICATOR = " ... "
# Parameter constraints # Parameter constraints
MIN_TEMPERATURE: Final = 0.0 MIN_TEMPERATURE: Final = 0.0
MAX_TEMPERATURE: Final = 2.0 MAX_TEMPERATURE: Final = 2.0
MIN_MAX_TOKENS: Final = 1 MIN_MAX_TOKENS: Final = 1
MAX_MAX_TOKENS: Final = 4096 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
+81 -118
View File
@@ -41,6 +41,7 @@ from .const import (
ABSOLUTE_MAX_HISTORY_SIZE, ABSOLUTE_MAX_HISTORY_SIZE,
MAX_ATTRIBUTE_SIZE, MAX_ATTRIBUTE_SIZE,
MAX_HISTORY_FILE_SIZE, MAX_HISTORY_FILE_SIZE,
TRUNCATION_INDICATOR,
) )
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -173,7 +174,6 @@ class HATextAICoordinator(DataUpdateCoordinator):
self.available = True self.available = True
self._state = STATE_READY self._state = STATE_READY
self._conversation_history = [] # Full conversation history
self._start_time = dt_util.utcnow() self._start_time = dt_util.utcnow()
@@ -404,17 +404,32 @@ class HATextAICoordinator(DataUpdateCoordinator):
async def async_initialize_history_file(self) -> None: async def async_initialize_history_file(self) -> None:
""" """
Asynchronously initialize history file. Asynchronously initialize history file and load existing history.
""" """
try: try:
# Ensure directory exists first
await self._create_history_dir() await self._create_history_dir()
# Initialize file if await self._file_exists(self._history_file):
if not await self._file_exists(self._history_file): # Load existing history
async with AsyncFileHandler(self._history_file, 'r') as f:
content = await f.read()
if content:
history = json.loads(content)
# Validate and load history
if isinstance(history, list):
self._conversation_history = history[-self.max_history_size:]
_LOGGER.debug(
f"Loaded {len(self._conversation_history)} history entries "
f"for {self.instance_name}"
)
else:
# Create new history file
async with AsyncFileHandler(self._history_file, 'w') as f: async with AsyncFileHandler(self._history_file, 'w') as f:
await f.write(json.dumps([])) await f.write(json.dumps([]))
await self._check_history_size()
await self.async_update_ha_state()
_LOGGER.debug(f"History file initialized: {self._history_file}") _LOGGER.debug(f"History file initialized: {self._history_file}")
except Exception as e: except Exception as e:
@@ -504,6 +519,15 @@ class HATextAICoordinator(DataUpdateCoordinator):
_LOGGER.error(f"Error writing history entry: {e}") _LOGGER.error(f"Error writing history entry: {e}")
_LOGGER.debug(traceback.format_exc()) _LOGGER.debug(traceback.format_exc())
async def _check_history_size(self) -> None:
"""Verify and adjust history size if needed."""
if len(self._conversation_history) > self.max_history_size:
_LOGGER.warning(
f"History size ({len(self._conversation_history)}) exceeds "
f"maximum ({self.max_history_size}). Trimming..."
)
self._conversation_history = self._conversation_history[-self.max_history_size:]
async def _check_file_size(self, file_path: str) -> int: async def _check_file_size(self, file_path: str) -> int:
""" """
Check file size asynchronously. Check file size asynchronously.
@@ -624,15 +648,14 @@ class HATextAICoordinator(DataUpdateCoordinator):
async def _async_update_data(self) -> Dict[str, Any]: async def _async_update_data(self) -> Dict[str, Any]:
"""Update coordinator data with improved error handling and performance.""" """Update coordinator data with improved error handling and performance."""
try: try:
async with asyncio.Semaphore(1): async with asyncio.Semaphore(1):
current_state = self._get_current_state() current_state = self._get_current_state()
limited_history = await self._get_limited_history() # Get limited history with info
history_data = await self._get_limited_history()
metrics = await self._get_current_metrics() metrics = await self._get_current_metrics()
if metrics is None: if metrics is None:
metrics = {} metrics = {}
@@ -647,47 +670,68 @@ class HATextAICoordinator(DataUpdateCoordinator):
"uptime": self._calculate_uptime(), "uptime": self._calculate_uptime(),
"system_prompt": self._get_truncated_system_prompt(), "system_prompt": self._get_truncated_system_prompt(),
"history_size": len(self._conversation_history), "history_size": len(self._conversation_history),
"conversation_history": limited_history, "conversation_history": history_data["entries"],
"history_info": history_data["info"],
"normalized_name": self.normalized_name, "normalized_name": self.normalized_name,
} }
await self._validate_update_data(data) await self._validate_update_data(data)
return data return data
except asyncio.CancelledError:
_LOGGER.warning("Update was cancelled")
raise
except Exception as err: except Exception as err:
_LOGGER.error(f"Error updating data: {err}", exc_info=True) _LOGGER.error(f"Error updating data: {err}", exc_info=True)
return self._get_safe_initial_state() return self._get_safe_initial_state()
async def _get_limited_history(self) -> List[Dict[str, Any]]: async def _get_limited_history(self) -> Dict[str, Any]:
"""Get limited conversation history with size constraints.""" """Get limited conversation history showing only last Q&A."""
limited_history = [] limited_history = []
if self._conversation_history: if self._conversation_history:
for entry in self._conversation_history[-3:]: last_entry = self._conversation_history[-1]
limited_entry = { limited_entry = {
"timestamp": entry["timestamp"], "timestamp": last_entry["timestamp"],
"question": self._truncate_text(entry["question"]), "question": last_entry["question"][:4096] + (TRUNCATION_INDICATOR if len(last_entry["question"]) > 4096 else ""),
"response": self._truncate_text(entry["response"]), "response": last_entry["response"][:4096] + (TRUNCATION_INDICATOR if len(last_entry["response"]) > 4096 else ""),
} }
limited_history.append(limited_entry) limited_history.append(limited_entry)
return limited_history
history_info = {
"total_entries": len(self._conversation_history),
"displayed_entries": len(limited_history),
"full_history_available": True,
"history_path": self._history_file,
}
return {
"entries": limited_history,
"full_history": self._conversation_history,
"info": history_info
}
async def _get_sanitized_last_response(self) -> Dict[str, Any]:
"""Get sanitized version of last response with truncation indicators."""
response = self.last_response.copy()
if "response" in response:
original_response = response["response"]
is_response_truncated = len(original_response) > 4096
response["response"] = original_response[:4096] + (TRUNCATION_INDICATOR if is_response_truncated else "")
response["is_response_truncated"] = is_response_truncated
response["full_response_length"] = len(original_response)
if "question" in response:
original_question = response["question"]
is_question_truncated = len(original_question) > 4096
response["question"] = original_question[:4096] + (TRUNCATION_INDICATOR if is_question_truncated else "")
response["is_question_truncated"] = is_question_truncated
response["full_question_length"] = len(original_question)
return response
def _truncate_text(self, text: str, max_length: int = MAX_ATTRIBUTE_SIZE) -> str: def _truncate_text(self, text: str, max_length: int = MAX_ATTRIBUTE_SIZE) -> str:
"""Safely truncate text to maximum length.""" """Safely truncate text to maximum length."""
return text[:max_length] if text else "" return text[:max_length] if text else ""
async def _get_sanitized_last_response(self) -> Dict[str, Any]:
"""Get sanitized version of last response."""
response = self.last_response.copy()
if "response" in response:
response["response"] = self._truncate_text(response["response"])
if "question" in response:
response["question"] = self._truncate_text(response["question"])
return response
def _calculate_uptime(self) -> float: def _calculate_uptime(self) -> float:
"""Calculate current uptime in seconds.""" """Calculate current uptime in seconds."""
return (dt_util.utcnow() - self._start_time).total_seconds() return (dt_util.utcnow() - self._start_time).total_seconds()
@@ -752,46 +796,6 @@ class HATextAICoordinator(DataUpdateCoordinator):
"normalized_name": self.normalized_name, "normalized_name": self.normalized_name,
} }
def _calculate_context_tokens(self, messages: List[Dict[str, str]], model: Optional[str] = None) -> int:
total_tokens = 0
# Compile regular expressions for performance
number_pattern = re.compile(r'[0-9]')
special_char_pattern = re.compile(r'[^\w\s]')
whitespace_pattern = re.compile(r'\s+')
try:
for message in messages:
text = message.get('content', '')
if text:
# Normalize whitespace
text = whitespace_pattern.sub(' ', text.strip())
# Advanced token estimation heuristics
words = text.split()
for word in words:
# Complexity-based token calculation
if len(word) > 8: # Long words
total_tokens += 2
elif number_pattern.search(word): # Words with numbers
total_tokens += 1.5
elif special_char_pattern.search(word): # Words with special characters
total_tokens += 1.5
elif word.isupper(): # Acronyms and technical terms
total_tokens += 1.5
else: # Regular words
total_tokens += 1
# Additional correction for technical texts
total_tokens = math.ceil(total_tokens * 1.2)
return int(total_tokens)
except Exception as e:
_LOGGER.error(f"Token calculation error: {e}. Processed {len(messages)} messages.")
# Safe fallback with minimal token estimation
return len(messages) * 100
async def async_ask_question( async def async_ask_question(
self, self,
question: str, question: str,
@@ -832,9 +836,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
system_prompt: Optional[str] = None, system_prompt: Optional[str] = None,
context_messages: Optional[int] = None, context_messages: Optional[int] = None,
) -> dict: ) -> dict:
""" """Process question with context management."""
Enhanced question processing with intelligent token management.
"""
if self.client is None: if self.client is None:
raise HomeAssistantError("AI client not initialized") raise HomeAssistantError("AI client not initialized")
@@ -856,62 +858,23 @@ class HATextAICoordinator(DataUpdateCoordinator):
if temp_system_prompt: if temp_system_prompt:
messages.append({"role": "system", "content": temp_system_prompt}) messages.append({"role": "system", "content": temp_system_prompt})
# Context history management # Add context from history
context_history = self._conversation_history[-temp_context_messages:] context_history = self._conversation_history[-temp_context_messages:]
# Comprehensive token calculation
context_tokens = self._calculate_context_tokens(
[{"content": entry["question"]} for entry in context_history] +
[{"content": entry["response"]} for entry in context_history] +
[{"content": question}],
temp_model
)
# Dynamic token allocation
available_tokens = max(0, temp_max_tokens - context_tokens)
# Context trimming if over token limit
if context_tokens > temp_max_tokens:
_LOGGER.warning(
f"Token limit exceeded. "
f"Context: {context_tokens}, "
f"Max: {temp_max_tokens}"
)
# Intelligent context reduction
while context_tokens > temp_max_tokens // 2 and context_history:
context_history.pop(0)
context_tokens = self._calculate_context_tokens(
[{"content": entry["question"]} for entry in context_history] +
[{"content": entry["response"]} for entry in context_history] +
[{"content": question}],
temp_model
)
# Rebuild messages with trimmed context
for entry in context_history: for entry in context_history:
messages.append({"role": "user", "content": entry["question"]}) messages.append({"role": "user", "content": entry["question"]})
messages.append({"role": "assistant", "content": entry["response"]}) messages.append({"role": "assistant", "content": entry["response"]})
# Add current question
messages.append({"role": "user", "content": question}) messages.append({"role": "user", "content": question})
# Detailed token logging # Process message
_LOGGER.debug(
f"Token Analysis: "
f"Context Tokens: {context_tokens}, "
f"Max Tokens: {temp_max_tokens}, "
f"Available Tokens: {available_tokens}"
)
# Prepare API call with dynamic token management
kwargs = { kwargs = {
"model": temp_model, "model": temp_model,
"temperature": temp_temperature, "temperature": temp_temperature,
"max_tokens": min(temp_max_tokens, available_tokens), "max_tokens": temp_max_tokens,
"messages": messages, "messages": messages,
} }
# Process message
response = await self.async_process_message(question, **kwargs) response = await self.async_process_message(question, **kwargs)
# Update metrics # Update metrics
+1 -1
View File
@@ -23,6 +23,6 @@
"single_config_entry": false, "single_config_entry": false,
"ssdp": [], "ssdp": [],
"usb": [], "usb": [],
"version": "2.0.7-beta", "version": "2.1.1",
"zeroconf": [] "zeroconf": []
} }
+2 -1
View File
@@ -68,6 +68,7 @@ from .const import (
DEFAULT_NAME_PREFIX, DEFAULT_NAME_PREFIX,
CONF_MAX_HISTORY_SIZE, CONF_MAX_HISTORY_SIZE,
MAX_ATTRIBUTE_SIZE, MAX_ATTRIBUTE_SIZE,
VERSION,
) )
from .coordinator import HATextAICoordinator from .coordinator import HATextAICoordinator
@@ -154,7 +155,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
name=self._attr_name, name=self._attr_name,
manufacturer="Community", manufacturer="Community",
model=f"{model} ({api_provider} provider)", model=f"{model} ({api_provider} provider)",
sw_version="1.0.0", sw_version=VERSION,
) )
_LOGGER.debug( _LOGGER.debug(
@@ -19,7 +19,7 @@
"model": "Zu verwendendes AI-Modell", "model": "Zu verwendendes AI-Modell",
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)", "api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
"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-4096 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)",
"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)"
@@ -33,7 +33,7 @@
"api_key": "API-Schlüssel zur Authentifizierung", "api_key": "API-Schlüssel zur Authentifizierung",
"model": "Zu verwendendes AI-Modell", "model": "Zu verwendendes AI-Modell",
"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-4096 Token)", "max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
"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)",
@@ -77,7 +77,7 @@
"data": { "data": {
"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-4096)", "max_tokens": "Maximale Länge der Antwort (1-100000)",
"request_interval": "Minimale Anfrageintervall (0,1-60 Sekunden)", "request_interval": "Minimale Anfrageintervall (0,1-60 Sekunden)",
"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)"
@@ -89,7 +89,8 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI (kompatibel)", "openai": "OpenAI (kompatibel)",
"anthropic": "Anthropic (kompatibel)" "anthropic": "Anthropic (kompatibel)",
"deepseek": "DeepSeek"
} }
} }
}, },
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "Max Tokens", "name": "Max Tokens",
"description": "Maximale Länge der Antwort (1-4096 Token)" "description": "Maximale Länge der Antwort (1-100000 Token)"
} }
} }
}, },
@@ -19,7 +19,7 @@
"model": "AI model to use", "model": "AI model to use",
"api_endpoint": "Custom API endpoint URL (optional)", "api_endpoint": "Custom API endpoint URL (optional)",
"temperature": "Response creativity (0-2, lower = more focused)", "temperature": "Response creativity (0-2, lower = more focused)",
"max_tokens": "Maximum response length (1-4096 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)",
"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)"
@@ -33,7 +33,7 @@
"api_key": "API key for authentication", "api_key": "API key for authentication",
"model": "AI model to use", "model": "AI model to use",
"temperature": "Response creativity (0-2, lower = more focused)", "temperature": "Response creativity (0-2, lower = more focused)",
"max_tokens": "Maximum response length (1-4096 tokens)", "max_tokens": "Maximum response length (1-100000 tokens)",
"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)",
@@ -77,7 +77,7 @@
"data": { "data": {
"model": "AI model", "model": "AI model",
"temperature": "Response creativity (0-2)", "temperature": "Response creativity (0-2)",
"max_tokens": "Maximum response length (1-4096)", "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)",
"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)"
@@ -89,7 +89,8 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI (compatible)", "openai": "OpenAI (compatible)",
"anthropic": "Anthropic (compatible)" "anthropic": "Anthropic (compatible)",
"deepseek": "DeepSeek"
} }
} }
}, },
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "Max Tokens", "name": "Max Tokens",
"description": "Maximum length of the response (1-4096 tokens)" "description": "Maximum length of the response (1-100000 tokens)"
} }
} }
}, },
@@ -19,7 +19,7 @@
"model": "Modelo de IA a utilizar", "model": "Modelo de IA a utilizar",
"api_endpoint": "URL del endpoint de API personalizado (opcional)", "api_endpoint": "URL del endpoint de API personalizado (opcional)",
"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-4096 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)",
"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)"
@@ -33,7 +33,7 @@
"api_key": "Clave API para autenticación", "api_key": "Clave API para autenticación",
"model": "Modelo de IA a utilizar", "model": "Modelo de IA a utilizar",
"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-4096 tokens)", "max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
"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)",
@@ -77,7 +77,7 @@
"data": { "data": {
"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-4096)", "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)",
"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)"
@@ -89,13 +89,14 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI (compatible)", "openai": "OpenAI (compatible)",
"anthropic": "Anthropic (compatible)" "anthropic": "Anthropic (compatible)",
"deepseek": "DeepSeek"
} }
} }
}, },
"services": { "services": {
"ask_question": { "ask_question": {
"name": "Hacer Pregunta (IA de Texto de HA)", "name": "Hacer Pregunta (HA Text AI)",
"description": "Envía una pregunta al modelo de IA y recibe una respuesta detallada. La respuesta se almacenará en el historial de conversación y se podrá recuperar más tarde.", "description": "Envía una pregunta al modelo de IA y recibe una respuesta detallada. La respuesta se almacenará en el historial de conversación y se podrá recuperar más tarde.",
"fields": { "fields": {
"instance": { "instance": {
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "Máx. Tokens", "name": "Máx. Tokens",
"description": "Longitud máxima de la respuesta (1-4096 tokens)" "description": "Longitud máxima de la respuesta (1-100000 tokens)"
} }
} }
}, },
@@ -19,7 +19,7 @@
"model": "उपयोग करने के लिए एआई मॉडल", "model": "उपयोग करने के लिए एआई मॉडल",
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)", "api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)", "temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-4096 टोकन)", "max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)", "request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)", "context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)" "max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
@@ -33,7 +33,7 @@
"api_key": "प्रमाणीकरण के लिए एपीआई कुंजी", "api_key": "प्रमाणीकरण के लिए एपीआई कुंजी",
"model": "उपयोग करने के लिए एआई मॉडल", "model": "उपयोग करने के लिए एआई मॉडल",
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)", "temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-4096 टोकन)", "max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)", "api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
"api_provider": "एपीआई प्रदाता", "api_provider": "एपीआई प्रदाता",
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)", "request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
@@ -77,7 +77,7 @@
"data": { "data": {
"model": "एआई मॉडल", "model": "एआई मॉडल",
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)", "temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-4096)", "max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)", "request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)", "context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)" "max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
@@ -89,13 +89,14 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI (अनुकूलित)", "openai": "OpenAI (अनुकूलित)",
"anthropic": "Anthropic (अनुकूलित)" "anthropic": "Anthropic (अनुकूलित)",
"deepseek": "DeepSeek"
} }
} }
}, },
"services": { "services": {
"ask_question": { "ask_question": {
"name": "प्रश्न पूछें (एचए टेक्स्ट एआई)", "name": "प्रश्न पूछें (HA Text AI)",
"description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।", "description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
"fields": { "fields": {
"instance": { "instance": {
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "अधिकतम टोकन", "name": "अधिकतम टोकन",
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-4096 टोकन)" "description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
} }
} }
}, },
@@ -19,7 +19,7 @@
"model": "Modello AI da utilizzare", "model": "Modello AI da utilizzare",
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)", "api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
"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-4096 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)",
"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)"
@@ -33,7 +33,7 @@
"api_key": "Chiave API per l'autenticazione", "api_key": "Chiave API per l'autenticazione",
"model": "Modello AI da utilizzare", "model": "Modello AI da utilizzare",
"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-4096 token)", "max_tokens": "Lunghezza massima della risposta (1-100000 token)",
"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)",
@@ -77,7 +77,7 @@
"data": { "data": {
"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-4096)", "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)",
"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)"
@@ -89,7 +89,8 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI (compatibile)", "openai": "OpenAI (compatibile)",
"anthropic": "Anthropic (compatibile)" "anthropic": "Anthropic (compatibile)",
"deepseek": "DeepSeek"
} }
} }
}, },
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "Token massimi", "name": "Token massimi",
"description": "Lunghezza massima della risposta (1-4096 token)" "description": "Lunghezza massima della risposta (1-100000 token)"
} }
} }
}, },
@@ -19,7 +19,7 @@
"model": "Модель ИИ для использования", "model": "Модель ИИ для использования",
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)", "api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)", "temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
"max_tokens": "Максимальная длина ответа (1-4096 токенов)", "max_tokens": "Максимальная длина ответа (1-100000 токенов)",
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)", "request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)", "context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
"max_history_size": "Максимальный размер истории разговора (1-100)" "max_history_size": "Максимальный размер истории разговора (1-100)"
@@ -33,7 +33,7 @@
"api_key": "API-ключ для аутентификации", "api_key": "API-ключ для аутентификации",
"model": "Модель ИИ для использования", "model": "Модель ИИ для использования",
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)", "temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
"max_tokens": "Максимальная длина ответа (1-4096 токенов)", "max_tokens": "Максимальная длина ответа (1-100000 токенов)",
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)", "api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
"api_provider": "Провайдер API", "api_provider": "Провайдер API",
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)", "request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
@@ -77,7 +77,7 @@
"data": { "data": {
"model": "Модель ИИ", "model": "Модель ИИ",
"temperature": "Креативность ответа (0-2)", "temperature": "Креативность ответа (0-2)",
"max_tokens": "Максимальная длина ответа (1-4096)", "max_tokens": "Максимальная длина ответа (1-100000)",
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)", "request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)", "context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
"max_history_size": "Максимальный размер истории разговора (1-100)" "max_history_size": "Максимальный размер истории разговора (1-100)"
@@ -89,13 +89,14 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI (совместимый)", "openai": "OpenAI (совместимый)",
"anthropic": "Anthropic (совместимый)" "anthropic": "Anthropic (совместимый)",
"deepseek": "DeepSeek"
} }
} }
}, },
"services": { "services": {
"ask_question": { "ask_question": {
"name": "Задать вопрос (Текстовый ИИ HA)", "name": "Задать вопрос (HA Text AI)",
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.", "description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.",
"fields": { "fields": {
"instance": { "instance": {
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "Максимум токенов", "name": "Максимум токенов",
"description": "Максимальная длина ответа (1-4096 токенов)" "description": "Максимальная длина ответа (1-100000 токенов)"
} }
} }
}, },
@@ -19,7 +19,7 @@
"model": "AI модел који ће се користити", "model": "AI модел који ће се користити",
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)", "api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
"temperature": "Креативност одговора (0-2, нижа = фокусираније)", "temperature": "Креативност одговора (0-2, нижа = фокусираније)",
"max_tokens": "Максимална дужина одговора (1-4096 токена)", "max_tokens": "Максимална дужина одговора (1-100000 токена)",
"request_interval": "Минимално време између захтева (0.1-60 секунди)", "request_interval": "Минимално време између захтева (0.1-60 секунди)",
"context_messages": "Број контекстуалних порука које треба задржати (1-20)", "context_messages": "Број контекстуалних порука које треба задржати (1-20)",
"max_history_size": "Максимална величина историје разговора (1-100)" "max_history_size": "Максимална величина историје разговора (1-100)"
@@ -33,7 +33,7 @@
"api_key": "API кључ за аутентификацију", "api_key": "API кључ за аутентификацију",
"model": "AI модел који ће се користити", "model": "AI модел који ће се користити",
"temperature": "Креативност одговора (0-2, нижа = фокусираније)", "temperature": "Креативност одговора (0-2, нижа = фокусираније)",
"max_tokens": "Максимална дужина одговора (1-4096 токена)", "max_tokens": "Максимална дужина одговора (1-100000 токена)",
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)", "api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
"api_provider": "API провајдер", "api_provider": "API провајдер",
"request_interval": "Минимално време између захтева (0.1-60 секунди)", "request_interval": "Минимално време између захтева (0.1-60 секунди)",
@@ -77,7 +77,7 @@
"data": { "data": {
"model": "AI модел", "model": "AI модел",
"temperature": "Креативност одговора (0-2)", "temperature": "Креативност одговора (0-2)",
"max_tokens": "Максимална дужина одговора (1-4096)", "max_tokens": "Максимална дужина одговора (1-100000)",
"request_interval": "Минимално време између захтева (0.1-60 секунди)", "request_interval": "Минимално време између захтева (0.1-60 секунди)",
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)", "context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
"max_history_size": "Максимална величина историје разговора (1-100)" "max_history_size": "Максимална величина историје разговора (1-100)"
@@ -89,7 +89,8 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI (компатибилан)", "openai": "OpenAI (компатибилан)",
"anthropic": "Anthropic (компатибилан)" "anthropic": "Anthropic (компатибилан)",
"deepseek": "DeepSeek"
} }
} }
}, },
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "Максимални токени", "name": "Максимални токени",
"description": "Максимална дужина одговора (1-4096 токена)" "description": "Максимална дужина одговора (1-100000 токена)"
} }
} }
}, },
@@ -19,7 +19,7 @@
"model": "要使用的AI模型", "model": "要使用的AI模型",
"api_endpoint": "自定义API端点URL(可选)", "api_endpoint": "自定义API端点URL(可选)",
"temperature": "响应创造力(0-2,越低越专注)", "temperature": "响应创造力(0-2,越低越专注)",
"max_tokens": "最大响应长度(1-4096个标记)", "max_tokens": "最大响应长度(1-100000个标记)",
"request_interval": "请求之间的最小时间(0.1-60秒)", "request_interval": "请求之间的最小时间(0.1-60秒)",
"context_messages": "保留的上下文消息数量(1-20", "context_messages": "保留的上下文消息数量(1-20",
"max_history_size": "最大对话历史大小(1-100" "max_history_size": "最大对话历史大小(1-100"
@@ -33,7 +33,7 @@
"api_key": "用于身份验证的API密钥", "api_key": "用于身份验证的API密钥",
"model": "要使用的AI模型", "model": "要使用的AI模型",
"temperature": "响应创造力(0-2,越低越专注)", "temperature": "响应创造力(0-2,越低越专注)",
"max_tokens": "最大响应长度(1-4096个标记)", "max_tokens": "最大响应长度(1-100000个标记)",
"api_endpoint": "自定义API端点URL(可选)", "api_endpoint": "自定义API端点URL(可选)",
"api_provider": "API提供者", "api_provider": "API提供者",
"request_interval": "请求之间的最小时间(0.1-60秒)", "request_interval": "请求之间的最小时间(0.1-60秒)",
@@ -77,7 +77,7 @@
"data": { "data": {
"model": "AI模型", "model": "AI模型",
"temperature": "响应创造力(0-2", "temperature": "响应创造力(0-2",
"max_tokens": "最大响应长度(1-4096", "max_tokens": "最大响应长度(1-100000",
"request_interval": "最小请求间隔(0.1-60秒)", "request_interval": "最小请求间隔(0.1-60秒)",
"context_messages": "要包含在上下文中的先前消息数量(1-20)", "context_messages": "要包含在上下文中的先前消息数量(1-20)",
"max_history_size": "最大对话历史大小(1-100" "max_history_size": "最大对话历史大小(1-100"
@@ -89,13 +89,14 @@
"api_provider": { "api_provider": {
"options": { "options": {
"openai": "OpenAI(兼容)", "openai": "OpenAI(兼容)",
"anthropic": "Anthropic(兼容)" "anthropic": "Anthropic(兼容)",
"deepseek": "DeepSeek "
} }
} }
}, },
"services": { "services": {
"ask_question": { "ask_question": {
"name": "提问HA文本AI", "name": "提问 (HA Text AI)",
"description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。", "description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。",
"fields": { "fields": {
"instance": { "instance": {
@@ -124,7 +125,7 @@
}, },
"max_tokens": { "max_tokens": {
"name": "最大标记数", "name": "最大标记数",
"description": "响应的最大长度(1-4096个标记)" "description": "响应的最大长度(1-100000个标记)"
} }
} }
}, },
+27 -29
View File
@@ -1,32 +1,30 @@
``` ```
ha-text-ai/ ha_text_ai/
├── custom_components ├── __init__.py
│   └── ha_text_ai ├── api_client.py
│   ├── __init__.py ├── config_flow.py
│   ├── api_client.py ├── const.py
│   ├── config_flow.py ├── coordinator.py
│   ├── const.py ├── icons
│   ├── coordinator.py │   ├── dark_icon.png
│   ├── icons │   ├── dark_icon@2x.png
│   │   ├── dark_icon.png │   ├── dark_logo.png
│   │   ├── dark_icon@2x.png │   ├── dark_logo@2x.png
│   │   ├── dark_logo.png │   ├── icon.png
│   │   ├── dark_logo@2x.png │   ├── icon@2x.png
│   │   ├── icon.png │   ├── logo.png
│   │   ├── icon@2x.png │   └── logo@2x.png
│   │   ├── logo.png ├── manifest.json
│   │   └── logo@2x.png ├── sensor.py
│   ├── manifest.json ├── services.yaml
│   ├── sensor.py └── translations
│   ├── services.yaml ├── de.json
│   ── translations ── en.json
│   ├── de.json ├── es.json
│   ├── en.json ├── hi.json
│   ├── es.json ├── it.json
│   ├── hi.json ├── ru.json
│   ├── it.json ├── sr.json
│   ── ru.json ── zh.json
│   ├── sr.json
│   └── zh.json
``` ```