mirror of
https://github.com/smkrv/ha-text-ai.git
synced 2026-07-22 07:03:58 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be06fddce1 | ||
|
|
5f0bd861a7 | ||
|
|
428aee46c8 | ||
|
|
561bcf0b1d | ||
|
|
2b1e42c665 |
@@ -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.
|
||||
@@ -32,7 +32,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
||||
- 🎯 **Advanced Customization**: Per-request model and parameter selection
|
||||
- 🔒 **Enhanced Security**: Secure API key management and usage monitoring
|
||||
- 🎨 **Improved User Experience**: Intuitive configuration and rich interfaces
|
||||
- 🔄 **Automation Integration**: Event-driven responses and template compatibility
|
||||
- 🔄 **Automation Integration**: Event-driven responses and template compatibility
|
||||
|
||||
<details>
|
||||
<summary>📦 Detailed Feature Breakdown</summary>
|
||||
@@ -164,6 +164,8 @@ To be compatible, a provider should support:
|
||||
7. Click "Download"
|
||||
8. Restart Home Assistant
|
||||
|
||||
Note: Also Integration has been submitted to HACS store and is currently pending review in [pull request #2896](https://github.com/hacs/default/pull/2896).
|
||||
|
||||
### Manual Installation
|
||||
1. Download the latest release
|
||||
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
||||
|
||||
@@ -56,6 +56,8 @@ DEFAULT_NAME: Final = "HA Text AI"
|
||||
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
||||
|
||||
TRUNCATION_INDICATOR = " … "
|
||||
|
||||
# Parameter constraints
|
||||
MIN_TEMPERATURE: Final = 0.0
|
||||
MAX_TEMPERATURE: Final = 2.0
|
||||
|
||||
@@ -41,6 +41,7 @@ from .const import (
|
||||
ABSOLUTE_MAX_HISTORY_SIZE,
|
||||
MAX_ATTRIBUTE_SIZE,
|
||||
MAX_HISTORY_FILE_SIZE,
|
||||
TRUNCATION_INDICATOR,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -647,15 +648,14 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
|
||||
async def _async_update_data(self) -> Dict[str, Any]:
|
||||
"""Update coordinator data with improved error handling and performance."""
|
||||
|
||||
try:
|
||||
async with asyncio.Semaphore(1):
|
||||
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()
|
||||
|
||||
if metrics is None:
|
||||
metrics = {}
|
||||
|
||||
@@ -670,47 +670,68 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
"uptime": self._calculate_uptime(),
|
||||
"system_prompt": self._get_truncated_system_prompt(),
|
||||
"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,
|
||||
}
|
||||
|
||||
await self._validate_update_data(data)
|
||||
|
||||
return data
|
||||
|
||||
except asyncio.CancelledError:
|
||||
_LOGGER.warning("Update was cancelled")
|
||||
raise
|
||||
except Exception as err:
|
||||
_LOGGER.error(f"Error updating data: {err}", exc_info=True)
|
||||
return self._get_safe_initial_state()
|
||||
|
||||
async def _get_limited_history(self) -> List[Dict[str, Any]]:
|
||||
"""Get limited conversation history with size constraints."""
|
||||
async def _get_limited_history(self) -> Dict[str, Any]:
|
||||
"""Get limited conversation history showing only last Q&A."""
|
||||
limited_history = []
|
||||
|
||||
if self._conversation_history:
|
||||
for entry in self._conversation_history[-3:]:
|
||||
limited_entry = {
|
||||
"timestamp": entry["timestamp"],
|
||||
"question": self._truncate_text(entry["question"]),
|
||||
"response": self._truncate_text(entry["response"]),
|
||||
}
|
||||
limited_history.append(limited_entry)
|
||||
return limited_history
|
||||
last_entry = self._conversation_history[-1]
|
||||
limited_entry = {
|
||||
"timestamp": last_entry["timestamp"],
|
||||
"question": last_entry["question"][:4096] + (TRUNCATION_INDICATOR if len(last_entry["question"]) > 4096 else ""),
|
||||
"response": last_entry["response"][:4096] + (TRUNCATION_INDICATOR if len(last_entry["response"]) > 4096 else ""),
|
||||
}
|
||||
limited_history.append(limited_entry)
|
||||
|
||||
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:
|
||||
"""Safely truncate text to maximum length."""
|
||||
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:
|
||||
"""Calculate current uptime in seconds."""
|
||||
return (dt_util.utcnow() - self._start_time).total_seconds()
|
||||
|
||||
Reference in New Issue
Block a user