Compare commits

...
78 Commits
Author SHA1 Message Date
SMKRV f397bbffe7 Release 2.0.5-beta 2024-12-03 18:29:24 +03:00
SMKRV 5709bce1ae docs(license): Switch to CC BY-NC-SA 4.0 2024-11-29 17:13:08 +03:00
SMKRV d549a36c3a docs(license): Switch to CC BY-NC-SA 4.0 2024-11-29 17:11:06 +03:00
SMKRV e9ba480e95 docs: Update to beta 2024-11-29 16:57:32 +03:00
SMKRV 8ac7154399 docs: Update to beta 2024-11-29 16:54:41 +03:00
SMKRV f25f2db885 Release v2.0.4-beta 2024-11-29 16:45:43 +03:00
SMKRV 621732ae0a feat(localization): Expand multilingual support
- Added translations for:
  * Chinese (zh)
  * Serbian (sr)
  * Italian (it)
  * Hindi (hi)
  * Spanish (es)

- Fixed minor bugs
- Improved language coverage
2024-11-29 16:44:21 +03:00
SMKRV ed85c659be docs(license): Switch to CC BY-NC-SA 4.0 2024-11-29 16:38:41 +03:00
SMKRV f6dcd1c382 docs(license): Switch to CC BY-NC-SA 4.0 2024-11-29 16:27:11 +03:00
SMKRV 37c572fd98 docs(license): Switch to CC BY-NC-SA 4.0 2024-11-29 16:27:04 +03:00
SMKRV 1ff709d05c docs: screenshots 2024-11-29 01:27:01 +03:00
SMKRV 83726feae1 Screenshots added 2024-11-29 01:24:57 +03:00
SMKRV f24c87cc51 Screenshots 2024-11-29 01:23:43 +03:00
SMKRV 1c40968a94 misc 2024-11-29 00:57:39 +03:00
SMKRV c37ec7c1dd Release v2.0.3-beta 2024-11-29 00:54:18 +03:00
SMKRV ff3e600302 Misc 2024-11-29 00:21:21 +03:00
SMKRV 3d064f5b9d Release v2.0.3-beta 2024-11-29 00:15:27 +03:00
SMKRV ae8f8bda03 Release v2.0.2-beta 2024-11-29 00:01:27 +03:00
SMKRV 2dbae19c41 Release v2.0.2-beta 2024-11-28 23:59:02 +03:00
SMKRV d3ef31f551 Release v2.0.2-beta 2024-11-28 23:27:39 +03:00
SMKRV ff0c0369e8 YAML configuration explained 2024-11-27 18:03:30 +03:00
SMKRV b0dafe081b YAML configuration explained 2024-11-27 16:58:00 +03:00
SMKRV a88b5d01c1 Vesion updated 2024-11-27 16:52:49 +03:00
SMKRV e7d5e62671 YAML configuration explained 2024-11-27 16:43:20 +03:00
SMKRV 5f41b9489d YAML configuration explained 2024-11-27 16:34:55 +03:00
SMKRV 958e241e0e YAML configuration explained 2024-11-27 16:30:58 +03:00
smkrvandGitHub 4b3efc0b6f Update README_RU.md 2024-11-27 01:36:11 +03:00
smkrvandGitHub 1592fc2371 Delete socia_logo.png 2024-11-26 23:50:38 +03:00
smkrvandGitHub d5a6613428 Update README.md 2024-11-26 18:00:45 +03:00
SMKRV 9324473c9e Banner chaged 2024-11-26 17:49:08 +03:00
SMKRV 456e797cca Banner changed 2024-11-26 17:47:49 +03:00
SMKRV f960b9f9b4 Misc 2024-11-26 17:47:17 +03:00
SMKRV 8449b73423 Banner changed 2024-11-26 17:46:51 +03:00
SMKRV f19ba9aac9 Banner changed 2024-11-26 17:45:59 +03:00
SMKRV 524849f6a9 Logo 2024-11-26 17:44:13 +03:00
SMKRV 0a64a9abe0 Misc 2024-11-26 16:52:35 +03:00
SMKRV adb4127f5a Markdown changes 2024-11-26 16:38:56 +03:00
SMKRV f463593180 Markdown changes 2024-11-26 16:35:49 +03:00
SMKRV e53f257977 Markdown changes 2024-11-26 16:31:44 +03:00
SMKRV 87199e856a markdown changes 2024-11-26 16:27:50 +03:00
SMKRV bcf7cfbf76 Markdown changes 2024-11-26 16:25:22 +03:00
SMKRV 9289e1388f Markdown changes 2024-11-26 16:23:35 +03:00
SMKRV 84db9b7bb8 Markdown changes 2024-11-26 16:22:39 +03:00
SMKRV bd1098a181 Markdown changes 2024-11-26 16:22:27 +03:00
SMKRV 6fd3db0063 Markdown changes 2024-11-26 16:21:56 +03:00
SMKRV bf52217cd5 Markdown changes 2024-11-26 16:21:45 +03:00
SMKRV b0cf5b3c61 Markdown changes 2024-11-26 16:21:22 +03:00
SMKRV 347c1675ca Markdown changes 2024-11-26 16:20:07 +03:00
SMKRV 961ae2d34f Markdown changes 2024-11-26 16:19:45 +03:00
SMKRV 14827c3adc Markdown changes 2024-11-26 15:45:19 +03:00
SMKRV 4a88453abc Markdown changes 2024-11-26 15:44:47 +03:00
SMKRV bc33d38f5e Markdown changes 2024-11-26 15:42:52 +03:00
SMKRV 657a5ede86 Markdown changes 2024-11-26 15:41:46 +03:00
SMKRV dd046fe3e8 Markdown changes 2024-11-26 15:40:02 +03:00
SMKRV 7391dbf5b1 Markdown changes 2024-11-26 15:37:06 +03:00
SMKRV a0ccb86bd4 Markdown changes 2024-11-26 15:36:06 +03:00
SMKRV c0eb5b165d Vesrion changed 2024-11-26 15:31:34 +03:00
SMKRV 9812babc7e Русский перевод README 2024-11-26 15:31:06 +03:00
SMKRV c61c4570b0 Русский перевод README 2024-11-26 15:30:07 +03:00
SMKRV d618feffff docs(readme): Enhance attribute descriptions with detailed English comments
- Add comprehensive explanations for HA Text AI sensor attributes
- Improve readability of README.md documentation
- Provide context and usage details for each sensor attribute
- Translate comments to English with technical clarity

Changes include:
* Detailed descriptions for Model and Provider Information
* Expanded System Status attribute explanations
* Clarified Performance Metrics comments
* Added context for Conversation and Token Usage
* Improved Last Interaction Details descriptions
* Enhanced System Health attribute documentation
2024-11-26 15:01:40 +03:00
SMKRV 0fdc3c93d3 Release v2.0.0-alpha 2024-11-26 14:02:37 +03:00
SMKRV d6e76f7805 Validate HACS 2024-11-26 13:16:10 +03:00
SMKRV b05afe1085 Release v2.0.0-alpha 2024-11-26 02:08:55 +03:00
SMKRV 2a4911f5f8 Release v2.0.0-alpha 2024-11-26 02:04:23 +03:00
SMKRV 208074d845 Release v2.0.0-alpha 2024-11-26 01:20:08 +03:00
SMKRV 616ff2c3fe 💡 Support the Project 2024-11-26 00:14:26 +03:00
SMKRV 987c939956 Support the Project 2024-11-26 00:12:43 +03:00
SMKRV 1615cc744e Support the Project 2024-11-26 00:12:10 +03:00
SMKRV 2d793a4b25 Support the Project 2024-11-26 00:11:55 +03:00
SMKRV aeeb4d5504 Support the Project 2024-11-26 00:09:46 +03:00
SMKRV daec801073 Misc 2024-11-25 23:50:33 +03:00
SMKRV e4916a7b7c Misc 2024-11-25 23:49:42 +03:00
SMKRV a08abd76e3 Misc 2024-11-25 23:48:55 +03:00
SMKRV a2be709608 Misc 2024-11-25 23:48:16 +03:00
SMKRV 69002ef926 Misc 2024-11-25 23:45:28 +03:00
SMKRV 9ade5a7194 misc 2024-11-25 23:43:05 +03:00
SMKRV 9b3f4f605b Sensor Attributes 2024-11-25 17:59:17 +03:00
SMKRV b862968d01 Release v2.0.0-alpha 2024-11-25 17:31:42 +03:00
32 changed files with 4097 additions and 13983 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ name: Bug report
about: Create a report to help us improve about: Create a report to help us improve
title: '' title: ''
labels: bug labels: bug
assignees: '' assignees: ''
--- ---
+1 -1
View File
@@ -3,7 +3,7 @@ name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
title: '' title: ''
labels: enhancement labels: enhancement
assignees: '' assignees: ''
--- ---
+17
View File
@@ -0,0 +1,17 @@
name: Validate
on:
push:
pull_request:
schedule:
- cron: "0 0 * * *"
workflow_dispatch:
jobs:
validate-hacs:
runs-on: "ubuntu-latest"
steps:
- name: HACS validation
uses: "hacs/action@main"
with:
category: "integration"
+1
View File
@@ -37,3 +37,4 @@ wheels/
Thumbs.db Thumbs.db
*.psd *.psd
*.zip *.zip
*.txt
+1 -1
View File
@@ -21,7 +21,7 @@ We welcome contributions to the HA Text AI project! This document will help you
git remote add upstream https://github.com/smkrv/ha-text-ai.git git remote add upstream https://github.com/smkrv/ha-text-ai.git
``` ```
### 2. Creating a Development Branch ### 2. Creating a Development Branch
```bash ```bash
# Update the main branch # Update the main branch
+433 -18
View File
@@ -1,22 +1,437 @@
MIT License Attribution-NonCommercial-ShareAlike 4.0 International
Copyright (c) 2024 smkrv =======================================================================
Permission is hereby granted, free of charge, to any person obtaining a copy Creative Commons Corporation ("Creative Commons") is not a law firm and
of this software and associated documentation files (the "Software"), to deal does not provide legal services or legal advice. Distribution of
in the Software without restriction, including without limitation the rights Creative Commons public licenses does not create a lawyer-client or
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell other relationship. Creative Commons makes its licenses and related
copies of the Software, and to permit persons to whom the Software is information available on an "as-is" basis. Creative Commons gives no
furnished to do so, subject to the following conditions: warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
The above copyright notice and this permission notice shall be included in all Using Creative Commons Public Licenses
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Creative Commons public licenses provide a standard set of terms and
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, conditions that creators and other rights holders may use to share
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE original works of authorship and other material subject to copyright
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER and certain other rights specified in the public license below. The
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, following considerations are for informational purposes only, are not
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE exhaustive, and do not form part of our licenses.
SOFTWARE.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
l. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
+262 -22
View File
@@ -2,22 +2,28 @@
<div align="center"> <div align="center">
![GitHub release](https://img.shields.io/github/release/smkrv/ha-text-ai.svg?style=flat-square) ![GitHub downloads](https://img.shields.io/github/downloads/smkrv/ha-text-ai/total.svg?style=flat-square) ![GitHub stars](https://img.shields.io/github/stars/smkrv/ha-text-ai.svg?style=social) ![GitHub last commit](https://img.shields.io/github/last-commit/smkrv/ha-text-ai.svg?style=flat-square) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT) [![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=flat-square)](https://github.com/hacs/integration) ![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)
<img src="https://github.com/smkrv/ha-text-ai/blob/3e3ec45b195c92989434fde40ae110027f4ea124/misc/icons/icon.png" alt="HA Text AI" width="140"/> <img src="https://github.com/smkrv/ha-text-ai/blob/524849f6a945ec62c2cf6a6b7ecd9a28b37bf0fa/misc/icons/logo.jpg" alt="HA Text AI" height="160"/>
### Advanced AI Integration for Home Assistant with multi-provider support ### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
</div> </div>
<p align="center"> <p align="center">
Transform your smart home experience with powerful AI assistance powered by multiple AI providers including OpenAI GPT and Anthropic Claude models. Get intelligent responses, automate complex scenarios, and enhance your home automation with advanced natural language processing. Transform your smart home experience with powerful AI assistance powered by multiple AI providers including OpenAI GPT and Anthropic Claude models. Get intelligent responses, automate complex scenarios, and enhance your home automation with advanced natural language processing.
</p> </p>
--- ---
> [!NOTE]
> 🚧 ALPHA VERSION 🚧 > [!IMPORTANT]
> Expect: potential bugs, frequent changes, incomplete features. > 🚧 BETA VERSION
> 🤝 Community Driven > Expect: potential bugs, frequent changes, incomplete features.
> 🤝 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>
>
> [Screenshots](misc/screenshots/screenshot.jpg)
## 🌟 Features ## 🌟 Features
@@ -34,10 +40,10 @@ Transform your smart home experience with powerful AI assistance powered by mult
- Natural conversation flow - Natural conversation flow
- 📝 **Enhanced Memory Management**: - 📝 **Enhanced Memory Management**:
- Persistent conversation history - File-based conversation history storage
- Context-aware responses - Automatic history rotation
- Customizable history limits - Configurable history size limits
- Model-specific filtering - Secure storage in Home Assistant
-**Performance Optimization**: -**Performance Optimization**:
- Efficient token usage - Efficient token usage
@@ -71,7 +77,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
## 📋 Prerequisites ## 📋 Prerequisites
- Home Assistant 2023.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/))
@@ -139,20 +145,63 @@ To be compatible, a provider should support:
4. Follow the configuration steps 4. Follow the configuration steps
### Via YAML ### Via YAML
### Platform Configuration (Global Settings)
```yaml ```yaml
ha_text_ai: ha_text_ai:
api_provider: openai # or anthropic api_provider: openai # Required
api_key: !secret ai_api_key api_key: !secret ai_api_key # Required
model: gpt-4o-mini model: gpt-4o-mini # Strongly recommended
temperature: 0.7 temperature: 0.7 # Optional
max_tokens: 1000 max_tokens: 1000 # Optional
request_interval: 1.0 request_interval: 1.0 # Optional
api_endpoint: https://api.openai.com/v1 # optional, for custom endpoints api_endpoint: https://api.openai.com/v1 # Required
system_prompt: | system_prompt: | # Optional
You are a home automation expert assistant. You are a home automation expert assistant.
Focus on practical and efficient solutions. Focus on practical and efficient solutions.
``` ```
### Sensor Configuration
```yaml
sensor:
- platform: ha_text_ai
name: "My AI Assistant" # Required, unique identifier
api_provider: openai # Optional (inherits from platform)
model: "gpt-4o-mini" # Optional
temperature: 0.7 # Optional
max_tokens: 1000 # Optional
```
### 📋 Configuration Parameters
#### Platform Configuration
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `api_provider` | String | ✅ | - | AI service provider (openai, anthropic) |
| `api_key` | String | ✅ | - | Authentication key for AI service |
| `model` | String | ⚠️ | Provider default | Strongly recommended: Specific AI model to use. If not specified, the provider's default model will be used |
| `temperature` | Float | ❌ | 0.7 | Response creativity level (0.0-2.0) |
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
| `max_history_size` | Integer | ❌ | 100 | Maximum number of conversation entries to store |
| `history_file_size` | Integer | ⚠️ | 1 | Maximum history file size in MB |
#### Sensor Configuration
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `platform` | String | ✅ | - | Must be `ha_text_ai` |
| `name` | String | ✅ | - | Unique sensor identifier |
| `api_provider` | String | ❌ | Platform setting | Override global provider |
| `model` | String | ⚠️ | Platform setting | Recommended: Override global model. If not specified, uses platform or provider default |
| `temperature` | Float | ❌ | Platform setting | Override global temperature |
| `max_tokens` | Integer | ❌ | Platform setting | Override global max tokens |
## 🛠️ Available Services ## 🛠️ Available Services
### ask_question ### ask_question
@@ -192,6 +241,157 @@ data:
filter_model: "gpt-4o" # optional filter_model: "gpt-4o" # optional
``` ```
### 🏷️ HA Text AI Sensor Naming Convention
#### Character Restrictions
- Only lowercase letters (a-z)
- Numbers (0-9)
- Underscore (_)
- Maximum length: 50 characters (including `ha_text_ai_`)
#### Sensor Name Structure
```yaml
# Always starts with 'sensor.ha_text_ai_'
# You define only the part after the underscore
sensor.ha_text_ai_YOUR_UNIQUE_SUFFIX
# Examples:
sensor.ha_text_ai_gpt # GPT-based sensor
sensor.ha_text_ai_claude # Claude-based sensor
sensor.ha_text_ai_gpt # Custom suffix
```
#### Response Retrieval
```yaml
# Use your specific sensor name
{{ state_attr('sensor.ha_text_ai_gpt', 'response') }}
```
#### Practical Usage
```yaml
automation:
- alias: "AI Response with Custom Sensor"
action:
- service: ha_text_ai.ask_question
data:
question: "Home automation advice"
- service: notify.mobile
data:
message: >
AI Tip:
{{ state_attr('sensor.ha_text_ai_gpt', 'response') }}
```
### 💡 Naming Rules
- Prefix is always `sensor.ha_text_ai_`
- Add your unique identifier after the underscore
- Use lowercase
- No spaces allowed
- Keep it descriptive but concise
### 🔍 HA Text AI Sensor Attributes
#### Model and Provider Information
```yaml
# Name of the AI model currently in use (e.g., latest version of GPT)
{{ state_attr('sensor.ha_text_ai_gpt', 'Model') }} # gpt-4o
# Service provider for the AI model (determines API endpoint and authentication)
{{ state_attr('sensor.ha_text_ai_gpt', 'Api provider') }} # openai
# Previous or alternative model configuration
{{ state_attr('sensor.ha_text_ai_gpt', 'Last model') }} # gpt-4o
```
#### System Status
```yaml
# Current operational readiness of the AI service API
{{ state_attr('sensor.ha_text_ai_gpt', 'Api status') }} # ready
# Indicates if a request is currently being processed
{{ state_attr('sensor.ha_text_ai_gpt', 'Is processing') }} # false
# Shows if the API has hit its request rate limit
{{ state_attr('sensor.ha_text_ai_gpt', 'Is rate limited') }} # false
# Status of the specific API endpoint being used
{{ state_attr('sensor.ha_text_ai_gpt', 'Endpoint status') }} # ready
```
#### Performance Metrics
```yaml
# Total number of successfully completed API requests
{{ state_attr('sensor.ha_text_ai_gpt', 'Successful requests') }} # 0
# Number of API requests that encountered errors
{{ state_attr('sensor.ha_text_ai_gpt', 'Failed requests') }} # 0
# Mean time taken to receive a response from the AI service
{{ state_attr('sensor.ha_text_ai_gpt', 'Average latency') }} # 0
# Maximum time taken for a single request-response cycle
{{ state_attr('sensor.ha_text_ai_gpt', 'Max latency') }} # 0
```
#### Conversation and Token Usage
```yaml
# Number of previous interactions stored in conversation context
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
# Total number of tokens used across all interactions
{{ state_attr('sensor.ha_text_ai_gpt', 'Total tokens') }} # 0
# Tokens used in the input prompts
{{ state_attr('sensor.ha_text_ai_gpt', 'Prompt tokens') }} # 0
# Tokens used in the AI's generated responses
{{ state_attr('sensor.ha_text_ai_gpt', 'Completion tokens') }} # 0
# Number of entries in current history file
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
# Last few conversation entries (limited to 3 for performance)
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
```
#### Last Interaction Details
```yaml
# Most recent complete response generated by the AI service
{{ state_attr('sensor.ha_text_ai_gpt', 'Response') }} # Last AI response
# The most recently processed user query or prompt
{{ state_attr('sensor.ha_text_ai_gpt', 'Question') }} # Last asked question
# Precise moment when the last interaction occurred (useful for tracking and logging)
{{ state_attr('sensor.ha_text_ai_gpt', 'Last timestamp') }} # Timestamp
```
#### System Health
```yaml
# Cumulative count of all errors encountered during AI service interactions
{{ state_attr('sensor.ha_text_ai_gpt', 'Total errors') }} # 0
# Indicates if the AI service is currently undergoing scheduled or emergency maintenance
{{ state_attr('sensor.ha_text_ai_gpt', 'Is maintenance') }} # false
# Total continuous operational time of the AI service (in hours or days)
{{ state_attr('sensor.ha_text_ai_gpt', 'Uptime') }} # 547,58
```
### History Storage
Conversation history stored in `.storage/ha_text_ai_history/` directory:
- Each instance has its own history file
- Files are automatically rotated when size limit is reached
- Archived history files are timestamped
- Default maximum file size: 1MB
### 💡 Pro Tips
- Always check attribute existence
- Use these attributes for monitoring and automation
- Some values might be 0 or empty initially
## 📘 FAQ ## 📘 FAQ
**Q: Which AI providers are supported?** **Q: Which AI providers are supported?**
@@ -218,6 +418,16 @@ A: Yes, your data is secure. The system operates entirely on your local machine,
**Q: How do context messages work?** **Q: How do context messages work?**
A: Context messages allow the AI to remember and reference previous conversation history. By default, 5 previous messages are included, but you can customize this from 1 to 20 messages to control the conversation depth and token usage. A: Context messages allow the AI to remember and reference previous conversation history. By default, 5 previous messages are included, but you can customize this from 1 to 20 messages to control the conversation depth and token usage.
**Q: Where is conversation history stored?**
A: History is stored in files under the `.storage/ha_text_ai_history/` directory, with automatic rotation and size management.
**Q: Can I access old conversation history?**
A: Yes, archived history files are stored with timestamps and can be accessed manually if needed.
**Q: How much history is kept?**
A: By default, up to 100 conversations are stored, but this can be configured. Files are automatically rotated when they reach 1MB.
## 🤝 Contributing ## 🤝 Contributing
Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md). Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md).
@@ -228,15 +438,45 @@ Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md).
4. Push branch (`git push origin feature/Enhancement`) 4. Push branch (`git push origin feature/Enhancement`)
5. Open Pull Request 5. Open Pull Request
## Legal Disclaimer and Limitation of Liability
### Software Disclaimer
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
## 📝 License ## 📝 License
MIT License - see [LICENSE](LICENSE) for details. Author: SMKRV
[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) - see [LICENSE](LICENSE) for details.
## 💡 Support the Project
The best support is:
- Sharing feedback
- Contributing ideas
- Recommending to friends
- Reporting issues
- Star the repository
If you want to say thanks financially, you can send a small token of appreciation in USDT:
**USDT Wallet (TRC10/TRC20):**
`TXC9zYHYPfWUGi4Sv4R1ctTBGScXXQk5HZ`
*Open-source is built by community passion!* 🚀
--- ---
<div align="center"> <div align="center">
Made with ❤️ for the Home Assistant Community Made with ❤️ and Claude 3.5 Sonnet for the Home Assistant Community
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues) [Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
+33 -22
View File
@@ -1,4 +1,11 @@
"""The HA Text AI integration.""" """
The HA Text AI integration.
@license: CC BY-NC-SA 4.0 International
@author: SMKRV
@github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai
"""
from __future__ import annotations from __future__ import annotations
import logging import logging
@@ -43,6 +50,8 @@ from .const import (
SERVICE_CLEAR_HISTORY, SERVICE_CLEAR_HISTORY,
SERVICE_GET_HISTORY, SERVICE_GET_HISTORY,
SERVICE_SET_SYSTEM_PROMPT, SERVICE_SET_SYSTEM_PROMPT,
DEFAULT_MAX_HISTORY,
CONF_MAX_HISTORY_SIZE,
) )
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -89,7 +98,7 @@ async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
source = os.path.join(os.path.dirname(__file__), 'icons', 'icon.svg') source = os.path.join(os.path.dirname(__file__), 'icons', 'icon.svg')
dest_dir = os.path.join(hass.config.path('www'), 'icons') dest_dir = os.path.join(hass.config.path('www'), 'icons')
os.makedirs(dest_dir, exist_ok=True) os.makedirs(dest_dir, exist_ok=True)
dest = os.path.join(dest_dir, 'icon.svg') dest = os.path.join(dest_dir, 'icon.png')
if not os.path.exists(dest): if not os.path.exists(dest):
shutil.copyfile(source, dest) shutil.copyfile(source, dest)
except Exception as ex: except Exception as ex:
@@ -197,11 +206,14 @@ async def async_check_api(session, endpoint: str, headers: dict, provider: str)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up HA Text AI from a config entry.""" """Set up HA Text AI from a config entry."""
_LOGGER.debug(f"Setting up HA Text AI entry: {entry.data}")
try: try:
if CONF_API_PROVIDER not in entry.data: if CONF_API_PROVIDER not in entry.data:
_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) api_provider = entry.data.get(CONF_API_PROVIDER)
model = entry.data.get(CONF_MODEL, DEFAULT_MODEL) model = entry.data.get(CONF_MODEL, DEFAULT_MODEL)
@@ -212,6 +224,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
).rstrip('/') ).rstrip('/')
api_key = entry.data[CONF_API_KEY] api_key = entry.data[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)
max_tokens = entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
temperature = entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
max_history_size = entry.data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
context_messages = entry.data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
is_anthropic = api_provider == API_PROVIDER_ANTHROPIC is_anthropic = api_provider == API_PROVIDER_ANTHROPIC
headers = { headers = {
@@ -242,39 +259,33 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass=hass, hass=hass,
client=api_client, client=api_client,
model=model, model=model,
update_interval=entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL), update_interval=request_interval,
instance_name=instance_name, instance_name=instance_name,
max_tokens=entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS), max_tokens=max_tokens,
temperature=entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE), temperature=temperature,
max_history_size=max_history_size,
context_messages=context_messages,
is_anthropic=is_anthropic, is_anthropic=is_anthropic,
context_messages=entry.data.get(
CONF_CONTEXT_MESSAGES,
DEFAULT_CONTEXT_MESSAGES
),
) )
coordinator.data = coordinator._initial_state.copy() _LOGGER.debug(f"Created coordinator for {instance_name}")
_LOGGER.debug(f"Initial state set for coordinator {instance_name}")
await coordinator.async_config_entry_first_refresh()
# Store coordinator
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator hass.data[DOMAIN][entry.entry_id] = coordinator
_LOGGER.debug(f"Stored coordinator in hass.data[{DOMAIN}][{entry.entry_id}]")
# Set up platforms
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
_LOGGER.info( _LOGGER.debug(f"Setup completed for {instance_name}")
"Successfully set up %s instance '%s' with model %s",
api_provider,
instance_name,
model
)
return True return True
except Exception as ex: except Exception as err:
_LOGGER.exception("Setup error: %s", str(ex)) _LOGGER.exception(f"Error setting up HA Text AI: {err}")
raise ConfigEntryNotReady(f"Setup error: {str(ex)}") from ex raise
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."""
+52 -20
View File
@@ -1,4 +1,11 @@
"""API Client for HA Text AI.""" """
API Client for HA Text AI.
@license: CC BY-NC-SA 4.0 International
@author: SMKRV
@github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai
"""
import logging import logging
import asyncio import asyncio
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional
@@ -19,6 +26,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
class APIClient: class APIClient:
"""API Client for OpenAI and Anthropic.""" """API Client for OpenAI and Anthropic."""
@@ -59,6 +67,7 @@ class APIClient:
payload: Dict[str, Any], payload: Dict[str, Any],
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Make API request with retry logic.""" """Make API request with retry logic."""
_LOGGER.debug(f"API Request: URL={url}, Payload={payload}")
for attempt in range(API_RETRY_COUNT): for attempt in range(API_RETRY_COUNT):
try: try:
async with timeout(API_TIMEOUT): async with timeout(API_TIMEOUT):
@@ -66,20 +75,23 @@ class APIClient:
url, url,
json=payload, json=payload,
headers=self.headers, headers=self.headers,
timeout=self.timeout timeout=self.timeout,
) as response: ) as response:
_LOGGER.debug(f"Response status: {response.status}")
if response.status != 200: if response.status != 200:
error_data = await response.json() error_data = await response.json()
_LOGGER.error(f"API error: {error_data}")
raise HomeAssistantError(f"API error: {error_data}") raise HomeAssistantError(f"API error: {error_data}")
return await response.json() return await response.json()
except asyncio.TimeoutError: except asyncio.TimeoutError:
_LOGGER.warning(f"Timeout on attempt {attempt + 1}")
if attempt == API_RETRY_COUNT - 1: if attempt == API_RETRY_COUNT - 1:
raise HomeAssistantError("API request timed out") raise HomeAssistantError("API request timed out")
await asyncio.sleep(1 * (attempt + 1)) await asyncio.sleep(1 * (attempt + 1))
except Exception as e: except Exception as e:
_LOGGER.warning(f"API request failed on attempt {attempt + 1}: {str(e)}")
if attempt == API_RETRY_COUNT - 1: if attempt == API_RETRY_COUNT - 1:
raise raise
_LOGGER.warning("API request failed, retrying: %s", str(e))
await asyncio.sleep(1 * (attempt + 1)) await asyncio.sleep(1 * (attempt + 1))
async def create( async def create(
@@ -101,6 +113,11 @@ class APIClient:
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)}")
@@ -125,16 +142,14 @@ class APIClient:
return { return {
"choices": [ "choices": [
{ {
"message": { "message": {"content": data["choices"][0]["message"]["content"]},
"content": data["choices"][0]["message"]["content"]
}
} }
], ],
"usage": { "usage": {
"prompt_tokens": data["usage"]["prompt_tokens"], "prompt_tokens": data["usage"]["prompt_tokens"],
"completion_tokens": data["usage"]["completion_tokens"], "completion_tokens": data["usage"]["completion_tokens"],
"total_tokens": data["usage"]["total_tokens"] "total_tokens": data["usage"]["total_tokens"],
} },
} }
async def _create_anthropic_completion( async def _create_anthropic_completion(
@@ -147,19 +162,24 @@ class APIClient:
"""Create completion using Anthropic API.""" """Create completion using Anthropic API."""
url = f"{self.endpoint}/v1/messages" url = f"{self.endpoint}/v1/messages"
# Convert messages to Anthropic format system_prompt = None
system_prompt = next( filtered_messages = []
(msg["content"] for msg in messages if msg["role"] == "system"), for msg in messages:
None if msg['role'] == 'system':
) if system_prompt is None:
conversation = [msg for msg in messages if msg["role"] != "system"] system_prompt = msg['content']
else:
system_prompt += f" {msg['content']}"
else:
filtered_messages.append(msg)
payload = { payload = {
"model": model, "model": model,
"messages": conversation, "messages": filtered_messages,
"max_tokens": max_tokens, "max_tokens": max_tokens,
"temperature": temperature, "temperature": temperature,
} }
if system_prompt: if system_prompt:
payload["system"] = system_prompt payload["system"] = system_prompt
@@ -167,14 +187,26 @@ class APIClient:
return { return {
"choices": [ "choices": [
{ {
"message": { "message": {"content": data["content"][0]["text"]},
"content": data["content"][0]["text"]
}
} }
], ],
"usage": { "usage": {
"prompt_tokens": data["usage"]["input_tokens"], "prompt_tokens": data["usage"]["input_tokens"],
"completion_tokens": data["usage"]["output_tokens"], "completion_tokens": data["usage"]["output_tokens"],
"total_tokens": data["usage"]["input_tokens"] + data["usage"]["output_tokens"] "total_tokens": data["usage"]["input_tokens"] + data["usage"]["output_tokens"],
} },
} }
async def check_connection(self) -> bool:
"""Check API connection."""
try:
await self._make_request(self.endpoint, {"test": "connection"})
return True
except Exception as e:
_LOGGER.error(f"Connection check failed: {str(e)}")
return False
async def shutdown(self) -> None:
"""Shutdown API client."""
_LOGGER.debug("Shutting down API client")
await self.session.close()
+132 -30
View File
@@ -1,4 +1,11 @@
"""Config flow for HA text AI integration.""" """
Config flow for HA text AI integration.
@license: CC BY-NC-SA 4.0 International
@author: SMKRV
@github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai
"""
import logging import logging
from typing import Any, Dict, Optional from typing import Any, Dict, Optional
@@ -34,10 +41,21 @@ from .const import (
MIN_MAX_TOKENS, MIN_MAX_TOKENS,
MAX_MAX_TOKENS, MAX_MAX_TOKENS,
MIN_REQUEST_INTERVAL, MIN_REQUEST_INTERVAL,
DEFAULT_NAME_PREFIX,
DEFAULT_MAX_HISTORY,
CONF_MAX_HISTORY_SIZE,
) )
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
def normalize_name(name: str) -> str:
"""Normalize name to conform to HA naming convention using underscores."""
normalized = ''.join(c if c.isalnum() or c == '_' else '_' for c in name)
normalized = '_'.join(filter(None, normalized.split('_')))
return normalized.lower()
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for HA text AI.""" """Handle a config flow for HA text AI."""
@@ -69,18 +87,18 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_provider(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult: async def async_step_provider(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
"""Handle provider configuration step.""" """Handle provider configuration step."""
self._errors = {}
if user_input is None: if user_input is None:
default_endpoint = ( default_endpoint = (
DEFAULT_OPENAI_ENDPOINT if self._provider == API_PROVIDER_OPENAI DEFAULT_OPENAI_ENDPOINT if self._provider == API_PROVIDER_OPENAI
else DEFAULT_ANTHROPIC_ENDPOINT else DEFAULT_ANTHROPIC_ENDPOINT
) )
suggested_name = f"HA Text AI {len(self._async_current_entries()) + 1}"
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=suggested_name): 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,
@@ -103,27 +121,86 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
vol.Coerce(int), vol.Coerce(int),
vol.Range(min=1, max=20) vol.Range(min=1, max=20)
), ),
}), vol.Optional(
errors=self._errors CONF_MAX_HISTORY_SIZE,
default=DEFAULT_MAX_HISTORY
): vol.All(
vol.Coerce(int),
vol.Range(min=1, max=100)
),
})
) )
instance_name = user_input[CONF_NAME] input_copy = user_input.copy()
await self._async_validate_name(instance_name)
if self._errors:
return await self.async_step_provider()
if not await self._async_validate_api(user_input): try:
return await self.async_step_provider() normalized_name = self._validate_and_normalize_name(input_copy[CONF_NAME])
input_copy[CONF_NAME] = normalized_name
except ValueError as e:
return self.async_show_form(
step_id="provider",
data_schema=vol.Schema({
vol.Required(CONF_NAME, default=input_copy[CONF_NAME]): str,
vol.Required(CONF_API_KEY, default=input_copy[CONF_API_KEY]): str,
vol.Required(CONF_MODEL, default=input_copy[CONF_MODEL]): str,
vol.Required(CONF_API_ENDPOINT, default=input_copy[CONF_API_ENDPOINT]): str,
vol.Optional(CONF_TEMPERATURE, default=input_copy.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)): vol.All(
vol.Coerce(float),
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
),
}),
errors={"name": str(e)}
)
return await self._create_entry(user_input) try:
if not await self._async_validate_api(input_copy):
return self.async_show_form(
step_id="provider",
data_schema=vol.Schema({
}),
errors=self._errors
)
except Exception as e:
return self.async_show_form(
step_id="provider",
data_schema=vol.Schema({
}),
errors={"base": str(e)}
)
return await self._create_entry(input_copy)
def _validate_and_normalize_name(self, name: str) -> str:
"""
Validate and normalize name with detailed error handling.
Raises:
ValueError: If name is invalid
Returns:
Normalized name
"""
if not name:
raise ValueError("empty")
name = name.strip()
normalized = ''.join(
c if c.isalnum() or c in ' _' else '_' # Only allow underscores
for c in name
)
normalized = normalized.replace(' ', '_').lower()
async def _async_validate_name(self, name: str) -> bool:
"""Validate that the name is unique."""
for entry in self._async_current_entries(): for entry in self._async_current_entries():
if entry.data.get(CONF_NAME) == name: if entry.data.get(CONF_NAME, "") == normalized:
self._errors["name"] = "name_exists" raise ValueError("name_exists")
return False
return True normalized = normalized[:50]
if not normalized:
raise ValueError("empty")
return normalized
async def _async_validate_api(self, user_input: Dict[str, Any]) -> bool: async def _async_validate_api(self, user_input: Dict[str, Any]) -> bool:
"""Validate API connection.""" """Validate API connection."""
@@ -167,21 +244,36 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
} }
async def _create_entry(self, user_input: Dict[str, Any]) -> FlowResult: async def _create_entry(self, user_input: Dict[str, Any]) -> FlowResult:
"""Create the config entry.""" """Create the config entry with comprehensive data preservation."""
instance_name = user_input[CONF_NAME] instance_name = user_input[CONF_NAME]
unique_id = f"{DOMAIN}_{instance_name}_{self._provider}".lower().replace(" ", "_") normalized_name = normalize_name(instance_name)
unique_id = f"{DOMAIN}_{normalized_name}_{self._provider}".lower()
entry_data = {
CONF_API_PROVIDER: self._provider,
CONF_NAME: instance_name,
"normalized_name": normalized_name,
CONF_API_KEY: user_input.get(CONF_API_KEY),
CONF_API_ENDPOINT: user_input.get(CONF_API_ENDPOINT),
"unique_id": unique_id,
CONF_MODEL: user_input.get(CONF_MODEL, DEFAULT_MODEL),
CONF_TEMPERATURE: user_input.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
CONF_MAX_TOKENS: user_input.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
CONF_REQUEST_INTERVAL: user_input.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL),
CONF_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),
}
for key, value in user_input.items():
if key not in entry_data:
entry_data[key] = value
_LOGGER.debug(f"Creating config entry with data: {entry_data}")
return self.async_create_entry( return self.async_create_entry(
title=instance_name, title=instance_name,
data={ data=entry_data
CONF_API_PROVIDER: self._provider,
CONF_NAME: instance_name,
**user_input,
"unique_id": unique_id,
CONF_CONTEXT_MESSAGES: user_input.get(
CONF_CONTEXT_MESSAGES,
DEFAULT_CONTEXT_MESSAGES)
}
) )
@staticmethod @staticmethod
@@ -243,5 +335,15 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
vol.Coerce(int), vol.Coerce(int),
vol.Range(min=1, max=20) vol.Range(min=1, max=20)
), ),
vol.Optional(
CONF_MAX_HISTORY_SIZE,
default=current_data.get(
CONF_MAX_HISTORY_SIZE,
DEFAULT_MAX_HISTORY
)
): vol.All(
vol.Coerce(int),
vol.Range(min=1, max=100)
),
}) })
) )
+16 -5
View File
@@ -1,4 +1,11 @@
"""Constants for the HA text AI integration.""" """
Constants for the HA text AI integration.
@license: CC BY-NC-SA 4.0 International
@author: SMKRV
@github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai
"""
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
@@ -6,7 +13,7 @@ from homeassistant.helpers import config_validation as cv
# Domain and platforms # Domain and platforms
DOMAIN: Final = "ha_text_ai" DOMAIN: Final = "ha_text_ai"
PLATFORMS: Final = [Platform.SENSOR] PLATFORMS: list[str] = ["sensor"]
# Provider configuration # Provider configuration
CONF_API_PROVIDER: Final = "api_provider" CONF_API_PROVIDER: Final = "api_provider"
@@ -29,10 +36,13 @@ 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_INSTANCE: Final = "instance" CONF_INSTANCE: Final = "instance"
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" 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"
ABSOLUTE_MAX_HISTORY_SIZE = 500
MAX_ENTRY_SIZE = 1 * 1024 * 1024
# Default values # Default values
DEFAULT_MODEL: Final = "gpt-4o-mini" DEFAULT_MODEL: Final = "gpt-4o-mini"
DEFAULT_TEMPERATURE: Final = 0.1 DEFAULT_TEMPERATURE: Final = 0.1
@@ -41,6 +51,7 @@ DEFAULT_REQUEST_INTERVAL: Final = 1.0
DEFAULT_TIMEOUT: Final = 30 DEFAULT_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_CONTEXT_MESSAGES: Final = 5 DEFAULT_CONTEXT_MESSAGES: Final = 5
# Parameter constraints # Parameter constraints
@@ -164,7 +175,7 @@ SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
vol.Required(CONF_INSTANCE): cv.string, vol.Required(CONF_INSTANCE): cv.string,
vol.Optional("limit", default=10): vol.All( vol.Optional("limit", default=10): vol.All(
vol.Coerce(int), vol.Coerce(int),
vol.Range(min=1, max=100) vol.Range(min=1, max=100),
), ),
vol.Optional("filter_model"): cv.string vol.Optional("filter_model"): cv.string
}) })
@@ -189,7 +200,7 @@ 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_MAX_HISTORY_SIZE, default=DEFAULT_MAX_HISTORY): vol.All( 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),
), ),
+603 -144
View File
@@ -1,7 +1,18 @@
"""The HA Text AI coordinator.""" """
The HA Text AI coordinator.
@license: CC BY-NC-SA 4.0 International
@author: SMKRV
@github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai
"""
from __future__ import annotations from __future__ import annotations
import logging import logging
import traceback
import aiofiles
import os
import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional
@@ -9,7 +20,9 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.const import CONF_NAME
from .config_flow import normalize_name
from .const import ( from .const import (
DOMAIN, DOMAIN,
STATE_READY, STATE_READY,
@@ -21,17 +34,35 @@ from .const import (
DEFAULT_TEMPERATURE, DEFAULT_TEMPERATURE,
DEFAULT_MAX_HISTORY, DEFAULT_MAX_HISTORY,
DEFAULT_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES,
ABSOLUTE_MAX_HISTORY_SIZE,
MAX_ENTRY_SIZE,
) )
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
class AsyncFileHandler:
"""Async context manager for file operations."""
def __init__(self, file_path: str, mode: str = 'a'):
self.file_path = file_path
self.mode = mode
async def __aenter__(self):
self.file = await aiofiles.open(self.file_path, self.mode)
return self.file
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.file.close()
class HATextAICoordinator(DataUpdateCoordinator): class HATextAICoordinator(DataUpdateCoordinator):
"""Home Assistant Text AI Conversation Coordinator."""
def __init__( def __init__(
self, self,
hass: HomeAssistant, hass: HomeAssistant,
client: Any, client: Any,
model: str, model: str,
update_interval: int, update_interval: int, # Moved up
instance_name: str, instance_name: str,
max_tokens: int = DEFAULT_MAX_TOKENS, max_tokens: int = DEFAULT_MAX_TOKENS,
temperature: float = DEFAULT_TEMPERATURE, temperature: float = DEFAULT_TEMPERATURE,
@@ -41,48 +72,57 @@ class HATextAICoordinator(DataUpdateCoordinator):
) -> None: ) -> None:
"""Initialize coordinator.""" """Initialize coordinator."""
self.instance_name = instance_name self.instance_name = instance_name
self.normalized_name = None
# Use the normalize_name function from config_flow to ensure consistency
from .config_flow import normalize_name
self.normalized_name = normalize_name(instance_name)
self.hass = hass self.hass = hass
self.client = client self.client = client
self.model = model self.model = model
self.temperature = temperature self.temperature = temperature
self.max_tokens = max_tokens self.max_tokens = max_tokens
self.max_history_size = max_history_size self.max_history_size = min(
max(1, max_history_size),
ABSOLUTE_MAX_HISTORY_SIZE
)
self.is_anthropic = is_anthropic self.is_anthropic = is_anthropic
# Initialize with default state # Initialize essential attributes first
self._initial_state = { self._is_processing = False
"state": STATE_READY, self._is_rate_limited = False
"metrics": { self._is_maintenance = False
"total_tokens": 0, self.endpoint_status = "ready"
"prompt_tokens": 0, self._system_prompt = None
"completion_tokens": 0, self._conversation_history = []
"successful_requests": 0,
"failed_requests": 0, self._performance_metrics = {
"total_errors": 0, "total_tokens": 0,
"average_latency": 0, "prompt_tokens": 0,
"max_latency": 0, "completion_tokens": 0,
"min_latency": float('inf'), "successful_requests": 0,
}, "failed_requests": 0,
"last_response": { "total_errors": 0,
"timestamp": dt_util.utcnow().isoformat(), "average_latency": 0,
"question": "", "max_latency": 0,
"response": "", "min_latency": float("inf"),
"model": model, }
"instance": instance_name,
"error": None self._last_response = {
}, "timestamp": dt_util.utcnow().isoformat(),
"is_processing": False, "question": "",
"is_rate_limited": False, "response": "",
"is_maintenance": False, "model": model,
"endpoint_status": "ready", "instance": instance_name,
"uptime": 0, "normalized_name": self.normalized_name,
"system_prompt": None, "error": None,
"history_size": 0,
"conversation_history": [],
} }
update_interval_td = timedelta(seconds=update_interval) update_interval_td = timedelta(seconds=update_interval)
# Call super().__init__ BEFORE other property access
super().__init__( super().__init__(
hass, hass,
_LOGGER, _LOGGER,
@@ -90,41 +130,300 @@ class HATextAICoordinator(DataUpdateCoordinator):
update_interval=update_interval_td, update_interval=update_interval_td,
) )
# Now initialize _initial_state (after super().__init__)
self._initial_state = {
"state": STATE_READY,
"metrics": self._performance_metrics.copy(),
"last_response": self.last_response.copy(), # Accessing here
"is_processing": self._is_processing,
"is_rate_limited": self._is_rate_limited,
"is_maintenance": self._is_maintenance,
"endpoint_status": self.endpoint_status,
"uptime": 0,
"system_prompt": self._system_prompt,
"history_size": len(self._conversation_history),
"conversation_history": self._conversation_history.copy(),
}
self.available = True
self._state = STATE_READY
self._conversation_history = [] # Full conversation history
self._start_time = dt_util.utcnow()
# Create history directory with safe mechanism
self._history_dir = os.path.join(
hass.config.path(".storage"),
"ha_text_ai_history"
)
os.makedirs(self._history_dir, exist_ok=True)
hass.async_create_task(self._check_history_directory())
# History file path using instance name
self._history_file = os.path.join(
self._history_dir,
f"{self.normalized_name}_history.txt"
)
# Maximum history file size (10 MB)
self._max_history_file_size = 10 * 1024 * 1024
# Asynchronous file initialization
hass.async_create_task(self.async_initialize_history_file())
_LOGGER.info(f"Initialized HA Text AI coordinator with instance: {instance_name}")
# Register instance # Register instance
self.hass.data.setdefault(DOMAIN, {}) self.hass.data.setdefault(DOMAIN, {})
self.hass.data[DOMAIN][instance_name] = self self.hass.data[DOMAIN][instance_name] = self
self.context_messages = context_messages self.context_messages = context_messages
self._system_prompt = None @property
self._conversation_history = [] def last_response(self) -> Dict[str, Any]:
self._performance_metrics = self._initial_state["metrics"].copy() """
self._is_processing = False Get the last response with fallback to conversation history.
self._is_rate_limited = False
self._is_maintenance = False
self.endpoint_status = "ready"
self.last_response = self._initial_state["last_response"].copy()
self._start_time = dt_util.utcnow()
_LOGGER.info(f"Initialized HA Text AI coordinator with instance: {instance_name}") Returns:
Dict containing last response information
"""
if self._last_response:
return self._last_response
if self._conversation_history:
latest = self._conversation_history[-1]
return {
"timestamp": latest.get("timestamp"),
"question": latest.get("question", ""),
"response": latest.get("response", ""),
"model": self.model,
"instance": self.instance_name,
"normalized_name": self.normalized_name,
"error": None
}
return {
"timestamp": dt_util.utcnow().isoformat(),
"question": "",
"response": "",
"model": self.model,
"instance": self.instance_name,
"normalized_name": self.normalized_name,
"error": None
}
@last_response.setter
def last_response(self, value: Dict[str, Any]) -> None:
"""
Set the last response value.
Args:
value: Dictionary containing response information
"""
self._last_response = value
async def async_initialize_history_file(self) -> None:
"""
Asynchronously initialize history file.
Creates the file and writes an initialization timestamp
without blocking the event loop.
"""
try:
# Use asyncio.to_thread to perform file I/O in a separate thread
await asyncio.to_thread(self._sync_initialize_history_file)
except Exception as e:
_LOGGER.error(f"Could not initialize history file: {e}")
_LOGGER.debug(traceback.format_exc())
def _sync_initialize_history_file(self) -> None:
"""
Synchronous method to create and initialize history file.
Runs in a separate thread to avoid blocking the event loop.
"""
try:
with open(self._history_file, 'a') as f:
f.write(f"History initialized at: {dt_util.utcnow().isoformat()}\n")
except Exception as e:
_LOGGER.error(f"Synchronous history file initialization failed: {e}")
# Add size check to _update_history method
async def _update_history(self, question: str, response: dict) -> None:
"""Update conversation history with size limits."""
try:
# Limit entry size
question = question[:MAX_ENTRY_SIZE]
response_content = response.get("content", "")[:MAX_ENTRY_SIZE]
history_entry = {
"timestamp": dt_util.utcnow().isoformat(),
"question": question,
"response": response_content,
}
self._conversation_history.append(history_entry)
# Enforce size limit
while len(self._conversation_history) > self.max_history_size:
self._conversation_history.pop(0)
await self._write_history_entry(history_entry)
await self._rotate_history()
except Exception as e:
_LOGGER.error(f"Error updating history: {e}")
_LOGGER.debug(traceback.format_exc())
# Update _write_history_entry method
async def _write_history_entry(self, entry: dict) -> None:
"""Write a single history entry to file asynchronously."""
try:
if not os.path.exists(self._history_dir):
os.makedirs(self._history_dir, exist_ok=True)
_LOGGER.debug(f"Writing history entry to {self._history_file}")
async with AsyncFileHandler(self._history_file) as f:
await f.write(
f"{entry['timestamp']}: "
f"Question: {entry['question']} - "
f"Response: {entry['response']}\n"
)
await f.flush()
_LOGGER.debug(f"Successfully wrote history entry")
except Exception as e:
_LOGGER.error(f"Error writing history entry: {e}")
_LOGGER.debug(traceback.format_exc())
def _sync_write_history_entry(self, entry: dict) -> None:
"""
Synchronous method to write history entry.
Runs in a separate thread to avoid blocking the event loop.
"""
try:
with open(self._history_file, 'a') as f:
f.write(
f"{entry['timestamp']}: "
f"Question: {entry['question']} - "
f"Response: {entry['response']}\n"
)
except Exception as e:
_LOGGER.error(f"Synchronous history entry writing failed: {e}")
async def _rotate_history(self) -> None:
"""Rotate conversation history with file management."""
try:
_LOGGER.debug(f"Starting history rotation for {self._history_file}")
await asyncio.to_thread(self._sync_rotate_history)
_LOGGER.debug(f"Completed history rotation")
except Exception as e:
_LOGGER.error(f"Error rotating history: {e}")
_LOGGER.debug(traceback.format_exc())
async def _check_history_directory(self) -> None:
"""
Asynchronously check history directory permissions and writability.
"""
try:
# Test write permission in a separate thread
test_file_path = os.path.join(self._history_dir, ".write_test")
await asyncio.to_thread(self._sync_test_directory_write, test_file_path)
except PermissionError:
_LOGGER.error(f"No write permissions for history directory: {self._history_dir}")
except Exception as e:
_LOGGER.error(f"Error checking history directory: {e}")
def _sync_test_directory_write(self, test_file_path: str) -> None:
"""
Synchronous method to test directory write permissions.
"""
try:
with open(test_file_path, 'w') as f:
f.write("Permission test")
os.remove(test_file_path)
except Exception as e:
_LOGGER.error(f"Directory write test failed: {e}")
def _sync_rotate_history(self) -> None:
"""
Synchronous method to rotate history files.
Runs in a separate thread to avoid blocking the event loop.
"""
try:
# Check and manage file size
if os.path.exists(self._history_file):
file_size = os.path.getsize(self._history_file)
if file_size > self._max_history_file_size:
# Create timestamped archive
archive_file = os.path.join(
self._history_dir,
f"{self.normalized_name}_history_{dt_util.utcnow().strftime('%Y%m%d_%H%M%S')}.txt"
)
os.rename(self._history_file, archive_file)
# Optional: Log rotation event
_LOGGER.info(f"History file rotated: {archive_file}")
# Ensure history doesn't exceed max size
if len(self._conversation_history) > self.max_history_size:
# Trim in-memory history
self._conversation_history = self._conversation_history[-self.max_history_size:]
# Write history entries
with open(self._history_file, 'a') as f:
for entry in self._conversation_history:
f.write(
f"{entry['timestamp']}: {entry['question']} - {entry['response']}\n"
)
except Exception as e:
_LOGGER.error(f"Synchronous history rotation failed: {e}")
_LOGGER.debug(traceback.format_exc())
async def _async_update_data(self) -> Dict[str, Any]: async def _async_update_data(self) -> Dict[str, Any]:
"""Update data via library.""" """Update data via library."""
try: try:
current_state = self._get_current_state() current_state = self._get_current_state()
_LOGGER.debug(f"Updating data for {self.instance_name}, current state: {current_state}") _LOGGER.debug(
f"Updating data for {self.instance_name}, current state: {current_state}"
)
limited_history = []
if self._conversation_history:
for entry in self._conversation_history[-3:]:
limited_entry = {
"timestamp": entry["timestamp"],
"question": entry["question"][:4096],
"response": entry["response"][:4096],
}
limited_history.append(limited_entry)
limited_last_response = self.last_response.copy()
if "response" in limited_last_response:
limited_last_response["response"] = limited_last_response["response"][:4096]
if "question" in limited_last_response:
limited_last_response["question"] = limited_last_response["question"][:4096]
data = { data = {
"state": current_state, "state": current_state,
"metrics": self._performance_metrics, "metrics": self._performance_metrics,
"last_response": self.last_response, "last_response": limited_last_response,
"is_processing": self._is_processing, "is_processing": self._is_processing,
"is_rate_limited": self._is_rate_limited, "is_rate_limited": self._is_rate_limited,
"is_maintenance": self._is_maintenance, "is_maintenance": self._is_maintenance,
"endpoint_status": self.endpoint_status, "endpoint_status": self.endpoint_status,
"uptime": (dt_util.utcnow() - self._start_time).total_seconds(), "uptime": (dt_util.utcnow() - self._start_time).total_seconds(),
"system_prompt": self._system_prompt, "system_prompt": self._system_prompt[:4096] if self._system_prompt else None,
"history_size": len(self._conversation_history), "history_size": len(self._conversation_history),
"conversation_history": self._conversation_history, "conversation_history": limited_history,
"normalized_name": self.normalized_name,
} }
# Validate data # Validate data
@@ -141,12 +440,15 @@ class HATextAICoordinator(DataUpdateCoordinator):
async def async_update_ha_state(self) -> None: async def async_update_ha_state(self) -> None:
"""Update Home Assistant state.""" """Update Home Assistant state."""
try: try:
_LOGGER.debug(f"Requesting state update for {self.instance_name}") _LOGGER.debug(
f"Requesting state update for {self.instance_name} (normalized: {self.normalized_name})"
)
await self.async_request_refresh() await self.async_request_refresh()
# Force update of all entities # Force update of all entities
entity_id_base = f"sensor.ha_text_ai_{self.normalized_name.lower()}"
for entity_id in self.hass.states.async_entity_ids(): for entity_id in self.hass.states.async_entity_ids():
if entity_id.startswith(f"sensor.ha_text_ai_{self.instance_name}"): if entity_id.startswith(entity_id_base):
self.hass.states.async_set(entity_id, self._get_current_state()) self.hass.states.async_set(entity_id, self._get_current_state())
except Exception as err: except Exception as err:
@@ -164,15 +466,67 @@ class HATextAICoordinator(DataUpdateCoordinator):
return STATE_ERROR return STATE_ERROR
return STATE_READY return STATE_READY
def _calculate_context_tokens(self, messages: List[Dict[str, str]]) -> int: def _calculate_context_tokens(self, messages: List[Dict[str, str]], model: str = None) -> int:
"""
Estimate tokens for conversation context.
Args:
messages: List of message dictionaries
model: Optional model name for provider-specific estimation
Returns:
Estimated number of tokens
"""
try: try:
# Anthropic specific token counting
if self.is_anthropic and hasattr(self.client, 'count_tokens'): if self.is_anthropic and hasattr(self.client, 'count_tokens'):
return sum(self.client.count_tokens(msg['content']) for msg in messages) return sum(self.client.count_tokens(msg['content']) for msg in messages)
return sum(len(msg['content']) // 4 for msg in messages) def estimate_tokens(text: str) -> int:
"""
Flexible token estimation algorithm.
Heuristics:
- Count words
- Estimate special characters
- Fallback to character-based estimation
"""
# Word-based estimation
words = len(text.split())
# Special character handling
special_chars = sum(1 for char in text if not char.isalnum())
# Character-based fallback
char_tokens = len(text) // 4
# Combine estimations with bias towards words
total_tokens = (words * 1.5) + (special_chars * 0.5) + char_tokens
return max(int(total_tokens), words)
# Calculate total tokens across all messages
total_tokens = sum(estimate_tokens(msg['content']) for msg in messages)
# Logging for debugging
_LOGGER.debug(
f"Token Estimation: "
f"Messages: {len(messages)}, "
f"Estimated Tokens: {total_tokens}"
)
return total_tokens
except Exception as e: except Exception as e:
_LOGGER.warning(f"Error calculating context tokens: {e}") # Safe fallback with detailed logging
return 0 _LOGGER.warning(
f"Token estimation failed. "
f"Error: {e}. "
f"Using conservative estimation."
)
# Conservative token estimation
return len(messages) * 100
async def async_ask_question( async def async_ask_question(
self, self,
@@ -183,80 +537,132 @@ 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 a question with optional parameters.""" """
Process a question with optional parameters.
This method is a direct wrapper around async_process_question,
allowing flexible AI interaction with optional model, temperature,
and context customization.
Args:
question: The input question or prompt
model: Optional AI model to use
temperature: Optional response creativity level
max_tokens: Optional maximum response length
system_prompt: Optional system-level instruction
context_messages: Optional number of context messages to include
Returns:
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
) )
async def async_process_question( async def async_process_question(
self, self,
question: str, question: str,
model: Optional[str] = None, model: Optional[str] = None,
temperature: Optional[float] = None, temperature: Optional[float] = None,
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,
) -> dict: ) -> dict:
temp_context_messages = context_messages or self.context_messages """
Enhanced question processing with intelligent token management.
"""
try:
self._is_processing = True
await self.async_update_ha_state()
if not question: temp_context_messages = context_messages or self.context_messages
raise ValueError("Question cannot be empty") temp_model = model or self.model
temp_temperature = temperature or self.temperature
temp_max_tokens = max_tokens or self.max_tokens
temp_system_prompt = system_prompt or self._system_prompt
_LOGGER.debug(f"Processing question for instance {self.instance_name}") # Start timing
start_time = dt_util.utcnow()
try: # Prepare messages with system prompt
self._is_processing = True messages = []
await self.async_update_ha_state() if temp_system_prompt:
temp_model = model or self.model
temp_temperature = temperature or self.temperature
temp_max_tokens = max_tokens or self.max_tokens
temp_system_prompt = system_prompt or self._system_prompt
start_time = dt_util.utcnow()
messages = []
if temp_system_prompt:
if self.is_anthropic:
system_content = f"\n\nHuman: {temp_system_prompt}\n\nAssistant: I understand and will follow these instructions."
messages.append({"role": "user", "content": system_content})
else:
messages.append({"role": "system", "content": temp_system_prompt}) messages.append({"role": "system", "content": temp_system_prompt})
# Add conversation history # Context history management
context_history = self._conversation_history[-temp_context_messages:] context_history = self._conversation_history[-temp_context_messages:]
for entry in context_history:
messages.append({"role": "user", "content": entry["question"]})
messages.append({"role": "assistant", "content": entry["response"]})
messages.append({"role": "user", "content": question}) # 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
)
kwargs = { # Dynamic token allocation
"model": temp_model, available_tokens = max(0, temp_max_tokens - context_tokens)
"temperature": temp_temperature,
"max_tokens": temp_max_tokens,
"messages": messages,
}
response = await self.async_process_message(question, **kwargs) # 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}"
)
# Update metrics # Intelligent context reduction
end_time = dt_util.utcnow() while context_tokens > temp_max_tokens // 2 and context_history:
latency = (end_time - start_time).total_seconds() context_history.pop(0)
self._update_metrics(latency, response) 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
)
# Update history # Rebuild messages with trimmed context
self._update_history(question, response) for entry in context_history:
messages.append({"role": "user", "content": entry["question"]})
messages.append({"role": "assistant", "content": entry["response"]})
return response messages.append({"role": "user", "content": question})
except Exception as err: # Detailed token logging
self._handle_error(err) _LOGGER.debug(
raise HomeAssistantError(f"Failed to process question: {err}") f"Token Analysis: "
f"Context Tokens: {context_tokens}, "
f"Max Tokens: {temp_max_tokens}, "
f"Available Tokens: {available_tokens}"
)
finally: # Prepare API call with dynamic token management
self._is_processing = False kwargs = {
await self.async_update_ha_state() "model": temp_model,
"temperature": temp_temperature,
"max_tokens": min(temp_max_tokens, available_tokens),
"messages": messages,
}
# Process message
response = await self.async_process_message(question, **kwargs)
# Update metrics
end_time = dt_util.utcnow()
latency = (end_time - start_time).total_seconds()
self._update_metrics(latency, response)
await self._update_history(question, response)
return response
except Exception as err:
self._handle_error(err)
raise HomeAssistantError(f"Failed to process question: {err}")
finally:
self._is_processing = False
await self.async_update_ha_state()
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."""
@@ -272,7 +678,7 @@ class HATextAICoordinator(DataUpdateCoordinator):
"response": response["content"], "response": response["content"],
"model": kwargs.get("model", self.model), "model": kwargs.get("model", self.model),
"instance": self.instance_name, "instance": self.instance_name,
"error": None "error": None,
} }
return response return response
@@ -283,20 +689,26 @@ class HATextAICoordinator(DataUpdateCoordinator):
async def _process_anthropic_message(self, question: str, **kwargs) -> dict: async def _process_anthropic_message(self, question: str, **kwargs) -> dict:
"""Process message using Anthropic API.""" """Process message using Anthropic API."""
response = await self.client.messages.create( try:
model=kwargs["model"], _LOGGER.debug(f"Anthropic API call: model={kwargs['model']}, max_tokens={kwargs['max_tokens']}")
max_tokens=kwargs["max_tokens"], response = await self.client.messages.create(
messages=kwargs["messages"], model=kwargs["model"],
temperature=kwargs["temperature"], max_tokens=kwargs["max_tokens"],
) messages=kwargs["messages"],
return { temperature=kwargs["temperature"],
"content": response.content[0].text, )
"tokens": { _LOGGER.debug(f"Anthropic response: tokens={response.usage}")
"prompt": response.usage.input_tokens, return {
"completion": response.usage.output_tokens, "content": response.content[0].text,
"total": response.usage.input_tokens + response.usage.output_tokens "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: async def _process_openai_message(self, question: str, **kwargs) -> dict:
"""Process message using OpenAI API.""" """Process message using OpenAI API."""
@@ -313,8 +725,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
"tokens": { "tokens": {
"prompt": response["usage"]["prompt_tokens"], "prompt": response["usage"]["prompt_tokens"],
"completion": response["usage"]["completion_tokens"], "completion": response["usage"]["completion_tokens"],
"total": response["usage"]["total_tokens"] "total": response["usage"]["total_tokens"],
} },
} }
except Exception as e: except Exception as e:
_LOGGER.error(f"Error in OpenAI API call: {str(e)}") _LOGGER.error(f"Error in OpenAI API call: {str(e)}")
@@ -337,35 +749,77 @@ class HATextAICoordinator(DataUpdateCoordinator):
metrics["max_latency"] = max(metrics["max_latency"], latency) metrics["max_latency"] = max(metrics["max_latency"], latency)
metrics["min_latency"] = min(metrics["min_latency"], latency) metrics["min_latency"] = min(metrics["min_latency"], latency)
def _update_history(self, question: str, response: dict) -> None:
"""Update conversation history."""
self._conversation_history.append({
"timestamp": dt_util.utcnow().isoformat(),
"question": question,
"response": response["content"]
})
while len(self._conversation_history) > self.max_history_size:
self._conversation_history.pop(0)
def _handle_error(self, error: Exception) -> None: def _handle_error(self, error: Exception) -> None:
"""Handle error and update metrics.""" """
Enhanced error handling with comprehensive diagnostics.
Captures detailed error information, tracks error metrics,
and provides context for troubleshooting AI processing issues.
"""
self._performance_metrics["total_errors"] += 1 self._performance_metrics["total_errors"] += 1
self._performance_metrics["failed_requests"] += 1 self._performance_metrics["failed_requests"] += 1
self.last_response = { error_details = {
"timestamp": dt_util.utcnow().isoformat(), "timestamp": dt_util.utcnow().isoformat(),
"question": "",
"response": "",
"model": self.model, "model": self.model,
"instance": self.instance_name, "instance": self.instance_name,
"error": str(error) "error_message": str(error),
"error_type": type(error).__name__,
"traceback": traceback.format_exc() if _LOGGER.isEnabledFor(logging.DEBUG) else None,
} }
# Specific error type handling
error_mapping = {
HomeAssistantError: {"is_ha_error": True},
ConnectionError: {
"is_connection_error": True,
"is_rate_limited": True
},
TimeoutError: {"is_timeout": True},
PermissionError: {"is_permission_denied": True},
ValueError: {"is_validation_error": True}
}
for error_type, error_flags in error_mapping.items():
if isinstance(error, error_type):
error_details.update(error_flags)
break
# Update system state based on error type
if error_details.get("is_rate_limited"):
self._is_rate_limited = True
_LOGGER.warning(f"Rate limit detected for {self.instance_name}")
if error_details.get("is_connection_error"):
self.endpoint_status = "unavailable"
self.last_response = error_details
_LOGGER.error(f"AI Processing Error: {error_details}")
# Optional: Add more sophisticated error tracking or notification logic
if _LOGGER.isEnabledFor(logging.DEBUG):
_LOGGER.debug(f"Full Error Traceback: {error_details['traceback']}")
async def async_clear_history(self) -> None: async def async_clear_history(self) -> None:
"""Clear conversation history.""" """
self._conversation_history = [] Asynchronously clear conversation history.
await self.async_update_ha_state()
Removes in-memory history and deletes history file.
"""
try:
# Clear in-memory history
self._conversation_history = []
# Safely remove history file
if os.path.exists(self._history_file):
await asyncio.to_thread(os.remove, self._history_file)
await self.async_update_ha_state()
_LOGGER.info(f"History for {self.instance_name} cleared successfully")
except Exception as e:
_LOGGER.error(f"Error clearing history: {e}")
_LOGGER.debug(traceback.format_exc())
async def async_get_history(self) -> List[Dict[str, str]]: async def async_get_history(self) -> List[Dict[str, str]]:
"""Get conversation history.""" """Get conversation history."""
@@ -375,3 +829,8 @@ class HATextAICoordinator(DataUpdateCoordinator):
"""Set system prompt.""" """Set system prompt."""
self._system_prompt = prompt self._system_prompt = prompt
await self.async_update_ha_state() await self.async_update_ha_state()
async def async_shutdown(self) -> None:
"""Shutdown coordinator."""
_LOGGER.debug(f"Shutting down coordinator for {self.instance_name}")
self.hass.data[DOMAIN].pop(self.instance_name, None)
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 678 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+1 -1
View File
@@ -23,6 +23,6 @@
"single_config_entry": false, "single_config_entry": false,
"ssdp": [], "ssdp": [],
"usb": [], "usb": [],
"version": "2.0.0", "version": "2.0.5-beta",
"zeroconf": [] "zeroconf": []
} }
+75 -30
View File
@@ -1,4 +1,11 @@
"""Sensor platform for HA Text AI.""" """
Sensor platform for HA Text AI.
@license: CC BY-NC-SA 4.0 International
@author: SMKRV
@github: https://github.com/smkrv/ha-text-ai
@source: https://github.com/smkrv/ha-text-ai
"""
import logging import logging
import math import math
from typing import Any, Dict from typing import Any, Dict
@@ -58,25 +65,39 @@ from .const import (
ENTITY_ICON, ENTITY_ICON,
ENTITY_ICON_ERROR, ENTITY_ICON_ERROR,
ENTITY_ICON_PROCESSING, ENTITY_ICON_PROCESSING,
DEFAULT_NAME_PREFIX,
CONF_MAX_HISTORY_SIZE,
) )
from .coordinator import HATextAICoordinator from .coordinator import HATextAICoordinator
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
entry: ConfigEntry, entry: ConfigEntry,
async_add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
) -> None: ) -> None:
"""Set up the HA Text AI sensor.""" """Set up the HA Text AI sensor."""
coordinator = hass.data[DOMAIN][entry.entry_id] _LOGGER.debug(f"Starting sensor setup for entry: {entry.entry_id}")
instance_name = coordinator.instance_name
_LOGGER.debug(f"Setting up sensor with instance: {instance_name}") try:
coordinator = hass.data[DOMAIN][entry.entry_id]
_LOGGER.debug(f"Found coordinator for entry {entry.entry_id}")
sensor = HATextAISensor(coordinator, entry) instance_name = coordinator.instance_name
async_add_entities([sensor], True) _LOGGER.debug(f"Setting up sensor with instance: {instance_name}")
sensor = HATextAISensor(coordinator, entry)
_LOGGER.debug(f"Created sensor instance: {sensor.entity_id}")
async_add_entities([sensor], True)
_LOGGER.debug(f"Added sensor entity: {sensor.entity_id}")
except Exception as err:
_LOGGER.exception(f"Error setting up sensor: {err}")
raise
class HATextAISensor(CoordinatorEntity, SensorEntity): class HATextAISensor(CoordinatorEntity, SensorEntity):
"""HA Text AI Sensor.""" """HA Text AI Sensor."""
@@ -89,19 +110,30 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
config_entry: ConfigEntry, config_entry: ConfigEntry,
) -> None: ) -> None:
"""Initialize the sensor.""" """Initialize the sensor."""
_LOGGER.debug(f"Initializing sensor with config entry: {config_entry.data}")
super().__init__(coordinator) super().__init__(coordinator)
self._config_entry = config_entry self._config_entry = config_entry
self._instance_name = coordinator.instance_name self._instance_name = coordinator.instance_name
self._normalized_name = coordinator.normalized_name
_LOGGER.debug(f"Instance name: {self._instance_name}")
_LOGGER.debug(f"Normalized name: {self._normalized_name}")
self._conversation_history = [] self._conversation_history = []
self._system_prompt = None self._system_prompt = None
self._attr_name = f"HA Text AI {self._instance_name}" self._attr_name = f"HA Text AI {self._instance_name}"
self.entity_id = f"sensor.ha_text_ai_{slugify(self._instance_name)}" self.entity_id = f"sensor.ha_text_ai_{self._normalized_name}"
self._attr_unique_id = f"{config_entry.entry_id}" self._attr_unique_id = f"{config_entry.entry_id}"
_LOGGER.debug(f"Created sensor with entity_id: {self.entity_id}")
_LOGGER.debug(f"Sensor name: {self._attr_name}")
_LOGGER.debug(f"Unique ID: {self._attr_unique_id}")
self.entity_description = SensorEntityDescription( self.entity_description = SensorEntityDescription(
key=f"ha_text_ai_{self._instance_name}", key=f"ha_text_ai_{self._normalized_name.lower()}",
entity_registry_enabled_default=True, entity_registry_enabled_default=True,
) )
@@ -118,13 +150,15 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
self._attr_device_info = DeviceInfo( self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self._attr_unique_id)}, identifiers={(DOMAIN, self._attr_unique_id)},
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="1.0.0",
) )
_LOGGER.debug(f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}") _LOGGER.debug(
f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}"
)
@property @property
def available(self) -> bool: def available(self) -> bool:
@@ -180,11 +214,14 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
data = self.coordinator.data data = self.coordinator.data
attributes = { attributes = {
ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"), ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"),
ATTR_API_PROVIDER: self._config_entry.data.get(CONF_API_PROVIDER, "Unknown"), ATTR_API_PROVIDER: self._config_entry.data.get(
CONF_API_PROVIDER, "Unknown"
),
ATTR_API_STATUS: self._current_state, ATTR_API_STATUS: self._current_state,
ATTR_TOTAL_ERRORS: self._error_count, ATTR_TOTAL_ERRORS: self._error_count,
ATTR_LAST_ERROR: self._last_error, ATTR_LAST_ERROR: self._last_error,
"instance_name": self._instance_name, "instance_name": self._instance_name,
"normalized_name": self._normalized_name,
ATTR_SYSTEM_PROMPT: data.get("system_prompt"), ATTR_SYSTEM_PROMPT: data.get("system_prompt"),
ATTR_IS_PROCESSING: data.get("is_processing", False), ATTR_IS_PROCESSING: data.get("is_processing", False),
ATTR_IS_RATE_LIMITED: data.get("is_rate_limited", False), ATTR_IS_RATE_LIMITED: data.get("is_rate_limited", False),
@@ -199,32 +236,40 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
metrics = data.get("metrics", {}) metrics = data.get("metrics", {})
if isinstance(metrics, dict): if isinstance(metrics, dict):
self._metrics = metrics self._metrics = metrics
attributes.update({ attributes.update(
METRIC_TOTAL_TOKENS: metrics.get("total_tokens", 0), {
METRIC_PROMPT_TOKENS: metrics.get("prompt_tokens", 0), METRIC_TOTAL_TOKENS: metrics.get("total_tokens", 0),
METRIC_COMPLETION_TOKENS: metrics.get("completion_tokens", 0), METRIC_PROMPT_TOKENS: metrics.get("prompt_tokens", 0),
METRIC_SUCCESSFUL_REQUESTS: metrics.get("successful_requests", 0), METRIC_COMPLETION_TOKENS: metrics.get("completion_tokens", 0),
METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0), METRIC_SUCCESSFUL_REQUESTS: metrics.get(
METRIC_AVERAGE_LATENCY: metrics.get("average_latency", 0), "successful_requests", 0
METRIC_MAX_LATENCY: metrics.get("max_latency", 0), ),
METRIC_MIN_LATENCY: metrics.get("min_latency", float("inf")), METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0),
}) METRIC_AVERAGE_LATENCY: metrics.get("average_latency", 0),
METRIC_MAX_LATENCY: metrics.get("max_latency", 0),
METRIC_MIN_LATENCY: metrics.get("min_latency", float("inf")),
}
)
# Add last response # Add last response
last_response = data.get("last_response", {}) last_response = data.get("last_response", {})
if isinstance(last_response, dict): if isinstance(last_response, dict):
self._last_response = last_response self._last_response = last_response
attributes.update({ attributes.update(
ATTR_RESPONSE: last_response.get("response", ""), {
ATTR_QUESTION: last_response.get("question", ""), ATTR_RESPONSE: last_response.get("response", ""),
"last_model": last_response.get("model", ""), ATTR_QUESTION: last_response.get("question", ""),
"last_timestamp": last_response.get("timestamp", ""), "last_model": last_response.get("model", ""),
"last_error": last_response.get("error"), "last_timestamp": last_response.get("timestamp", ""),
}) "last_error": last_response.get("error"),
}
)
# Add performance metrics if available # Add performance metrics if available
if ATTR_PERFORMANCE_METRICS in data: if ATTR_PERFORMANCE_METRICS in data:
attributes[ATTR_PERFORMANCE_METRICS] = data[ATTR_PERFORMANCE_METRICS] attributes[ATTR_PERFORMANCE_METRICS] = data[
ATTR_PERFORMANCE_METRICS
]
# Add API version if available # Add API version if available
if ATTR_API_VERSION in data: if ATTR_API_VERSION in data:
@@ -288,7 +333,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
"Error handling update for %s: %s", "Error handling update for %s: %s",
self.entity_id, self.entity_id,
err, err,
exc_info=True exc_info=True,
) )
self.async_write_ha_state() self.async_write_ha_state()
+98 -4
View File
@@ -40,15 +40,14 @@ ask_question:
min: 1 min: 1
max: 20 max: 20
step: 1 step: 1
mode: box mode: slider
model: model:
name: Model name: Model
description: "Select AI model to use (optional, overrides default setting)" description: "Select AI model to use (optional, overrides default setting)"
required: false required: false
selector: selector:
text: text: {}
multiline: false
temperature: temperature:
name: Temperature name: Temperature
@@ -73,3 +72,98 @@ ask_question:
max: 4096 max: 4096
step: 1 step: 1
mode: box mode: box
clear_history:
name: Clear History
description: >-
Delete all stored questions and responses from the conversation history
fields:
instance:
name: Instance
description: Name of the HA Text AI instance to clear history for
required: true
selector:
entity:
integration: ha_text_ai
domain: sensor
get_history:
name: Get History
description: Retrieve conversation history with optional filtering and sorting
fields:
instance:
name: Instance
description: Name of the HA Text AI instance to get history from
required: true
selector:
entity:
integration: ha_text_ai
domain: sensor
limit:
name: Limit
description: Number of conversations to return (1-100)
required: false
default: 10
selector:
number:
min: 1
max: 100
step: 1
mode: box
filter_model:
name: Filter Model
description: Filter conversations by specific AI model
required: false
selector:
text:
multiline: false
start_date:
name: Start Date
description: Filter conversations starting from this date/time
required: false
selector:
text:
multiline: false
include_metadata:
name: Include Metadata
description: Include additional information like tokens used, response time, etc.
required: false
default: false
selector:
boolean:
sort_order:
name: Sort Order
description: Sort order for results (newest or oldest first)
required: false
default: newest
selector:
select:
options:
- newest
- oldest
set_system_prompt:
name: Set System Prompt
description: Set default system behavior instructions for all future conversations
fields:
instance:
name: Instance
description: Name of the HA Text AI instance to set system prompt for
required: true
selector:
entity:
integration: ha_text_ai
domain: sensor
prompt:
name: System Prompt
description: Instructions that define how the AI should behave and respond
required: true
selector:
text:
multiline: true
+290 -255
View File
@@ -1,261 +1,296 @@
{ {
"config": { "config": {
"step": { "step": {
"provider": { "provider": {
"title": "KI-Anbieter auswählen", "title": "Wählen Sie AI-Anbieter",
"description": "Wählen Sie den KI-Dienst-Anbieter für diese Instanz", "description": "Wählen Sie, welchen AI-Dienstanbieter Sie für diese Instanz verwenden möchten.",
"data": { "data": {
"api_provider": "API-Anbieter", "api_provider": "API-Anbieter",
"context_messages": "Anzahl der zu speichernden Kontextnachrichten (1-20)" "context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
} "max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
},
"user": {
"title": "HA Text AI Instanz konfigurieren",
"description": "Richten Sie eine neue KI-Assistenten-Instanz mit Ihrem ausgewählten Anbieter ein",
"data": {
"name": "Instanzname (z.B. 'GPT Assistent', 'Claude Helfer')",
"api_key": "API-Schlüssel für Authentifizierung",
"model": "Zu verwendendes KI-Modell",
"temperature": "Antwort-Kreativität (0-2, niedriger = fokussierter)",
"max_tokens": "Maximale Antwortlänge (1-4096 Token)",
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
"context_messages": "Anzahl der zu speichernden Kontextnachrichten (1-20)"
}
}
},
"error": {
"name_exists": "Eine Instanz mit diesem Namen existiert bereits",
"invalid_name": "Ungültiger Instanzname",
"invalid_auth": "Authentifizierung fehlgeschlagen - überprüfen Sie Ihren API-Schlüssel",
"invalid_api_key": "Ungültiger API-Schlüssel - bitte überprüfen Sie Ihre Anmeldedaten",
"cannot_connect": "Verbindung zum API-Dienst fehlgeschlagen",
"invalid_model": "Ausgewähltes Modell ist nicht verfügbar",
"rate_limit": "Anfragelimit überschritten",
"context_length": "Kontextlänge überschritten",
"rate_limit_exceeded": "API-Anfragelimit überschritten",
"maintenance": "Dienst ist in Wartung",
"invalid_response": "Ungültige API-Antwort erhalten",
"api_error": "API-Dienst-Fehler aufgetreten",
"timeout": "Anfrage-Zeitüberschreitung",
"invalid_instance": "Ungültige Instanz angegeben",
"unknown": "Unerwarteter Fehler aufgetreten"
} }
},
"provider": {
"title": "Anbieter-Einstellungen",
"description": "Geben Sie die Verbindungsdetails für Ihren gewählten AI-Anbieter an.",
"data": {
"name": "Instanzname (z. B. 'GPT Assistant', 'Claude Helper')",
"api_key": "API-Schlüssel zur Authentifizierung",
"model": "Zu verwendendes AI-Modell",
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
"max_tokens": "Maximale Länge der Antwort (1-4096 Token)",
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
}
},
"user": {
"title": "HA Text AI Instanz konfigurieren",
"description": "Richten Sie eine neue AI-Assistenteninstanz mit Ihrem ausgewählten Anbieter ein.",
"data": {
"name": "Instanzname (z. B. 'GPT Assistant', 'Claude Helper')",
"api_key": "API-Schlüssel zur Authentifizierung",
"model": "Zu verwendendes AI-Modell",
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
"max_tokens": "Maximale Länge der Antwort (1-4096 Token)",
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
"api_provider": "API-Anbieter",
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
}
}
}, },
"options": { "error": {
"step": { "history_storage_error": "Fehler beim Initialisieren des Verlaufspeichers. Überprüfen Sie die Berechtigungen.",
"init": { "history_rotation_error": "Fehler beim Drehen der Verlaufsdatei.",
"title": "Instanzeinstellungen aktualisieren", "history_file_access_error": "Zugriff auf das Verzeichnis für den Verlaufsspeicher nicht möglich.",
"description": "Einstellungen für diese KI-Assistenten-Instanz ändern", "name_exists": "Eine Instanz mit diesem Namen existiert bereits",
"data": { "invalid_name": "Ungültiger Instanzname",
"model": "KI-Modell", "invalid_auth": "Authentifizierung fehlgeschlagen - überprüfen Sie Ihren API-Schlüssel",
"temperature": "Antwort-Kreativität (0-2)", "invalid_api_key": "Ungültiger API-Schlüssel - bitte überprüfen Sie Ihre Anmeldeinformationen",
"max_tokens": "Maximale Antwortlänge (1-4096)", "cannot_connect": "Verbindung zum API-Dienst fehlgeschlagen",
"request_interval": "Minimales Anfragen-Intervall (0,1-60 Sekunden)", "invalid_model": "Ausgewähltes Modell ist nicht verfügbar",
"context_messages": "Anzahl der vorherigen Nachrichten, die in den Kontext einbezogen werden sollen (1-20)" "rate_limit": "Rate-Limit überschritten",
"context_length": "Kontextlänge überschritten",
} "rate_limit_exceeded": "API-Rate-Limit überschritten",
} "maintenance": "Dienst ist in Wartung",
} "invalid_response": "Ungültige API-Antwort erhalten",
"api_error": "Ein Fehler im API-Dienst ist aufgetreten",
"timeout": "Zeitüberschreitung bei der Anfrage",
"invalid_instance": "Ungültige Instanz angegeben",
"unknown": "Unerwarteter Fehler aufgetreten",
"empty": "Name darf nicht leer sein",
"invalid_characters": "Name darf nur Buchstaben, Zahlen, Leerzeichen, Unterstriche und Bindestriche enthalten",
"name_too_long": "Name darf höchstens 50 Zeichen lang sein"
}, },
"services": { "abort": {
"ask_question": { "already_configured": "Instanz bereits konfiguriert"
"name": "Frage stellen (HA Text AI)",
"description": "Senden Sie eine Frage an das KI-Modell und erhalten Sie eine detaillierte Antwort. Die Antwort wird in der Gesprächshistorie gespeichert und kann später abgerufen werden.",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der zu verwendenden HA Text AI Instanz"
},
"question": {
"name": "Frage",
"description": "Ihre Frage oder Eingabeaufforderung für den KI-Assistenten"
},
"context_messages": {
"name": "Kontextnachrichten",
"description": "Anzahl der vorherigen Nachrichten, die in den Kontext einbezogen werden sollen (1-20)"
},
"system_prompt": {
"name": "Systemaufforderung",
"description": "Optionale Systemaufforderung zur Kontexteinstellung für diese spezifische Frage"
},
"model": {
"name": "Modell",
"description": "Wählen Sie das zu verwendende KI-Modell (optional, überschreibt Standardeinstellung)"
},
"temperature": {
"name": "Temperatur",
"description": "Steuert die Antwort-Kreativität (0,0-2,0)"
},
"max_tokens": {
"name": "Max. Token",
"description": "Maximale Länge der Antwort (1-4096 Token)"
}
}
},
"clear_history": {
"name": "Verlauf löschen",
"description": "Alle gespeicherten Fragen und Antworten aus dem Gesprächsverlauf löschen",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der HA Text AI Instanz, für die der Verlauf gelöscht werden soll"
}
}
},
"get_history": {
"name": "Verlauf abrufen",
"description": "Gesprächsverlauf mit optionaler Filterung und Sortierung abrufen",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der HA Text AI Instanz, aus der der Verlauf abgerufen werden soll"
},
"limit": {
"name": "Limit",
"description": "Anzahl der zurückzugebenden Gespräche (1-100)"
},
"filter_model": {
"name": "Modell filtern",
"description": "Gespräche nach bestimmtem KI-Modell filtern"
},
"start_date": {
"name": "Startdatum",
"description": "Gespräche ab diesem Datum/Zeitpunkt filtern"
},
"include_metadata": {
"name": "Metadaten einbeziehen",
"description": "Zusätzliche Informationen wie verwendete Token, Antwortzeit usw. einbeziehen"
},
"sort_order": {
"name": "Sortierreihenfolge",
"description": "Sortierreihenfolge der Ergebnisse (neueste oder älteste zuerst)"
}
}
},
"set_system_prompt": {
"name": "Systemaufforderung festlegen",
"description": "Standardmäßige Systemverhaltensinstruktionen für alle zukünftigen Gespräche festlegen",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der HA Text AI Instanz, für die die Systemaufforderung festgelegt werden soll"
},
"prompt": {
"name": "Systemaufforderung",
"description": "Anweisungen, die definieren, wie sich die KI verhalten und antworten soll"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Bereit",
"processing": "Verarbeitung",
"error": "Fehler",
"disconnected": "Getrennt",
"rate_limited": "Anfragelimit",
"maintenance": "Wartung",
"initializing": "Initialisierung",
"retrying": "Wiederholung",
"queued": "In Warteschlange"
},
"state_attributes": {
"question": {
"name": "Letzte Frage"
},
"response": {
"name": "Letzte Antwort"
},
"model": {
"name": "Aktuelles Modell"
},
"temperature": {
"name": "Temperatur"
},
"max_tokens": {
"name": "Max. Token"
},
"system_prompt": {
"name": "Systemaufforderung"
},
"response_time": {
"name": "Letzte Antwortzeit"
},
"total_responses": {
"name": "Gesamte Antworten"
},
"error_count": {
"name": "Fehleranzahl"
},
"last_error": {
"name": "Letzter Fehler"
},
"api_status": {
"name": "API-Status"
},
"tokens_used": {
"name": "Insgesamt verwendete Token"
},
"average_response_time": {
"name": "Durchschnittliche Antwortzeit"
},
"last_request_time": {
"name": "Letzte Anforderungszeit"
},
"is_processing": {
"name": "Verarbeitungsstatus"
},
"is_rate_limited": {
"name": "Status Anfragelimit"
},
"is_maintenance": {
"name": "Wartungsstatus"
},
"api_version": {
"name": "API-Version"
},
"endpoint_status": {
"name": "Endpunktstatus"
},
"performance_metrics": {
"name": "Leistungsmetriken"
},
"history_size": {
"name": "Verlaufsgröße"
},
"uptime": {
"name": "Betriebszeit"
},
"total_tokens": {
"name": "Gesamte Token"
},
"prompt_tokens": {
"name": "Prompt-Token"
},
"completion_tokens": {
"name": "Abschluss-Token"
},
"successful_requests": {
"name": "Erfolgreiche Anfragen"
},
"failed_requests": {
"name": "Fehlgeschlagene Anfragen"
},
"average_latency": {
"name": "Durchschnittliche Latenz"
},
"max_latency": {
"name": "Maximale Latenz"
},
"min_latency": {
"name": "Minimale Latenz"
}
}
}
}
} }
},
"options": {
"step": {
"init": {
"title": "Instanzeinstellungen aktualisieren",
"description": "Ändern Sie die Einstellungen für diese AI-Assistenteninstanz.",
"data": {
"model": "AI-Modell",
"temperature": "Kreativität der Antwort (0-2)",
"max_tokens": "Maximale Länge der Antwort (1-4096)",
"request_interval": "Minimale Anfrageintervall (0,1-60 Sekunden)",
"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)"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI (kompatibel)",
"anthropic": "Anthropic (kompatibel)"
}
}
},
"services": {
"ask_question": {
"name": "Frage stellen (HA Text AI)",
"description": "Stellen Sie eine Frage an das AI-Modell und erhalten Sie eine detaillierte Antwort. Die Antwort wird im Gesprächsverlauf gespeichert und kann später abgerufen werden.",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der zu verwendenden HA Text AI-Instanz"
},
"question": {
"name": "Frage",
"description": "Ihre Frage oder Aufforderung für den AI-Assistenten"
},
"context_messages": {
"name": "Kontextnachrichten",
"description": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)"
},
"system_prompt": {
"name": "Systemaufforderung",
"description": "Optionale Systemaufforderung zur Festlegung des Kontexts für diese spezifische Frage"
},
"model": {
"name": "Modell",
"description": "Wählen Sie das zu verwendende AI-Modell (optional, überschreibt die Standardeinstellung)"
},
"temperature": {
"name": "Temperatur",
"description": "Steuert die Kreativität der Antwort (0,0-2,0)"
},
"max_tokens": {
"name": "Max Tokens",
"description": "Maximale Länge der Antwort (1-4096 Token)"
}
}
},
"clear_history": {
"name": "Verlauf löschen",
"description": "Löschen Sie alle gespeicherten Fragen und Antworten aus dem Gesprächsverlauf",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der HA Text AI-Instanz, für die der Verlauf gelöscht werden soll"
}
}
},
"get_history": {
"name": "Verlauf abrufen",
"description": "Rufen Sie den Gesprächsverlauf mit optionaler Filterung und Sortierung ab",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der HA Text AI-Instanz, von der der Verlauf abgerufen werden soll"
},
"limit": {
"name": "Limit",
"description": "Anzahl der zurückzugebenden Gespräche (1-100)"
},
"filter_model": {
"name": "Modell filtern",
"description": "Gespräche nach spezifischem AI-Modell filtern"
},
"start_date": {
"name": "Startdatum",
"description": "Gespräche ab diesem Datum/Zeit filtern"
},
"include_metadata": {
"name": "Metadaten einbeziehen",
"description": "Zusätzliche Informationen wie verwendete Tokens, Antwortzeit usw. einbeziehen"
},
"sort_order": {
"name": "Sortierreihenfolge",
"description": "Sortierreihenfolge für die Ergebnisse (neueste oder älteste zuerst)"
}
}
},
"set_system_prompt": {
"name": "Systemaufforderung festlegen",
"description": "Standardverhaltensanweisungen für alle zukünftigen Gespräche festlegen",
"fields": {
"instance": {
"name": "Instanz",
"description": "Name der HA Text AI-Instanz, für die die Systemaufforderung festgelegt werden soll"
},
"prompt": {
"name": "Systemaufforderung",
"description": "Anweisungen, die definieren, wie die AI sich verhalten und antworten soll"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Bereit",
"processing": "Verarbeitung",
"error": "Fehler",
"disconnected": "Getrennt",
"rate_limited": "Rate limitiert",
"maintenance": "Wartung",
"initializing": "Initialisierung",
"retrying": "Wiederholen",
"queued": "In der Warteschlange"
},
"state_attributes": {
"question": {
"name": "Letzte Frage"
},
"response": {
"name": "Letzte Antwort"
},
"model": {
"name": "Aktuelles Modell"
},
"temperature": {
"name": "Temperatur"
},
"max_tokens": {
"name": "Max Tokens"
},
"system_prompt": {
"name": "Systemaufforderung"
},
"response_time": {
"name": "Letzte Antwortzeit"
},
"total_responses": {
"name": "Gesamtantworten"
},
"error_count": {
"name": "Fehleranzahl"
},
"last_error": {
"name": "Letzter Fehler"
},
"api_status": {
"name": "API-Status"
},
"tokens_used": {
"name": "Gesamte verwendete Tokens"
},
"average_response_time": {
"name": "Durchschnittliche Antwortzeit"
},
"last_request_time": {
"name": "Letzte Anfragezeit"
},
"is_processing": {
"name": "Verarbeitungsstatus"
},
"is_rate_limited": {
"name": "Rate-limitiert Status"
},
"is_maintenance": {
"name": "Wartungsstatus"
},
"api_version": {
"name": "API-Version"
},
"endpoint_status": {
"name": "Endpunktstatus"
},
"performance_metrics": {
"name": "Leistungskennzahlen"
},
"history_size": {
"name": "Größe des Verlaufs"
},
"uptime": {
"name": "Betriebszeit"
},
"total_tokens": {
"name": "Gesamte Tokens"
},
"prompt_tokens": {
"name": "Eingabe Tokens"
},
"completion_tokens": {
"name": "Vervollständigungs Tokens"
},
"successful_requests": {
"name": "Erfolgreiche Anfragen"
},
"failed_requests": {
"name": "Fehlgeschlagene Anfragen"
},
"average_latency": {
"name": "Durchschnittliche Latenz"
},
"max_latency": {
"name": "Maximale Latenz"
},
"min_latency": {
"name": "Minimale Latenz"
}
}
}
}
}
} }
+290 -254
View File
@@ -1,260 +1,296 @@
{ {
"config": { "config": {
"step": { "step": {
"provider": { "provider": {
"title": "Select AI Provider", "title": "Select AI Provider",
"description": "Choose which AI service provider to use for this instance", "description": "Choose which AI service provider to use for this instance.",
"data": { "data": {
"api_provider": "API Provider", "api_provider": "API Provider",
"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)"
},
"user": {
"title": "Configure HA Text AI Instance",
"description": "Set up a new AI assistant instance with your selected provider",
"data": {
"name": "Instance name (e.g., 'GPT Assistant', 'Claude Helper')",
"api_key": "API key for authentication",
"model": "AI model to use",
"temperature": "Response creativity (0-2, lower = more focused)",
"max_tokens": "Maximum response length (1-4096 tokens)",
"api_endpoint": "Custom API endpoint URL (optional)",
"request_interval": "Minimum time between requests (0.1-60 seconds)",
"context_messages": "Number of context messages to retain (1-20)"
}
}
},
"error": {
"name_exists": "An instance with this name already exists",
"invalid_name": "Invalid instance name",
"invalid_auth": "Authentication failed - check your API key",
"invalid_api_key": "Invalid API key - please verify your credentials",
"cannot_connect": "Failed to connect to API service",
"invalid_model": "Selected model is not available",
"rate_limit": "Rate limit exceeded",
"context_length": "Context length exceeded",
"rate_limit_exceeded": "API rate limit exceeded",
"maintenance": "Service is under maintenance",
"invalid_response": "Invalid API response received",
"api_error": "API service error occurred",
"timeout": "Request timed out",
"invalid_instance": "Invalid instance specified",
"unknown": "Unexpected error occurred"
} }
},
"provider": {
"title": "Provider Settings",
"description": "Provide connection details for your chosen AI provider.",
"data": {
"name": "Instance name (e.g., 'GPT Assistant', 'Claude Helper')",
"api_key": "API key for authentication",
"model": "AI model to use",
"api_endpoint": "Custom API endpoint URL (optional)",
"temperature": "Response creativity (0-2, lower = more focused)",
"max_tokens": "Maximum response length (1-4096 tokens)",
"request_interval": "Minimum time between requests (0.1-60 seconds)",
"context_messages": "Number of context messages to retain (1-20)",
"max_history_size": "Maximum conversation history size (1-100)"
}
},
"user": {
"title": "Configure HA Text AI Instance",
"description": "Set up a new AI assistant instance with your selected provider.",
"data": {
"name": "Instance name (e.g., 'GPT Assistant', 'Claude Helper')",
"api_key": "API key for authentication",
"model": "AI model to use",
"temperature": "Response creativity (0-2, lower = more focused)",
"max_tokens": "Maximum response length (1-4096 tokens)",
"api_endpoint": "Custom API endpoint URL (optional)",
"api_provider": "API Provider",
"request_interval": "Minimum time between requests (0.1-60 seconds)",
"context_messages": "Number of context messages to retain (1-20)",
"max_history_size": "Maximum conversation history size (1-100)"
}
}
}, },
"options": { "error": {
"step": { "history_storage_error": "Failed to initialize history storage. Check permissions.",
"init": { "history_rotation_error": "Error during history file rotation.",
"title": "Update Instance Settings", "history_file_access_error": "Cannot access history storage directory.",
"description": "Modify settings for this AI assistant instance", "name_exists": "An instance with this name already exists",
"data": { "invalid_name": "Invalid instance name",
"model": "AI model", "invalid_auth": "Authentication failed - check your API key",
"temperature": "Response creativity (0-2)", "invalid_api_key": "Invalid API key - please verify your credentials",
"max_tokens": "Maximum response length (1-4096)", "cannot_connect": "Failed to connect to API service",
"request_interval": "Minimum request interval (0.1-60 seconds)", "invalid_model": "Selected model is not available",
"context_messages": "Number of previous messages to include in context (1-20)" "rate_limit": "Rate limit exceeded",
} "context_length": "Context length exceeded",
} "rate_limit_exceeded": "API rate limit exceeded",
} "maintenance": "Service is under maintenance",
"invalid_response": "Invalid API response received",
"api_error": "API service error occurred",
"timeout": "Request timed out",
"invalid_instance": "Invalid instance specified",
"unknown": "Unexpected error occurred",
"empty": "Name cannot be empty",
"invalid_characters": "Name can only contain letters, numbers, spaces, underscores and hyphens",
"name_too_long": "Name must be 50 characters or less"
}, },
"services": { "abort": {
"ask_question": { "already_configured": "Instance already configured"
"name": "Ask Question (HA Text AI)",
"description": "Send a question to the AI model and receive a detailed response. The response will be stored in the conversation history and can be retrieved later.",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to use"
},
"question": {
"name": "Question",
"description": "Your question or prompt for the AI assistant"
},
"context_messages": {
"name": "Context Messages",
"description": "Number of previous messages to include in context (1-20)"
},
"system_prompt": {
"name": "System Prompt",
"description": "Optional system prompt to set context for this specific question"
},
"model": {
"name": "Model",
"description": "Select AI model to use (optional, overrides default setting)"
},
"temperature": {
"name": "Temperature",
"description": "Controls response creativity (0.0-2.0)"
},
"max_tokens": {
"name": "Max Tokens",
"description": "Maximum length of the response (1-4096 tokens)"
}
}
},
"clear_history": {
"name": "Clear History",
"description": "Delete all stored questions and responses from the conversation history",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to clear history for"
}
}
},
"get_history": {
"name": "Get History",
"description": "Retrieve conversation history with optional filtering and sorting",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to get history from"
},
"limit": {
"name": "Limit",
"description": "Number of conversations to return (1-100)"
},
"filter_model": {
"name": "Filter Model",
"description": "Filter conversations by specific AI model"
},
"start_date": {
"name": "Start Date",
"description": "Filter conversations starting from this date/time"
},
"include_metadata": {
"name": "Include Metadata",
"description": "Include additional information like tokens used, response time, etc."
},
"sort_order": {
"name": "Sort Order",
"description": "Sort order for results (newest or oldest first)"
}
}
},
"set_system_prompt": {
"name": "Set System Prompt",
"description": "Set default system behavior instructions for all future conversations",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to set system prompt for"
},
"prompt": {
"name": "System Prompt",
"description": "Instructions that define how the AI should behave and respond"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Ready",
"processing": "Processing",
"error": "Error",
"disconnected": "Disconnected",
"rate_limited": "Rate Limited",
"maintenance": "Maintenance",
"initializing": "Initializing",
"retrying": "Retrying",
"queued": "Queued"
},
"state_attributes": {
"question": {
"name": "Last Question"
},
"response": {
"name": "Last Response"
},
"model": {
"name": "Current Model"
},
"temperature": {
"name": "Temperature"
},
"max_tokens": {
"name": "Max Tokens"
},
"system_prompt": {
"name": "System Prompt"
},
"response_time": {
"name": "Last Response Time"
},
"total_responses": {
"name": "Total Responses"
},
"error_count": {
"name": "Error Count"
},
"last_error": {
"name": "Last Error"
},
"api_status": {
"name": "API Status"
},
"tokens_used": {
"name": "Total Tokens Used"
},
"average_response_time": {
"name": "Average Response Time"
},
"last_request_time": {
"name": "Last Request Time"
},
"is_processing": {
"name": "Processing Status"
},
"is_rate_limited": {
"name": "Rate Limited Status"
},
"is_maintenance": {
"name": "Maintenance Status"
},
"api_version": {
"name": "API Version"
},
"endpoint_status": {
"name": "Endpoint Status"
},
"performance_metrics": {
"name": "Performance Metrics"
},
"history_size": {
"name": "History Size"
},
"uptime": {
"name": "Uptime"
},
"total_tokens": {
"name": "Total Tokens"
},
"prompt_tokens": {
"name": "Prompt Tokens"
},
"completion_tokens": {
"name": "Completion Tokens"
},
"successful_requests": {
"name": "Successful Requests"
},
"failed_requests": {
"name": "Failed Requests"
},
"average_latency": {
"name": "Average Latency"
},
"max_latency": {
"name": "Maximum Latency"
},
"min_latency": {
"name": "Minimum Latency"
}
}
}
}
} }
},
"options": {
"step": {
"init": {
"title": "Update Instance Settings",
"description": "Modify settings for this AI assistant instance.",
"data": {
"model": "AI model",
"temperature": "Response creativity (0-2)",
"max_tokens": "Maximum response length (1-4096)",
"request_interval": "Minimum request interval (0.1-60 seconds)",
"context_messages": "Number of previous messages to include in context (1-20)",
"max_history_size": "Maximum conversation history size (1-100)"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI (compatible)",
"anthropic": "Anthropic (compatible)"
}
}
},
"services": {
"ask_question": {
"name": "Ask Question (HA Text AI)",
"description": "Send a question to the AI model and receive a detailed response. The response will be stored in the conversation history and can be retrieved later.",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to use"
},
"question": {
"name": "Question",
"description": "Your question or prompt for the AI assistant"
},
"context_messages": {
"name": "Context Messages",
"description": "Number of previous messages to include in context (1-20)"
},
"system_prompt": {
"name": "System Prompt",
"description": "Optional system prompt to set context for this specific question"
},
"model": {
"name": "Model",
"description": "Select AI model to use (optional, overrides default setting)"
},
"temperature": {
"name": "Temperature",
"description": "Controls response creativity (0.0-2.0)"
},
"max_tokens": {
"name": "Max Tokens",
"description": "Maximum length of the response (1-4096 tokens)"
}
}
},
"clear_history": {
"name": "Clear History",
"description": "Delete all stored questions and responses from the conversation history",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to clear history for"
}
}
},
"get_history": {
"name": "Get History",
"description": "Retrieve conversation history with optional filtering and sorting",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to get history from"
},
"limit": {
"name": "Limit",
"description": "Number of conversations to return (1-100)"
},
"filter_model": {
"name": "Filter Model",
"description": "Filter conversations by specific AI model"
},
"start_date": {
"name": "Start Date",
"description": "Filter conversations starting from this date/time"
},
"include_metadata": {
"name": "Include Metadata",
"description": "Include additional information like tokens used, response time, etc."
},
"sort_order": {
"name": "Sort Order",
"description": "Sort order for results (newest or oldest first)"
}
}
},
"set_system_prompt": {
"name": "Set System Prompt",
"description": "Set default system behavior instructions for all future conversations",
"fields": {
"instance": {
"name": "Instance",
"description": "Name of the HA Text AI instance to set system prompt for"
},
"prompt": {
"name": "System Prompt",
"description": "Instructions that define how the AI should behave and respond"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Ready",
"processing": "Processing",
"error": "Error",
"disconnected": "Disconnected",
"rate_limited": "Rate Limited",
"maintenance": "Maintenance",
"initializing": "Initializing",
"retrying": "Retrying",
"queued": "Queued"
},
"state_attributes": {
"question": {
"name": "Last Question"
},
"response": {
"name": "Last Response"
},
"model": {
"name": "Current Model"
},
"temperature": {
"name": "Temperature"
},
"max_tokens": {
"name": "Max Tokens"
},
"system_prompt": {
"name": "System Prompt"
},
"response_time": {
"name": "Last Response Time"
},
"total_responses": {
"name": "Total Responses"
},
"error_count": {
"name": "Error Count"
},
"last_error": {
"name": "Last Error"
},
"api_status": {
"name": "API Status"
},
"tokens_used": {
"name": "Total Tokens Used"
},
"average_response_time": {
"name": "Average Response Time"
},
"last_request_time": {
"name": "Last Request Time"
},
"is_processing": {
"name": "Processing Status"
},
"is_rate_limited": {
"name": "Rate Limited Status"
},
"is_maintenance": {
"name": "Maintenance Status"
},
"api_version": {
"name": "API Version"
},
"endpoint_status": {
"name": "Endpoint Status"
},
"performance_metrics": {
"name": "Performance Metrics"
},
"history_size": {
"name": "History Size"
},
"uptime": {
"name": "Uptime"
},
"total_tokens": {
"name": "Total Tokens"
},
"prompt_tokens": {
"name": "Prompt Tokens"
},
"completion_tokens": {
"name": "Completion Tokens"
},
"successful_requests": {
"name": "Successful Requests"
},
"failed_requests": {
"name": "Failed Requests"
},
"average_latency": {
"name": "Average Latency"
},
"max_latency": {
"name": "Maximum Latency"
},
"min_latency": {
"name": "Minimum Latency"
}
}
}
}
}
} }
@@ -0,0 +1,296 @@
{
"config": {
"step": {
"provider": {
"title": "Seleccionar proveedor de IA",
"description": "Elige qué proveedor de servicio de IA utilizar para esta instancia.",
"data": {
"api_provider": "Proveedor de API",
"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)"
}
},
"provider": {
"title": "Configuración del proveedor",
"description": "Proporciona los detalles de conexión para tu proveedor de IA elegido.",
"data": {
"name": "Nombre de la instancia (por ejemplo, 'Asistente GPT', 'Ayudante Claude')",
"api_key": "Clave API para autenticación",
"model": "Modelo de IA a utilizar",
"api_endpoint": "URL del endpoint de API personalizado (opcional)",
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
"max_tokens": "Longitud máxima de la respuesta (1-4096 tokens)",
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
"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)"
}
},
"user": {
"title": "Configurar instancia de IA de texto de HA",
"description": "Configura una nueva instancia de asistente de IA con tu proveedor seleccionado.",
"data": {
"name": "Nombre de la instancia (por ejemplo, 'Asistente GPT', 'Ayudante Claude')",
"api_key": "Clave API para autenticación",
"model": "Modelo de IA a utilizar",
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
"max_tokens": "Longitud máxima de la respuesta (1-4096 tokens)",
"api_endpoint": "URL del endpoint de API personalizado (opcional)",
"api_provider": "Proveedor de API",
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
"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)"
}
}
},
"error": {
"history_storage_error": "Error al inicializar el almacenamiento del historial. Verifica los permisos.",
"history_rotation_error": "Error durante la rotación del archivo de historial.",
"history_file_access_error": "No se puede acceder al directorio de almacenamiento del historial.",
"name_exists": "Ya existe una instancia con este nombre",
"invalid_name": "Nombre de instancia no válido",
"invalid_auth": "La autenticación falló - verifica tu clave API",
"invalid_api_key": "Clave API no válida - verifica tus credenciales",
"cannot_connect": "Error al conectar con el servicio de API",
"invalid_model": "El modelo seleccionado no está disponible",
"rate_limit": "Límite de tasa excedido",
"context_length": "Longitud del contexto excedida",
"rate_limit_exceeded": "Límite de tasa de API excedido",
"maintenance": "El servicio está en mantenimiento",
"invalid_response": "Respuesta de API no válida recibida",
"api_error": "Ocurrió un error en el servicio de API",
"timeout": "Se agotó el tiempo de la solicitud",
"invalid_instance": "Instancia no válida especificada",
"unknown": "Ocurrió un error inesperado",
"empty": "El nombre no puede estar vacío",
"invalid_characters": "El nombre solo puede contener letras, números, espacios, guiones bajos y guiones",
"name_too_long": "El nombre debe tener 50 caracteres o menos"
},
"abort": {
"already_configured": "Instancia ya configurada"
}
},
"options": {
"step": {
"init": {
"title": "Actualizar configuración de la instancia",
"description": "Modifica la configuración para esta instancia de asistente de IA.",
"data": {
"model": "Modelo de IA",
"temperature": "Creatividad de la respuesta (0-2)",
"max_tokens": "Longitud máxima de la respuesta (1-4096)",
"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)",
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI (compatible)",
"anthropic": "Anthropic (compatible)"
}
}
},
"services": {
"ask_question": {
"name": "Hacer Pregunta (IA de Texto de HA)",
"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": {
"instance": {
"name": "Instancia",
"description": "Nombre de la instancia de IA de Texto de HA a utilizar"
},
"question": {
"name": "Pregunta",
"description": "Tu pregunta o solicitud para el asistente de IA"
},
"context_messages": {
"name": "Mensajes de Contexto",
"description": "Número de mensajes anteriores a incluir en el contexto (1-20)"
},
"system_prompt": {
"name": "Indicaciones del Sistema",
"description": "Indicaciones opcionales para establecer contexto para esta pregunta específica"
},
"model": {
"name": "Modelo",
"description": "Selecciona el modelo de IA a utilizar (opcional, anula la configuración predeterminada)"
},
"temperature": {
"name": "Temperatura",
"description": "Controla la creatividad de la respuesta (0.0-2.0)"
},
"max_tokens": {
"name": "Máx. Tokens",
"description": "Longitud máxima de la respuesta (1-4096 tokens)"
}
}
},
"clear_history": {
"name": "Borrar Historial",
"description": "Elimina todas las preguntas y respuestas almacenadas del historial de conversación",
"fields": {
"instance": {
"name": "Instancia",
"description": "Nombre de la instancia de IA de Texto de HA para borrar el historial"
}
}
},
"get_history": {
"name": "Obtener Historial",
"description": "Recupera el historial de conversación con filtrado y ordenación opcionales",
"fields": {
"instance": {
"name": "Instancia",
"description": "Nombre de la instancia de IA de Texto de HA para obtener historial"
},
"limit": {
"name": "Límite",
"description": "Número de conversaciones a devolver (1-100)"
},
"filter_model": {
"name": "Filtrar Modelo",
"description": "Filtrar conversaciones por modelo de IA específico"
},
"start_date": {
"name": "Fecha de Inicio",
"description": "Filtrar conversaciones a partir de esta fecha/hora"
},
"include_metadata": {
"name": "Incluir Metadatos",
"description": "Incluir información adicional como tokens utilizados, tiempo de respuesta, etc."
},
"sort_order": {
"name": "Orden de Clasificación",
"description": "Orden de clasificación para los resultados (más recientes o más antiguos primero)"
}
}
},
"set_system_prompt": {
"name": "Establecer Indicaciones del Sistema",
"description": "Establecer instrucciones de comportamiento del sistema predeterminadas para todas las futuras conversaciones",
"fields": {
"instance": {
"name": "Instancia",
"description": "Nombre de la instancia de IA de Texto de HA para establecer indicaciones del sistema"
},
"prompt": {
"name": "Indicaciones del Sistema",
"description": "Instrucciones que definen cómo debe comportarse y responder la IA"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Listo",
"processing": "Procesando",
"error": "Error",
"disconnected": "Desconectado",
"rate_limited": "Limitado por tasa",
"maintenance": "Mantenimiento",
"initializing": "Inicializando",
"retrying": "Reintentando",
"queued": "En cola"
},
"state_attributes": {
"question": {
"name": "Última Pregunta"
},
"response": {
"name": "Última Respuesta"
},
"model": {
"name": "Modelo Actual"
},
"temperature": {
"name": "Temperatura"
},
"max_tokens": {
"name": "Máx. Tokens"
},
"system_prompt": {
"name": "Indicaciones del Sistema"
},
"response_time": {
"name": "Último Tiempo de Respuesta"
},
"total_responses": {
"name": "Total de Respuestas"
},
"error_count": {
"name": "Conteo de Errores"
},
"last_error": {
"name": "Último Error"
},
"api_status": {
"name": "Estado de API"
},
"tokens_used": {
"name": "Total de Tokens Usados"
},
"average_response_time": {
"name": "Tiempo de Respuesta Promedio"
},
"last_request_time": {
"name": "Último Tiempo de Solicitud"
},
"is_processing": {
"name": "Estado de Procesamiento"
},
"is_rate_limited": {
"name": "Estado Limitado por Tasa"
},
"is_maintenance": {
"name": "Estado de Mantenimiento"
},
"api_version": {
"name": "Versión de API"
},
"endpoint_status": {
"name": "Estado del Endpoint"
},
"performance_metrics": {
"name": "Métricas de Rendimiento"
},
"history_size": {
"name": "Tamaño del Historial"
},
"uptime": {
"name": "Tiempo de Actividad"
},
"total_tokens": {
"name": "Total de Tokens"
},
"prompt_tokens": {
"name": "Tokens de Solicitud"
},
"completion_tokens": {
"name": "Tokens de Finalización"
},
"successful_requests": {
"name": "Solicitudes Exitosas"
},
"failed_requests": {
"name": "Solicitudes Fallidas"
},
"average_latency": {
"name": "Latencia Promedio"
},
"max_latency": {
"name": "Latencia Máxima"
},
"min_latency": {
"name": "Latencia Mínima"
}
}
}
}
}
}
@@ -0,0 +1,296 @@
{
"config": {
"step": {
"provider": {
"title": "एआई प्रदाता चुनें",
"description": "इस उदाहरण के लिए किस एआई सेवा प्रदाता का उपयोग करना है, चुनें।",
"data": {
"api_provider": "एपीआई प्रदाता",
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
}
},
"provider": {
"title": "प्रदाता सेटिंग्स",
"description": "आपके द्वारा चुने गए एआई प्रदाता के लिए कनेक्शन विवरण प्रदान करें।",
"data": {
"name": "उदाहरण का नाम (जैसे, 'जीपीटी सहायक', 'क्लॉड सहायक')",
"api_key": "प्रमाणीकरण के लिए एपीआई कुंजी",
"model": "उपयोग करने के लिए एआई मॉडल",
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-4096 टोकन)",
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
}
},
"user": {
"title": "एचए टेक्स्ट एआई उदाहरण कॉन्फ़िगर करें",
"description": "अपने चुने हुए प्रदाता के साथ एक नया एआई सहायक उदाहरण सेट करें।",
"data": {
"name": "उदाहरण का नाम (जैसे, 'जीपीटी सहायक', 'क्लॉड सहायक')",
"api_key": "प्रमाणीकरण के लिए एपीआई कुंजी",
"model": "उपयोग करने के लिए एआई मॉडल",
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-4096 टोकन)",
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
"api_provider": "एपीआई प्रदाता",
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
}
}
},
"error": {
"history_storage_error": "इतिहास भंडारण प्रारंभ करने में विफल। अनुमतियों की जांच करें।",
"history_rotation_error": "इतिहास फ़ाइल घुमाने के दौरान त्रुटि।",
"history_file_access_error": "इतिहास भंडारण निर्देशिका तक पहुंच नहीं है।",
"name_exists": "इस नाम के साथ एक उदाहरण पहले से मौजूद है",
"invalid_name": "अमान्य उदाहरण नाम",
"invalid_auth": "प्रमाणीकरण विफल - अपनी एपीआई कुंजी की जांच करें",
"invalid_api_key": "अमान्य एपीआई कुंजी - कृपया अपनी क्रेडेंशियल्स की पुष्टि करें",
"cannot_connect": "एपीआई सेवा से कनेक्ट करने में विफल",
"invalid_model": "चुना हुआ मॉडल उपलब्ध नहीं है",
"rate_limit": "रेट सीमा पार",
"context_length": "संदर्भ लंबाई पार",
"rate_limit_exceeded": "एपीआई रेट सीमा पार",
"maintenance": "सेवा रखरखाव में है",
"invalid_response": "अमान्य एपीआई प्रतिक्रिया प्राप्त हुई",
"api_error": "एपीआई सेवा में त्रुटि हुई",
"timeout": "अनुरोध समय सीमा समाप्त",
"invalid_instance": "अमान्य उदाहरण निर्दिष्ट किया गया",
"unknown": "अप्रत्याशित त्रुटि हुई",
"empty": "नाम खाली नहीं हो सकता",
"invalid_characters": "नाम में केवल अक्षर, अंक, रिक्त स्थान, अंडरस्कोर और हाइफन हो सकते हैं",
"name_too_long": "नाम 50 अक्षरों या उससे कम होना चाहिए"
},
"abort": {
"already_configured": "उदाहरण पहले से कॉन्फ़िगर किया गया है"
}
},
"options": {
"step": {
"init": {
"title": "उदाहरण सेटिंग्स अपडेट करें",
"description": "इस एआई सहायक उदाहरण के लिए सेटिंग्स संशोधित करें।",
"data": {
"model": "एआई मॉडल",
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-4096)",
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI (अनुकूलित)",
"anthropic": "Anthropic (अनुकूलित)"
}
}
},
"services": {
"ask_question": {
"name": "प्रश्न पूछें (एचए टेक्स्ट एआई)",
"description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
"fields": {
"instance": {
"name": "उदाहरण",
"description": "उपयोग करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
},
"question": {
"name": "प्रश्न",
"description": "आपका प्रश्न या एआई सहायक के लिए प्रॉम्प्ट"
},
"context_messages": {
"name": "संदर्भ संदेश",
"description": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)"
},
"system_prompt": {
"name": "सिस्टम प्रॉम्प्ट",
"description": "इस विशेष प्रश्न के लिए संदर्भ सेट करने के लिए वैकल्पिक सिस्टम प्रॉम्प्ट"
},
"model": {
"name": "मॉडल",
"description": "उपयोग करने के लिए एआई मॉडल का चयन करें (वैकल्पिक, डिफ़ॉल्ट सेटिंग को ओवरराइड करता है)"
},
"temperature": {
"name": "तापमान",
"description": "प्रतिक्रिया की रचनात्मकता को नियंत्रित करता है (0.0-2.0)"
},
"max_tokens": {
"name": "अधिकतम टोकन",
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-4096 टोकन)"
}
}
},
"clear_history": {
"name": "इतिहास साफ करें",
"description": "बातचीत के इतिहास से सभी संग्रहीत प्रश्नों और प्रतिक्रियाओं को हटाएं",
"fields": {
"instance": {
"name": "उदाहरण",
"description": "इतिहास साफ़ करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
}
}
},
"get_history": {
"name": "इतिहास प्राप्त करें",
"description": "वैकल्पिक फ़िल्टरिंग और छंटाई के साथ बातचीत का इतिहास प्राप्त करें",
"fields": {
"instance": {
"name": "उदाहरण",
"description": "इतिहास प्राप्त करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
},
"limit": {
"name": "सीमा",
"description": "वापस करने के लिए बातचीत की संख्या (1-100)"
},
"filter_model": {
"name": "फिल्टर मॉडल",
"description": "विशिष्ट एआई मॉडल द्वारा बातचीत को फ़िल्टर करें"
},
"start_date": {
"name": "शुरुआत की तारीख",
"description": "इस दिन/समय से शुरू होने वाली बातचीत को फ़िल्टर करें"
},
"include_metadata": {
"name": "मेटाडेटा शामिल करें",
"description": "उपयोग किए गए टोकन, प्रतिक्रिया समय आदि जैसी अतिरिक्त जानकारी शामिल करें।"
},
"sort_order": {
"name": "छंटाई क्रम",
"description": "परिणामों के लिए छंटाई क्रम (नवीनतम या सबसे पुराना पहले)"
}
}
},
"set_system_prompt": {
"name": "सिस्टम प्रॉम्प्ट सेट करें",
"description": "सभी भविष्य की बातचीत के लिए डिफ़ॉल्ट सिस्टम व्यवहार निर्देश सेट करें",
"fields": {
"instance": {
"name": "उदाहरण",
"description": "सिस्टम प्रॉम्प्ट सेट करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
},
"prompt": {
"name": "सिस्टम प्रॉम्प्ट",
"description": "निर्देश जो यह परिभाषित करते हैं कि एआई को कैसे व्यवहार करना चाहिए और प्रतिक्रिया देनी चाहिए"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "तैयार",
"processing": "प्रसंस्करण",
"error": "त्रुटि",
"disconnected": "असंयुक्त",
"rate_limited": "रेट सीमित",
"maintenance": "रखरखाव",
"initializing": "प्रारंभिककरण",
"retrying": "पुनः प्रयास कर रहा है",
"queued": "क्यू में"
},
"state_attributes": {
"question": {
"name": "अंतिम प्रश्न"
},
"response": {
"name": "अंतिम प्रतिक्रिया"
},
"model": {
"name": "वर्तमान मॉडल"
},
"temperature": {
"name": "तापमान"
},
"max_tokens": {
"name": "अधिकतम टोकन"
},
"system_prompt": {
"name": "सिस्टम प्रॉम्प्ट"
},
"response_time": {
"name": "अंतिम प्रतिक्रिया का समय"
},
"total_responses": {
"name": "कुल प्रतिक्रियाएं"
},
"error_count": {
"name": "त्रुटियों की संख्या"
},
"last_error": {
"name": "अंतिम त्रुटि"
},
"api_status": {
"name": "एपीआई स्थिति"
},
"tokens_used": {
"name": "कुल उपयोग किए गए टोकन"
},
"average_response_time": {
"name": "औसत प्रतिक्रिया समय"
},
"last_request_time": {
"name": "अंतिम अनुरोध का समय"
},
"is_processing": {
"name": "प्रसंस्करण स्थिति"
},
"is_rate_limited": {
"name": "रेट सीमित स्थिति"
},
"is_maintenance": {
"name": "रखरखाव स्थिति"
},
"api_version": {
"name": "एपीआई संस्करण"
},
"endpoint_status": {
"name": "एंडपॉइंट स्थिति"
},
"performance_metrics": {
"name": "प्रदर्शन मैट्रिक्स"
},
"history_size": {
"name": "इतिहास का आकार"
},
"uptime": {
"name": "अपटाइम"
},
"total_tokens": {
"name": "कुल टोकन"
},
"prompt_tokens": {
"name": "प्रॉम्प्ट टोकन"
},
"completion_tokens": {
"name": "पूर्णता टोकन"
},
"successful_requests": {
"name": "सफल अनुरोध"
},
"failed_requests": {
"name": "विफल अनुरोध"
},
"average_latency": {
"name": "औसत विलंबता"
},
"max_latency": {
"name": "अधिकतम विलंबता"
},
"min_latency": {
"name": "न्यूनतम विलंबता"
}
}
}
}
}
}
@@ -0,0 +1,296 @@
{
"config": {
"step": {
"provider": {
"title": "Seleziona fornitore AI",
"description": "Scegli quale fornitore di servizi AI utilizzare per questa istanza.",
"data": {
"api_provider": "Fornitore API",
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
}
},
"provider": {
"title": "Impostazioni fornitore",
"description": "Fornisci i dettagli di connessione per il tuo fornitore di AI scelto.",
"data": {
"name": "Nome dell'istanza (es. 'Assistente GPT', 'Aiuto Claude')",
"api_key": "Chiave API per l'autenticazione",
"model": "Modello AI da utilizzare",
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
"max_tokens": "Lunghezza massima della risposta (1-4096 token)",
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
}
},
"user": {
"title": "Configura istanza AI di testo HA",
"description": "Imposta una nuova istanza di assistente AI con il fornitore selezionato.",
"data": {
"name": "Nome dell'istanza (es. 'Assistente GPT', 'Aiuto Claude')",
"api_key": "Chiave API per l'autenticazione",
"model": "Modello AI da utilizzare",
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
"max_tokens": "Lunghezza massima della risposta (1-4096 token)",
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
"api_provider": "Fornitore API",
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
}
}
},
"error": {
"history_storage_error": "Impossibile inizializzare la memorizzazione della cronologia. Controlla i permessi.",
"history_rotation_error": "Errore durante la rotazione del file di cronologia.",
"history_file_access_error": "Impossibile accedere alla directory di memorizzazione della cronologia.",
"name_exists": "Esiste già un'istanza con questo nome",
"invalid_name": "Nome dell'istanza non valido",
"invalid_auth": "Autenticazione fallita - controlla la tua chiave API",
"invalid_api_key": "Chiave API non valida - verifica le tue credenziali",
"cannot_connect": "Impossibile connettersi al servizio API",
"invalid_model": "Il modello selezionato non è disponibile",
"rate_limit": "Limite di frequenza superato",
"context_length": "Lunghezza del contesto superata",
"rate_limit_exceeded": "Limite di frequenza API superato",
"maintenance": "Il servizio è in manutenzione",
"invalid_response": "Risposta API non valida ricevuta",
"api_error": "Si è verificato un errore nel servizio API",
"timeout": "Richiesta scaduta",
"invalid_instance": "Istanze specificata non valida",
"unknown": "Si è verificato un errore imprevisto",
"empty": "Il nome non può essere vuoto",
"invalid_characters": "Il nome può contenere solo lettere, numeri, spazi, trattini bassi e trattini",
"name_too_long": "Il nome deve essere lungo 50 caratteri o meno"
},
"abort": {
"already_configured": "Istanze già configurata"
}
},
"options": {
"step": {
"init": {
"title": "Aggiorna impostazioni dell'istanza",
"description": "Modifica le impostazioni per questa istanza di assistente AI.",
"data": {
"model": "Modello AI",
"temperature": "Creatività della risposta (0-2)",
"max_tokens": "Lunghezza massima della risposta (1-4096)",
"request_interval": "Intervallo minimo di richiesta (0.1-60 secondi)",
"context_messages": "Numero di messaggi precedenti da includere nel contesto (1-20)",
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI (compatibile)",
"anthropic": "Anthropic (compatibile)"
}
}
},
"services": {
"ask_question": {
"name": "Fai una domanda (HA Text AI)",
"description": "Invia una domanda al modello AI e ricevi una risposta dettagliata. La risposta sarà memorizzata nella cronologia delle conversazioni e potrà essere recuperata in seguito.",
"fields": {
"instance": {
"name": "Istanze",
"description": "Nome dell'istanza HA Text AI da utilizzare"
},
"question": {
"name": "Domanda",
"description": "La tua domanda o richiesta per l'assistente AI"
},
"context_messages": {
"name": "Messaggi di contesto",
"description": "Numero di messaggi precedenti da includere nel contesto (1-20)"
},
"system_prompt": {
"name": "Prompt di sistema",
"description": "Prompt di sistema opzionale per impostare il contesto per questa specifica domanda"
},
"model": {
"name": "Modello",
"description": "Seleziona il modello AI da utilizzare (opzionale, sovrascrive l'impostazione predefinita)"
},
"temperature": {
"name": "Temperatura",
"description": "Controlla la creatività della risposta (0.0-2.0)"
},
"max_tokens": {
"name": "Token massimi",
"description": "Lunghezza massima della risposta (1-4096 token)"
}
}
},
"clear_history": {
"name": "Cancella cronologia",
"description": "Elimina tutte le domande e risposte memorizzate dalla cronologia delle conversazioni",
"fields": {
"instance": {
"name": "Istanze",
"description": "Nome dell'istanza HA Text AI per cui cancellare la cronologia"
}
}
},
"get_history": {
"name": "Ottieni cronologia",
"description": "Recupera la cronologia delle conversazioni con opzioni di filtro e ordinamento",
"fields": {
"instance": {
"name": "Istanze",
"description": "Nome dell'istanza HA Text AI da cui recuperare la cronologia"
},
"limit": {
"name": "Limite",
"description": "Numero di conversazioni da restituire (1-100)"
},
"filter_model": {
"name": "Filtra modello",
"description": "Filtra le conversazioni per modello AI specifico"
},
"start_date": {
"name": "Data di inizio",
"description": "Filtra le conversazioni a partire da questa data/ora"
},
"include_metadata": {
"name": "Includi metadati",
"description": "Includi informazioni aggiuntive come token utilizzati, tempo di risposta, ecc."
},
"sort_order": {
"name": "Ordine di ordinamento",
"description": "Ordine di ordinamento per i risultati (più recenti o più vecchi per primi)"
}
}
},
"set_system_prompt": {
"name": "Imposta prompt di sistema",
"description": "Imposta le istruzioni di comportamento predefinite per tutte le future conversazioni",
"fields": {
"instance": {
"name": "Istanze",
"description": "Nome dell'istanza HA Text AI per cui impostare il prompt di sistema"
},
"prompt": {
"name": "Prompt di sistema",
"description": "Istruzioni che definiscono come l'AI dovrebbe comportarsi e rispondere"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Pronto",
"processing": "Elaborazione",
"error": "Errore",
"disconnected": "Disconnesso",
"rate_limited": "Limite di frequenza",
"maintenance": "Manutenzione",
"initializing": "Inizializzazione",
"retrying": "Riprova",
"queued": "In coda"
},
"state_attributes": {
"question": {
"name": "Ultima domanda"
},
"response": {
"name": "Ultima risposta"
},
"model": {
"name": "Modello attuale"
},
"temperature": {
"name": "Temperatura"
},
"max_tokens": {
"name": "Token massimi"
},
"system_prompt": {
"name": "Prompt di sistema"
},
"response_time": {
"name": "Ultimo tempo di risposta"
},
"total_responses": {
"name": "Risposte totali"
},
"error_count": {
"name": "Conteggio errori"
},
"last_error": {
"name": "Ultimo errore"
},
"api_status": {
"name": "Stato API"
},
"tokens_used": {
"name": "Token totali utilizzati"
},
"average_response_time": {
"name": "Tempo medio di risposta"
},
"last_request_time": {
"name": "Ultimo tempo di richiesta"
},
"is_processing": {
"name": "Stato di elaborazione"
},
"is_rate_limited": {
"name": "Stato limite di frequenza"
},
"is_maintenance": {
"name": "Stato di manutenzione"
},
"api_version": {
"name": "Versione API"
},
"endpoint_status": {
"name": "Stato dell'endpoint"
},
"performance_metrics": {
"name": "Metriche di prestazione"
},
"history_size": {
"name": "Dimensione della cronologia"
},
"uptime": {
"name": "Tempo di attività"
},
"total_tokens": {
"name": "Token totali"
},
"prompt_tokens": {
"name": "Token di prompt"
},
"completion_tokens": {
"name": "Token di completamento"
},
"successful_requests": {
"name": "Richieste riuscite"
},
"failed_requests": {
"name": "Richieste fallite"
},
"average_latency": {
"name": "Latenza media"
},
"max_latency": {
"name": "Latenza massima"
},
"min_latency": {
"name": "Latenza minima"
}
}
}
}
}
}
+290 -254
View File
@@ -1,260 +1,296 @@
{ {
"config": { "config": {
"step": { "step": {
"provider": { "provider": {
"title": "Выбор провайдера ИИ", "title": "Выбор провайдера ИИ",
"description": "Выберите сервис ИИ для этого экземпляра", "description": "Выберите сервис искусственного интеллекта для этого экземпляра.",
"data": { "data": {
"api_provider": "Провайдер API", "api_provider": "Провайдер API",
"context_messages": "Количество сообщений в контексте (1-20)" "context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
} "max_history_size": "Максимальный размер истории разговора (1-100)"
},
"user": {
"title": "Настройка экземпляра HA Text AI",
"description": "Настройте нового помощника ИИ с выбранным провайдером",
"data": {
"name": "Название экземпляра (например, 'GPT Помощник', 'Claude Ассистент')",
"api_key": "API-ключ для аутентификации",
"model": "Модель ИИ для использования",
"temperature": "Креативность ответов (0-2, меньше = более сфокусированно)",
"max_tokens": "Максимальная длина ответа (1-4096 токенов)",
"api_endpoint": "Пользовательский URL-адрес API (необязательно)",
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)"
}
}
},
"error": {
"name_exists": "Экземпляр с таким именем уже существует",
"invalid_name": "Некорректное имя экземпляра",
"invalid_auth": "Ошибка аутентификации - проверьте API-ключ",
"invalid_api_key": "Неверный API-ключ - проверьте учетные данные",
"cannot_connect": "Не удалось подключиться к сервису API",
"invalid_model": "Выбранная модель недоступна",
"rate_limit": "Превышен лимит запросов",
"context_length": "Превышена длина контекста",
"rate_limit_exceeded": "Превышен лимит API",
"maintenance": "Сервис на техническом обслуживании",
"invalid_response": "Получен некорректный ответ API",
"api_error": "Произошла ошибка сервиса API",
"timeout": "Время ожидания истекло",
"invalid_instance": "Указан неверный экземпляр",
"unknown": "Произошла непредвиденная ошибка"
} }
},
"provider": {
"title": "Настройки провайдера",
"description": "Укажите параметры подключения для выбранного провайдера ИИ.",
"data": {
"name": "Название экземпляра (например, 'GPT Помощник', 'Клод Ассистент')",
"api_key": "API-ключ для аутентификации",
"model": "Модель ИИ для использования",
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
"max_tokens": "Максимальная длина ответа (1-4096 токенов)",
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
"max_history_size": "Максимальный размер истории разговора (1-100)"
}
},
"user": {
"title": "Настройка экземпляра текстового ИИ для Home Assistant",
"description": "Настройте новый экземпляр ИИ-помощника с выбранным провайдером.",
"data": {
"name": "Название экземпляра (например, 'GPT Помощник', 'Клод Ассистент')",
"api_key": "API-ключ для аутентификации",
"model": "Модель ИИ для использования",
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
"max_tokens": "Максимальная длина ответа (1-4096 токенов)",
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
"api_provider": "Провайдер API",
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
"max_history_size": "Максимальный размер истории разговора (1-100)"
}
}
}, },
"options": { "error": {
"step": { "history_storage_error": "Не удалось инициализировать хранилище истории. Проверьте разрешения.",
"init": { "history_rotation_error": "Ошибка при ротации файла истории.",
"title": "Обновление настроек экземпляра", "history_file_access_error": "Невозможно получить доступ к директории хранения истории.",
"description": "Измените настройки для этого помощника ИИ", "name_exists": "Экземпляр с таким именем уже существует",
"data": { "invalid_name": "Недопустимое имя экземпляра",
"model": "Модель ИИ", "invalid_auth": "Ошибка аутентификации - проверьте API-ключ",
"temperature": "Креативность ответов (0-2)", "invalid_api_key": "Недопустимый API-ключ - пожалуйста, проверьте учетные данные",
"max_tokens": "Максимальная длина ответа (1-4096)", "cannot_connect": "Не удалось подключиться к сервису API",
"request_interval": "Минимальный интервал запросов (0.1-60 секунд)", "invalid_model": "Выбранная модель недоступна",
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)" "rate_limit": "Превышен лимит запросов",
} "context_length": "Превышена длина контекста",
} "rate_limit_exceeded": "Превышен лимит запросов API",
} "maintenance": "Сервис находится на техническом обслуживании",
"invalid_response": "Получен некорректный ответ API",
"api_error": "Произошла ошибка сервиса API",
"timeout": "Время ожидания запроса истекло",
"invalid_instance": "Указан некорректный экземпляр",
"unknown": "Произошла непредвиденная ошибка",
"empty": "Имя не может быть пустым",
"invalid_characters": "Имя может содержать только буквы, цифры, пробелы, подчеркивания и дефисы",
"name_too_long": "Имя должно быть не длиннее 50 символов"
}, },
"services": { "abort": {
"ask_question": { "already_configured": "Экземпляр уже настроен"
"name": "Задать вопрос (HA Text AI)",
"description": "Отправьте вопрос модели ИИ и получите подробный ответ. Ответ будет сохранен в истории беседы и может быть извлечен позже.",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра HA Text AI для использования"
},
"question": {
"name": "Вопрос",
"description": "Ваш вопрос или запрос помощнику ИИ"
},
"context_messages": {
"name": "Контекстные сообщения",
"description": "Количество предыдущих сообщений для включения в контекст (1-20)"
},
"system_prompt": {
"name": "Системный промпт",
"description": "Необязательный системный промпт для установки контекста для этого конкретного вопроса"
},
"model": {
"name": "Модель",
"description": "Выберите модель ИИ (необязательно, переопределяет настройки по умолчанию)"
},
"temperature": {
"name": "Температура",
"description": "Управляет креативностью ответа (0.0-2.0)"
},
"max_tokens": {
"name": "Максимальное количество токенов",
"description": "Максимальная длина ответа (1-4096 токенов)"
}
}
},
"clear_history": {
"name": "Очистить историю",
"description": "Удалить все сохраненные вопросы и ответы из истории беседы",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра HA Text AI для очистки истории"
}
}
},
"get_history": {
"name": "Получить историю",
"description": "Получить историю беседы с дополнительной фильтрацией и сортировкой",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра HA Text AI для получения истории"
},
"limit": {
"name": "Лимит",
"description": "Количество возвращаемых бесед (1-100)"
},
"filter_model": {
"name": "Фильтр модели",
"description": "Фильтрация бесед по конкретной модели ИИ"
},
"start_date": {
"name": "Начальная дата",
"description": "Фильтрация бесед, начиная с указанной даты/времени"
},
"include_metadata": {
"name": "Включить метаданные",
"description": "Включить дополнительную информацию, например, использованные токены, время ответа и т.д."
},
"sort_order": {
"name": "Порядок сортировки",
"description": "Порядок результатов (сначала новые или старые)"
}
}
},
"set_system_prompt": {
"name": "Установить системный промпт",
"description": "Установить инструкции по умолчанию для поведения ИИ во всех будущих разговорах",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра HA Text AI для установки системного промпта"
},
"prompt": {
"name": "Системный промпт",
"description": "Инструкции, определяющие, как ИИ должен вести себя и отвечать"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Готов",
"processing": "Обработка",
"error": "Ошибка",
"disconnected": "Отключен",
"rate_limited": "Лимит запросов",
"maintenance": "Техническое обслуживание",
"initializing": "Инициализация",
"retrying": "Повторная попытка",
"queued": "В очереди"
},
"state_attributes": {
"question": {
"name": "Последний вопрос"
},
"response": {
"name": "Последний ответ"
},
"model": {
"name": "Текущая модель"
},
"temperature": {
"name": "Температура"
},
"max_tokens": {
"name": "Максимальное количество токенов"
},
"system_prompt": {
"name": "Системный промпт"
},
"response_time": {
"name": "Время последнего ответа"
},
"total_responses": {
"name": "Всего ответов"
},
"error_count": {
"name": "Количество ошибок"
},
"last_error": {
"name": "Последняя ошибка"
},
"api_status": {
"name": "Статус API"
},
"tokens_used": {
"name": "Всего использовано токенов"
},
"average_response_time": {
"name": "Среднее время ответа"
},
"last_request_time": {
"name": "Время последнего запроса"
},
"is_processing": {
"name": "Статус обработки"
},
"is_rate_limited": {
"name": "Статус лимита запросов"
},
"is_maintenance": {
"name": "Статус обслуживания"
},
"api_version": {
"name": "Версия API"
},
"endpoint_status": {
"name": "Статус эндпоинта"
},
"performance_metrics": {
"name": "Показатели производительности"
},
"history_size": {
"name": "Размер истории"
},
"uptime": {
"name": "Время работы"
},
"total_tokens": {
"name": "Всего токенов"
},
"prompt_tokens": {
"name": "Токены промпта"
},
"completion_tokens": {
"name": "Токены завершения"
},
"successful_requests": {
"name": "Успешные запросы"
},
"failed_requests": {
"name": "Неудачные запросы"
},
"average_latency": {
"name": "Средняя задержка"
},
"max_latency": {
"name": "Максимальная задержка"
},
"min_latency": {
"name": "Минимальная задержка"
}
}
}
}
} }
},
"options": {
"step": {
"init": {
"title": "Обновление настроек экземпляра",
"description": "Измените настройки для этого экземпляра ИИ-помощника.",
"data": {
"model": "Модель ИИ",
"temperature": "Креативность ответа (0-2)",
"max_tokens": "Максимальная длина ответа (1-4096)",
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
"max_history_size": "Максимальный размер истории разговора (1-100)"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI (совместимый)",
"anthropic": "Anthropic (совместимый)"
}
}
},
"services": {
"ask_question": {
"name": "Задать вопрос (Текстовый ИИ HA)",
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра текстового ИИ для использования"
},
"question": {
"name": "Вопрос",
"description": "Ваш вопрос или запрос к ИИ-помощнику"
},
"context_messages": {
"name": "Контекстные сообщения",
"description": "Количество предыдущих сообщений для включения в контекст (1-20)"
},
"system_prompt": {
"name": "Системный промпт",
"description": "Необязательный системный промпт для установки контекста для этого конкретного вопроса"
},
"model": {
"name": "Модель",
"description": "Выберите модель ИИ для использования (необязательно, переопределяет настройки по умолчанию)"
},
"temperature": {
"name": "Температура",
"description": "Управление креативностью ответа (0.0-2.0)"
},
"max_tokens": {
"name": "Максимум токенов",
"description": "Максимальная длина ответа (1-4096 токенов)"
}
}
},
"clear_history": {
"name": "Очистить историю",
"description": "Удалить все сохраненные вопросы и ответы из истории разговора",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра текстового ИИ для очистки истории"
}
}
},
"get_history": {
"name": "Получить историю",
"description": "Получить историю разговора с дополнительной фильтрацией и сортировкой",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра текстового ИИ для получения истории"
},
"limit": {
"name": "Лимит",
"description": "Количество разговоров для возврата (1-100)"
},
"filter_model": {
"name": "Фильтр модели",
"description": "Фильтрация разговоров по конкретной модели ИИ"
},
"start_date": {
"name": "Начальная дата",
"description": "Фильтрация разговоров, начиная с указанной даты/времени"
},
"include_metadata": {
"name": "Включить метаданные",
"description": "Включить дополнительную информацию, например, использованные токены, время ответа и т.д."
},
"sort_order": {
"name": "Порядок сортировки",
"description": "Порядок сортировки результатов (сначала новые или старые)"
}
}
},
"set_system_prompt": {
"name": "Установить системный промпт",
"description": "Установить инструкции по умолчанию для поведения ИИ во всех будущих разговорах",
"fields": {
"instance": {
"name": "Экземпляр",
"description": "Название экземпляра текстового ИИ для установки системного промпта"
},
"prompt": {
"name": "Системный промпт",
"description": "Инструкции, определяющие, как ИИ должен вести себя и отвечать"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Готов",
"processing": "Обработка",
"error": "Ошибка",
"disconnected": "Отключен",
"rate_limited": "Лимит запросов",
"maintenance": "Техническое обслуживание",
"initializing": "Инициализация",
"retrying": "Повторная попытка",
"queued": "В очереди"
},
"state_attributes": {
"question": {
"name": "Последний вопрос"
},
"response": {
"name": "Последний ответ"
},
"model": {
"name": "Текущая модель"
},
"temperature": {
"name": "Температура"
},
"max_tokens": {
"name": "Максимум токенов"
},
"system_prompt": {
"name": "Системный промпт"
},
"response_time": {
"name": "Время последнего ответа"
},
"total_responses": {
"name": "Всего ответов"
},
"error_count": {
"name": "Количество ошибок"
},
"last_error": {
"name": "Последняя ошибка"
},
"api_status": {
"name": "Статус API"
},
"tokens_used": {
"name": "Всего использовано токенов"
},
"average_response_time": {
"name": "Среднее время ответа"
},
"last_request_time": {
"name": "Время последнего запроса"
},
"is_processing": {
"name": "Статус обработки"
},
"is_rate_limited": {
"name": "Статус лимита запросов"
},
"is_maintenance": {
"name": "Статус обслуживания"
},
"api_version": {
"name": "Версия API"
},
"endpoint_status": {
"name": "Статус конечной точки"
},
"performance_metrics": {
"name": "Показатели производительности"
},
"history_size": {
"name": "Размер истории"
},
"uptime": {
"name": "Время работы"
},
"total_tokens": {
"name": "Всего токенов"
},
"prompt_tokens": {
"name": "Токены промпта"
},
"completion_tokens": {
"name": "Токены завершения"
},
"successful_requests": {
"name": "Успешные запросы"
},
"failed_requests": {
"name": "Неудачные запросы"
},
"average_latency": {
"name": "Средняя задержка"
},
"max_latency": {
"name": "Максимальная задержка"
},
"min_latency": {
"name": "Минимальная задержка"
}
}
}
}
}
} }
@@ -0,0 +1,296 @@
{
"config": {
"step": {
"provider": {
"title": "Изаберите AI провајдера",
"description": "Изаберите који AI сервис провајдер да користите за ову инстанцу.",
"data": {
"api_provider": "API провајдер",
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
"max_history_size": "Максимална величина историје разговора (1-100)"
}
},
"provider": {
"title": "Подешавања провајдера",
"description": "Обезбедите детаље о вези за изабраног AI провајдера.",
"data": {
"name": "Име инстанце (нпр. 'GPT Асистент', 'Claude Помоћник')",
"api_key": "API кључ за аутентификацију",
"model": "AI модел који ће се користити",
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
"max_tokens": "Максимална дужина одговора (1-4096 токена)",
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
"max_history_size": "Максимална величина историје разговора (1-100)"
}
},
"user": {
"title": "Конфигуришите HA Text AI инстанцу",
"description": "Подесите нову AI асистент инстанцу са изабраним провајдером.",
"data": {
"name": "Име инстанце (нпр. 'GPT Асистент', 'Claude Помоћник')",
"api_key": "API кључ за аутентификацију",
"model": "AI модел који ће се користити",
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
"max_tokens": "Максимална дужина одговора (1-4096 токена)",
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
"api_provider": "API провајдер",
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
"max_history_size": "Максимална величина историје разговора (1-100)"
}
}
},
"error": {
"history_storage_error": "Неуспела инициализација складишта историје. Проверите дозволе.",
"history_rotation_error": "Грешка током ротације историјских датотека.",
"history_file_access_error": "Немогуће приступити директоријуму складишта историје.",
"name_exists": "Инстанца са овим именом већ постоји",
"invalid_name": "Неважеће име инстанце",
"invalid_auth": "Аутентификација није успела - проверите ваш API кључ",
"invalid_api_key": "Неважећи API кључ - молимо проверите ваше акредитиве",
"cannot_connect": "Неуспело повезивање са API сервисом",
"invalid_model": "Изабрани модел није доступан",
"rate_limit": "Пређена граница захтева",
"context_length": "Дужина контекста пређена",
"rate_limit_exceeded": "Пређена граница API захтева",
"maintenance": "Сервис је у одржавању",
"invalid_response": "Примљен неважећи API одговор",
"api_error": "Дошло је до грешке у API сервису",
"timeout": "Време захтева је истекло",
"invalid_instance": "Неважећа инстанца је назначена",
"unknown": "Дошло је до неочекиване грешке",
"empty": "Име не може бити празно",
"invalid_characters": "Име може садржавати само слова, цифре, размаке, подцрта и цртице",
"name_too_long": "Име мора бити 50 знакова или мање"
},
"abort": {
"already_configured": "Инстанца је већ конфигурисана"
}
},
"options": {
"step": {
"init": {
"title": "Ажурирајте подешавања инстанце",
"description": "Измените подешавања за ову AI асистент инстанцу.",
"data": {
"model": "AI модел",
"temperature": "Креативност одговора (0-2)",
"max_tokens": "Максимална дужина одговора (1-4096)",
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
"max_history_size": "Максимална величина историје разговора (1-100)"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI (компатибилан)",
"anthropic": "Anthropic (компатибилан)"
}
}
},
"services": {
"ask_question": {
"name": "Поставите питање (HA Text AI)",
"description": "Пошаљите питање AI моделу и примите детаљан одговор. Одговор ће бити сачуван у историји разговора и може се касније повратити.",
"fields": {
"instance": {
"name": "Инстанца",
"description": "Име HA Text AI инстанце коју ћете користити"
},
"question": {
"name": "Питање",
"description": "Ваше питање или упит за AI асистента"
},
"context_messages": {
"name": "Контекстуалне поруке",
"description": "Број претходних порука које треба укључити у контекст (1-20)"
},
"system_prompt": {
"name": "Системски упит",
"description": "Опционални системски упит за постављање контекста за ово конкретно питање"
},
"model": {
"name": "Модел",
"description": "Изаберите AI модел који ћете користити (опционо, надмашује подразумевану поставку)"
},
"temperature": {
"name": "Температура",
"description": "Контролише креативност одговора (0.0-2.0)"
},
"max_tokens": {
"name": "Максимални токени",
"description": "Максимална дужина одговора (1-4096 токена)"
}
}
},
"clear_history": {
"name": "Обриши историју",
"description": "Избришите све сачуване питања и одговоре из историје разговора",
"fields": {
"instance": {
"name": "Инстанца",
"description": "Име HA Text AI инстанце за коју желите да обришете историју"
}
}
},
"get_history": {
"name": "Добијте историју",
"description": "Повратите историју разговора уз опционално филтрирање и сортирање",
"fields": {
"instance": {
"name": "Инстанца",
"description": "Име HA Text AI инстанце из које желите да добијете историју"
},
"limit": {
"name": "Лимит",
"description": "Број разговора које треба вратити (1-100)"
},
"filter_model": {
"name": "Филтер модел",
"description": "Филтрирајте разговоре по одређеном AI моделу"
},
"start_date": {
"name": "Датум почетка",
"description": "Филтрирајте разговоре који почињу од овог датума/времена"
},
"include_metadata": {
"name": "Укључи метаподатке",
"description": "Укључите додатне информације као што су коришћени токени, време одговора итд."
},
"sort_order": {
"name": "Редослед сортирања",
"description": "Редослед сортирања за резултате (најновији или најстарији први)"
}
}
},
"set_system_prompt": {
"name": "Поставите системски упит",
"description": "Поставите подразумеване инструкције за системско понашање за све будуће разговоре",
"fields": {
"instance": {
"name": "Инстанца",
"description": "Име HA Text AI инстанце за коју желите да поставите системски упит"
},
"prompt": {
"name": "Системски упит",
"description": "Инструкције које дефинишу како AI треба да се понаша и одговара"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "Спремно",
"processing": "Обрада",
"error": "Грешка",
"disconnected": "Прекључено",
"rate_limited": "Ограничење захтева",
"maintenance": "Одржавање",
"initializing": "Инициализује се",
"retrying": "Покушава поново",
"queued": "У реду"
},
"state_attributes": {
"question": {
"name": "Последње питање"
},
"response": {
"name": "Последњи одговор"
},
"model": {
"name": "Тренутни модел"
},
"temperature": {
"name": "Температура"
},
"max_tokens": {
"name": "Максимални токени"
},
"system_prompt": {
"name": "Системски упит"
},
"response_time": {
"name": "Време последњег одговора"
},
"total_responses": {
"name": "Укупно одговора"
},
"error_count": {
"name": "Број грешака"
},
"last_error": {
"name": "Последња грешка"
},
"api_status": {
"name": "Статус API"
},
"tokens_used": {
"name": "Укупно коришћени токени"
},
"average_response_time": {
"name": "Просечно време одговора"
},
"last_request_time": {
"name": "Време последњег захтева"
},
"is_processing": {
"name": "Статус обраде"
},
"is_rate_limited": {
"name": "Статус ограничења захтева"
},
"is_maintenance": {
"name": "Статус одржавања"
},
"api_version": {
"name": "Верзија API"
},
"endpoint_status": {
"name": "Статус крајње тачке"
},
"performance_metrics": {
"name": "Перформансне метрике"
},
"history_size": {
"name": "Величина историје"
},
"uptime": {
"name": "Уптиме"
},
"total_tokens": {
"name": "Укупно токена"
},
"prompt_tokens": {
"name": "Токени упита"
},
"completion_tokens": {
"name": "Токени завршетка"
},
"successful_requests": {
"name": "Успешни захтеви"
},
"failed_requests": {
"name": "Неуспешни захтеви"
},
"average_latency": {
"name": "Просечна латенција"
},
"max_latency": {
"name": "Максимална латенција"
},
"min_latency": {
"name": "Минимална латенција"
}
}
}
}
}
}
@@ -0,0 +1,296 @@
{
"config": {
"step": {
"provider": {
"title": "选择AI提供者",
"description": "选择要用于此实例的AI服务提供者。",
"data": {
"api_provider": "API提供者",
"context_messages": "保留的上下文消息数量(1-20",
"max_history_size": "最大对话历史大小(1-100"
}
},
"provider": {
"title": "提供者设置",
"description": "提供所选AI提供者的连接详细信息。",
"data": {
"name": "实例名称(例如,'GPT助手''Claude助手'",
"api_key": "用于身份验证的API密钥",
"model": "要使用的AI模型",
"api_endpoint": "自定义API端点URL(可选)",
"temperature": "响应创造力(0-2,越低越专注)",
"max_tokens": "最大响应长度(1-4096个标记)",
"request_interval": "请求之间的最小时间(0.1-60秒)",
"context_messages": "保留的上下文消息数量(1-20",
"max_history_size": "最大对话历史大小(1-100"
}
},
"user": {
"title": "配置HA文本AI实例",
"description": "使用所选提供者设置新的AI助手实例。",
"data": {
"name": "实例名称(例如,'GPT助手''Claude助手'",
"api_key": "用于身份验证的API密钥",
"model": "要使用的AI模型",
"temperature": "响应创造力(0-2,越低越专注)",
"max_tokens": "最大响应长度(1-4096个标记)",
"api_endpoint": "自定义API端点URL(可选)",
"api_provider": "API提供者",
"request_interval": "请求之间的最小时间(0.1-60秒)",
"context_messages": "保留的上下文消息数量(1-20",
"max_history_size": "最大对话历史大小(1-100"
}
}
},
"error": {
"history_storage_error": "无法初始化历史存储。检查权限。",
"history_rotation_error": "历史文件轮换时出错。",
"history_file_access_error": "无法访问历史存储目录。",
"name_exists": "具有此名称的实例已存在",
"invalid_name": "无效的实例名称",
"invalid_auth": "身份验证失败 - 检查您的API密钥",
"invalid_api_key": "无效的API密钥 - 请验证您的凭据",
"cannot_connect": "无法连接到API服务",
"invalid_model": "所选模型不可用",
"rate_limit": "超出速率限制",
"context_length": "上下文长度超出限制",
"rate_limit_exceeded": "API速率限制超出",
"maintenance": "服务正在维护中",
"invalid_response": "收到无效的API响应",
"api_error": "发生API服务错误",
"timeout": "请求超时",
"invalid_instance": "指定的实例无效",
"unknown": "发生意外错误",
"empty": "名称不能为空",
"invalid_characters": "名称只能包含字母、数字、空格、下划线和连字符",
"name_too_long": "名称必须少于50个字符"
},
"abort": {
"already_configured": "实例已配置"
}
},
"options": {
"step": {
"init": {
"title": "更新实例设置",
"description": "修改此AI助手实例的设置。",
"data": {
"model": "AI模型",
"temperature": "响应创造力(0-2",
"max_tokens": "最大响应长度(1-4096",
"request_interval": "最小请求间隔(0.1-60秒)",
"context_messages": "要包含在上下文中的先前消息数量(1-20)",
"max_history_size": "最大对话历史大小(1-100"
}
}
}
},
"selector": {
"api_provider": {
"options": {
"openai": "OpenAI(兼容)",
"anthropic": "Anthropic(兼容)"
}
}
},
"services": {
"ask_question": {
"name": "提问(HA文本AI",
"description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。",
"fields": {
"instance": {
"name": "实例",
"description": "要使用的HA文本AI实例名称"
},
"question": {
"name": "问题",
"description": "您对AI助手的问题或提示"
},
"context_messages": {
"name": "上下文消息",
"description": "要包含在上下文中的先前消息数量(1-20)"
},
"system_prompt": {
"name": "系统提示",
"description": "可选的系统提示,用于为此特定问题设置上下文"
},
"model": {
"name": "模型",
"description": "选择要使用的AI模型(可选,覆盖默认设置)"
},
"temperature": {
"name": "温度",
"description": "控制响应创造力(0.0-2.0"
},
"max_tokens": {
"name": "最大标记数",
"description": "响应的最大长度(1-4096个标记)"
}
}
},
"clear_history": {
"name": "清除历史",
"description": "删除对话历史中存储的所有问题和响应",
"fields": {
"instance": {
"name": "实例",
"description": "要清除历史的HA文本AI实例名称"
}
}
},
"get_history": {
"name": "获取历史",
"description": "检索对话历史,可选的过滤和排序",
"fields": {
"instance": {
"name": "实例",
"description": "要获取历史的HA文本AI实例名称"
},
"limit": {
"name": "限制",
"description": "要返回的对话数量(1-100"
},
"filter_model": {
"name": "过滤模型",
"description": "按特定AI模型过滤对话"
},
"start_date": {
"name": "开始日期",
"description": "过滤从此日期/时间开始的对话"
},
"include_metadata": {
"name": "包含元数据",
"description": "包括额外信息,如使用的标记、响应时间等。"
},
"sort_order": {
"name": "排序顺序",
"description": "结果的排序顺序(最新或最旧优先)"
}
}
},
"set_system_prompt": {
"name": "设置系统提示",
"description": "为所有未来的对话设置默认的系统行为指令",
"fields": {
"instance": {
"name": "实例",
"description": "要设置系统提示的HA文本AI实例名称"
},
"prompt": {
"name": "系统提示",
"description": "定义AI应如何行为和响应的指令"
}
}
}
},
"entity": {
"sensor": {
"ha_text_ai": {
"name": "{name}",
"state": {
"ready": "准备就绪",
"processing": "处理中",
"error": "错误",
"disconnected": "已断开连接",
"rate_limited": "速率限制",
"maintenance": "维护中",
"initializing": "初始化中",
"retrying": "重试中",
"queued": "排队中"
},
"state_attributes": {
"question": {
"name": "最后问题"
},
"response": {
"name": "最后响应"
},
"model": {
"name": "当前模型"
},
"temperature": {
"name": "温度"
},
"max_tokens": {
"name": "最大标记数"
},
"system_prompt": {
"name": "系统提示"
},
"response_time": {
"name": "最后响应时间"
},
"total_responses": {
"name": "总响应数"
},
"error_count": {
"name": "错误计数"
},
"last_error": {
"name": "最后错误"
},
"api_status": {
"name": "API状态"
},
"tokens_used": {
"name": "总使用标记数"
},
"average_response_time": {
"name": "平均响应时间"
},
"last_request_time": {
"name": "最后请求时间"
},
"is_processing": {
"name": "处理状态"
},
"is_rate_limited": {
"name": "速率限制状态"
},
"is_maintenance": {
"name": "维护状态"
},
"api_version": {
"name": "API版本"
},
"endpoint_status": {
"name": "端点状态"
},
"performance_metrics": {
"name": "性能指标"
},
"history_size": {
"name": "历史大小"
},
"uptime": {
"name": "正常运行时间"
},
"total_tokens": {
"name": "总标记数"
},
"prompt_tokens": {
"name": "提示标记数"
},
"completion_tokens": {
"name": "完成标记数"
},
"successful_requests": {
"name": "成功请求数"
},
"failed_requests": {
"name": "失败请求数"
},
"average_latency": {
"name": "平均延迟"
},
"max_latency": {
"name": "最大延迟"
},
"min_latency": {
"name": "最小延迟"
}
}
}
}
}
}
+1 -5
View File
@@ -1,9 +1,5 @@
{ {
"name": "HA text AI", "name": "HA text AI",
"render_readme": true, "render_readme": true,
"icon": "mdi:robot", "homeassistant": "2024.11.0"
"domains": ["sensor"],
"homeassistant": "2024.11.0",
"version": "2.0.0",
"documentation": "https://github.com/smkrv/ha-text-ai"
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 923 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

+20 -14
View File
@@ -2,18 +2,24 @@
ha-text-ai/ ha-text-ai/
├── custom_components/ ├── custom_components/
── ha_text_ai/ ── ha_text_ai/
├── __init__.py ├── __init__.py
├── config_flow.py ├── config_flow.py
├── coordinator.py ├── coordinator.py
├── manifest.json ├── manifest.json
├── sensor.py ├── sensor.py
├── services.yaml ├── services.yaml
├── const.py ├── const.py
└── api_client.py └── api_client.py
└── strings/ ├── translations/
├── en.json ├── en.json
├── de.json ├── de.json
└── ru.json └── ru.json
└── icons/
├── icon.png
├── icon@2x.png
├── logo.png
└── logo@2x.png
``` ```